Problema em função para imprimir nomes - Lista encadeade (linguagem C)

Question: Estou tendo problema para imprimir os nomes que eu estou registrando neste programa.
Estou inserindo elementos em um registro: login, nome e valores. Cada novo elemento é inserido em uma lista encadeada.
Por exemplo, se eu fiz três registros distintos como Victor, Mayko e Itamar o programa aparece da seguinte forma:
Nome eh  Itamar.
Nome eh Itamar.
Nome eh Itamar.
Acredito que haja um erro neste código:
void imprime_nomes(lista *l){            // função que imprime os valores
            nodo* p = l->cauda;
                while(p)
                {                                           // Usando while, não é necessário estabelecer um loop para percorrer toda lista.
                printf("Login eh: %s\n", p->dado->login);
                printf("Nome eh: %s\n", p->dado->nome);
                p = p->dir;
                }
    }

Segue código completo:
<stdlib.h>

#include <stdio.h>
#include <stdlib.h>

    typedef struct registro_st{         // sequência de objetos do mesmo tipo
        char login[50];
        char nome[50];
        float valor;
        struct registro *prox;
    } registro;

    typedef struct nodo_st{
        registro *dado;
        struct nodo_st *dir;
        struct nodo_st *esq;
    } nodo;

    typedef struct Lista_st{
        nodo *cabeca;
        nodo *cauda;
        int tamanho;
    } lista;

    nodo* CriarNodo(registro * p){
            nodo* n;
            n = (nodo*)malloc(sizeof(nodo));
            n->dado = p;
            n->dir = NULL;
            n->esq = NULL;
            return n;
    }

    void criarLista(lista *l){
        l->cauda = NULL;
        l->cabeca = NULL;
        l->tamanho = 0;
    }

    void insere_ini(lista *l, registro* dado){
        nodo* novo = (nodo*)malloc(sizeof(nodo));
            if(novo == NULL){
                return 0; //falta de espaço
            };

            novo->dado = dado;
            novo->dir = l->cauda; //antigo primeiro aponta para o próximo
            l->cauda = novo;        // novo nodo recebe ponteiro para começo
            l->tamanho = l->tamanho + 1;
            printf("\n\nEsse foi o registro de num: %d.\n", l->tamanho);
            printf("\nnodo implementado!!\n");
            return novo;
    }

    }

    //FUNÇÕES PARA UTILIZAR NO MAIN

    void imprime_nomes(lista *l){            // função que imprime os valores
            nodo* p = l->cauda;
                while(p)
                {                                           // Usando while, não é necessário estabelecer um loop para percorrer toda lista.
                printf("Login eh: %s\n", p->dado->login);
                printf("Nome eh: %s\n", p->dado->nome);
                p = p->dir;
                }
    }

    void criar_registro(registro *p){                   //função para adicionar os contatos
        printf("Qual login para registro:\n");
        scanf("%s", &p->login);
        printf("Qual o nome do contato:\n");
        scanf("%s", &p->nome);
        printf("Qual valor para registrar:\n");
        scanf("%f", &p->valor);
    }

    int main(){

    registro p1_main;
    lista   p2_main;
    int escolha1 = 99, escolha2;

    criarLista(&p2_main); //cria a lista para salvar os nodos.

    do {
        printf("Qual opção a seguir você deseja realizar?\n\n1-Adicionar Contato\n2-Apresentar nomes registrados\n\n");
        scanf("%d", &escolha1);

    switch(escolha1){
        case 1:
            criar_registro(&p1_main);
            insere_ini(&p2_main, &p1_main);
            break;
        case 2:
            imprime_nomes(&p2_main);

        }
    }

    while ( escolha1 != 0);

    return 0;

    }

Answer: O problema é que você está alocando estaticamente a variável p1_main, logo, toda a vez que tu chama:
criar_registro(&p1_main);
insere_ini(&p2_main, &p1_main);

é o mesmo registro que tu está alterando e adicionando na lista. Você deveria fazer alocação dinâmica do p1_main, como segue:
case 1:
        p1_main = (registro*)calloc(1, sizeof(registro));
        criar_registro(p1_main);
        insere_ini(p2_main, p1_main);

sendo assim, cada vez que for adicionado um novo registro, haverá um novo espaço em memória para ele.


General Topology: pasting lemma problem

Question: Let $\{A_i\}_{i\in I}$ be a collection of subsets of a topological space $X$, such that $X = \bigcup_{i \in I} A_i$. Let $f:X \rightarrow Y$ be a map of topological spaces such that the restriction of $f$ to each $A_i$ (equipped with the subspace topology induced from $X$) is continuous.
Show that if each $A_i$ is closed, and $I$ is finite, then $f$ is continuous.
I understand that this can be solved by the pasting lemma, but I don't see how I can do it using both hypotheses that $A_i$ is closed and $I$ finite.
Answer: Let $F\subseteq Y$ be closed.
Then $f^{-1}(F)\cap A_i$ is closed in $A_i$ for every $i\in I$ because $f$ restricted to $A_i$ is continuous for every $i\in I$.
That means that we can write $f^{-1}(F)\cap A_i=A_i\cap G$ for some closed $G\subseteq X$.
But then $A_i\cap G$ is - as an intersection of closed sets - also closed (here it is used that $A_i$ is closed).
Then $f^{-1}(F)=\bigcup_{i\in I}(f^{-1}(F)\cap A_i)$ is a finite union of closed sets, hence is closed (here it is used that $I$ is finite).
This proves that $f$ is continuous.

General Topology: pasting lemma problem


Probability of a given result with multiples of mixed dice with different number of faces

Question: What is the formula to calculate the probability of getting 41 when I throw two 10-sided dice and four 8-sided dice? I'm looking for an algorithm for the general case of throwing multiples of two sets of differently-faced dice.
Code if same number of faces
Here is some Typescript based on the Python code here that gives the probability if all the dice have the same number of faces:
function probabilityOfN(dice: number, sides: number, n: number): number {
    return Array.from({length: sides}, (_, i) => (1 / sides) * probabilityOfN(dice - 1, sides, n - i - 1))
        .reduce((a, b) => a + b)
}

Missing code if different number of faces
function probabilityOfN(diceA: number, sidesA: number, diceB: number, sidesB: number, n: number): number {
    // ???
}

The question is how to do the calculation for this function? Could be in Python as well.
Test case
Given:

diceA = 2
sidesA = 10
diceB = 4
sidesB = 8
n = 41

Then according to https://dice.clockworkmod.com/ the probability should come out as 0.01
Answer: I would suggest using a generating polynomial to do this. The idea is to represent the contribution of one die towards the total by the power series $(x^1 + x^2 + \dots + x^n)$ where $n$ is the number of faces on the die, then multiplying together one series per die and calculating the coefficient of the power of the sum you're looking for, e.g., the coefficient of $x^{41}$ in your example. Then you can divide by the number of different possible die rolls to get the result as a probability.
This works because expanding all the terms in the product is analogous to listing all the possible combinations of die rolls on your dice, e.g., rolling a 1 on all 6 dice in the question is represented by choosing the $x^1$ term from the series for each die and multiplying these together to get $x^6$. So with the 6 dice in the question, there is only 1 way to roll a total of 6. Similarly, there will be many different rolls that give a sum of 41 and number of these will be equal to the coefficient of $x^{41}$.
You can reduce the degree of combinatorial explosion by discarding terms where the power of $x$ exceeds the target, or cannot reach it based on the remaining terms in the product.
Wolfram Alpha pseudocode:
Coefficient(sum(x^n, n=1 to 10)^2 * sum(x^n, n=1 to 8)^4, x^41) / (10^2 * 8^4)

Sample calculation
Comment: I upvoted. The math behind this is fun, but I think the answer would be better if it explained why that works. I have a feeling that, the way your answer is currently worded, there will be two types of readers: those who already know what you're talking about, and those who will think this is too nerdy for them. That makes me a bit sad because this is a really cool way to solve this problem.
Comment: Saying *find the coefficient of $x^{41}$ in the expansion of $\left(\frac{x}{1-x}\right)^{2+4}\left(\frac{1-x^{10}}{10}\right)^2\left(\frac{1-x^8}{8}\right)^4$* is not quite what I would call fun, though it is perfectly possible
Answer: The brute force method would be to order your dice, enumerate all possible combinations of throws, count the number of "successful" throws and divide by the total number of possible throws. In your particular case, you have $10^2\times 8^4=409,600$ possible throws. A few lines of code tell you that $4,132$ of these show a total of 41. So the probability is indeed $\frac{4,132}{409,600}\approx 0.01$.
In R (sorry, I'm more fluent in R, but this should be understandable):
dice <- c(rep(10,2),rep(8,4))
all_possible_combos <- expand.grid(sapply(dice,function(n)1:n))
sum(rowSums(all_possible_combos)==41)
nrow(all_possible_combos)

The key part is the expand.grid() function that gives you all possible combinations. Here is the analogous histogram to yours:
hist(rowSums(all_possible_combos),breaks=seq(-0.5,sum(dice)+0.5))

This works quickly enough with just six dice, and does not rely on the fact that you have only two types of dice. If you have much more, you may run into a combinatorial explosion. In this case, it may make sense to treat each group separately (see How to easily determine the results distribution for multiple dice?) and sum over the possible ways to split the target number of 41 between the two groups of dice. The question just is whether the gain in performance outweighs the loss in understandability.
Comment: With a lot of dice, it may be easier to use recursion over the dice.  With $d$ dice and at most $s$ sides per die, this should work with complexity $O(d^2s^2)$
Answer: Using @Henry's suggestion of recursion over the dice, below is an R function that will return the full PMF of the sum resulting from rolling a set of fair dice with number of faces of each die given by the vector d.
The function manages combinatorial explosion by summing the probability by each possible cumulative die roll at each iteration. So the length of the PMF after iteration $i$ is:
$$1-i+\sum_{j=1}^id_j$$
I also provide a function employing the fast Fourier transform.

Recursive Algorithm
To illustrate the recursive algorithm, consider rolling three 4-sided dice. Initialize the result by starting with the first die roll.
d <- rep(4, 3) # 3d4
v <- 1:d[1] # initialize the total value of the rolls
p <- rep(1/d[1], d[1]) # the probability of each value

Calculate all possible results of adding the first roll to the second roll and their probabilities.
(mv <- outer(v, 1:d[2], "+"))
#>      [,1] [,2] [,3] [,4]
#> [1,]    2    3    4    5
#> [2,]    3    4    5    6
#> [3,]    4    5    6    7
#> [4,]    5    6    7    8
(mp <- outer(p, rep(1/d[2], d[2])))
#>        [,1]   [,2]   [,3]   [,4]
#> [1,] 0.0625 0.0625 0.0625 0.0625
#> [2,] 0.0625 0.0625 0.0625 0.0625
#> [3,] 0.0625 0.0625 0.0625 0.0625
#> [4,] 0.0625 0.0625 0.0625 0.0625

Aggregate probabilities by value to get the PMF of the first two rolls.
(p <- sapply(split(mp, mv), sum))
#>      2      3      4      5      6      7      8
#> 0.0625 0.1250 0.1875 0.2500 0.1875 0.1250 0.0625
(v <- as.integer(names(p)))
#> [1] 2 3 4 5 6 7 8

Repeat the process by adding the result of the third roll to the first two.
(mv <- outer(v, 1:d[3], "+"))
#>      [,1] [,2] [,3] [,4]
#> [1,]    3    4    5    6
#> [2,]    4    5    6    7
#> [3,]    5    6    7    8
#> [4,]    6    7    8    9
#> [5,]    7    8    9   10
#> [6,]    8    9   10   11
#> [7,]    9   10   11   12
(mp <- outer(p, rep(1/d[3], d[3])))
#>       [,1]     [,2]     [,3]     [,4]
#> 2 0.015625 0.015625 0.015625 0.015625
#> 3 0.031250 0.031250 0.031250 0.031250
#> 4 0.046875 0.046875 0.046875 0.046875
#> 5 0.062500 0.062500 0.062500 0.062500
#> 6 0.046875 0.046875 0.046875 0.046875
#> 7 0.031250 0.031250 0.031250 0.031250
#> 8 0.015625 0.015625 0.015625 0.015625
(p <- sapply(split(mp, mv), sum))
#>        3        4        5        6        7        8        9       10
#> 0.015625 0.046875 0.093750 0.156250 0.187500 0.187500 0.156250 0.093750
#>       11       12
#> 0.046875 0.015625
(v <- as.integer(names(p)))
#>  [1]  3  4  5  6  7  8  9 10 11 12

Notice that the probability matrix is constant across each row, so we can use cumsum instead of outer to speed up the algorithm. We can also wait until the end to generate the vector v.
droll <- function(d) {
  d <- sort(d, TRUE)
  p <- rep(1/d[1], d[1])

  if (length(d) > 1L) {
    for (x in d[-1]) {
      cs <- cumsum(p/x)
      k <- length(p) - x
      p <- c(
        cs[1:x],
        cs[seq.int(x + 1, length.out = k)] - cs[seq_len(k)],
        cs[length(p)] - cs[(k + 1):(length(p) - 1)]
      )
    }
  }

  list(v = length(d):sum(d), p = p)
}

Testing with four 8-sided and two 10-sided dice:
# 4d8 + 2d10
with(
  droll(rep.int(c(8, 10), c(4, 2))),
  barplot(p, names.arg = v, main = "4d8 + 2d10")
)

A larger test:
# 24d6 + 16d8 + 17d10 + 9d12 + 11d20
with(
  droll(rep.int(c(6, 8, 10, 12, 20), c(24, 16, 17, 9, 11))),
  barplot(p, names.arg = v, main = "24d6 + 16d8 + 17d10 + 9d12 + 11d20")
)

Fast Fourier Transform
If many of the dice share the same number of sides, the fast Fourier transform is more performant still, requiring a single transform for each denomination of dice and one inverse transform.
droll.fft <- function(d) {
  n <- table(d)
  d <- as.integer(names(n))
  maxroll <- sum(n*d)
  r <- maxroll - sum(n) + 1
  N <- as.integer(2^ceiling(log2(r)))
  p <- fft(rep.int(c(1/d[1], 0), c(d[1], N - d[1])))^n[1]

  if (length(d) > 1L) {
    for (i in 2:length(d)) {
      p <- p*fft(rep.int(c(1/d[i], 0), c(d[i], N - d[i])))^n[i]
    }
  }

  list(v = sum(n):maxroll, p = Re(fft(p, TRUE)[1:r])/N)
}

microbenchmark::microbenchmark(
  droll = droll(rep.int(c(6, 8, 10, 12, 20), c(24, 16, 17, 9, 11))),
  droll.fft = droll.fft(rep.int(c(6, 8, 10, 12, 20), c(24, 16, 17, 9, 11))),
  check = "equal"
)
#> Unit: microseconds
#>       expr   min     lq     mean median      uq    max neval
#>      droll 658.6 853.90 1201.909 949.20 1039.35 9536.1   100
#>  droll.fft 306.6 332.45  356.929 346.85  372.40  576.2   100

Answer: Based on @Stephan's beautiful answer, here is the Typescript code for posterity:
function probabilityOfNwithDifferentFaces(n: number, ...allDiceAndSides: [number, number][]): number {
    if (!allDiceAndSides.length) return 0
    // trying to avoid combinatorial explosion
    const cleaned = allDiceAndSides.filter(([dice, sides]) => dice > 0 && sides > 0 && dice < 100 && sides <= 100)
        .slice(0, 7)
    if (cleaned.length === 1) return probabilityOfN(cleaned[0][0], cleaned[0][1], n)
    const minResult = cleaned.reduce((acc, [dice]) => acc + dice, 0)
    const maxResult = cleaned.reduce((acc, [dice, sides]) => acc + dice * sides, 0)
    if (n < minResult || n > maxResult) return 0
    cleaned.sort((a, b) => b[1] - a[1])
    const allRepeats: number[] = cleaned.flatMap(([dice, sides]) => Array(dice).fill(sides))
    // console.log(allRepeats)
    const all_possible_combos: number[][] = []
    for (let i = 1; i <= allRepeats.length; i++) {
        const die_combos: number[] = []
        for (let j = 1; j <= allRepeats[i - 1]; j++) {
            die_combos.push(j)
        }
        all_possible_combos.push(die_combos)
    }
    const cartesian_product = (...arrays: any[]) => arrays.reduce(
        (a, b) => a.flatMap((d: any) => b.map((e: any) => [d, e].flat())))
    const all_combinations = cartesian_product(...all_possible_combos)
    // @ts-ignore
    const sum_of_rows = all_combinations.map(row => row.reduce((a, b) => a + b))
    // @ts-ignore
    const count_of_rows_summing_to_n = sum_of_rows.filter(sum => sum === n).length
    // console.log(count_of_rows_summing_to_n)
    const totalPossibleThrows = all_combinations.length
    // console.log(totalPossibleThrows)
    // console.log(probability)
    return count_of_rows_summing_to_n / totalPossibleThrows
}

And some use cases:
function calculateAndReportWithDifferentFaces(n: number, ...allDiceAndSides: [number, number][]) {
    const p = probabilityOfNwithDifferentFaces(n, ...allDiceAndSides)
    const rollString = allDiceAndSides.map(([dice, sides]) => `${dice}d${sides}`).join(" + ")
    console.log(`Got ${p.toFixed(3)} for ${n} with ${rollString}`)
}

function differentFacesProbabilityTest() {
    console.log("=== Individual probabilities with different faces")
    calculateAndReportWithDifferentFaces(2, [1, 10], [1, 6])
    calculateAndReportWithDifferentFaces(9, [1, 10], [1, 6])
    calculateAndReportWithDifferentFaces(14, [1, 10], [1, 6])
    calculateAndReportWithDifferentFaces(15, [1, 10], [1, 6])
    calculateAndReportWithDifferentFaces(16, [1, 10], [1, 6])
    calculateAndReportWithDifferentFaces(31, [2, 10], [4, 8])
    calculateAndReportWithDifferentFaces(41, [2, 10], [4, 8])
    calculateAndReportWithDifferentFaces(41, [4, 8], [2, 10])
    console.log("Same faces check:")
    calculateAndReportWithDifferentFaces(2, [2, 10])
    calculateAndReportWithDifferentFaces(11, [2, 10])
    calculateAndReportWithDifferentFaces(19, [2, 10])
    calculateAndReportWithDifferentFaces(20, [2, 10])
    console.log("Incorrect inputs:")
    calculateAndReportWithDifferentFaces(5, [2, 10], [4, 8])
    calculateAndReportWithDifferentFaces(53, [2, 10], [4, 8])
}


BigDecimal 1.0E+8 / 100000000 with ROUND_HALF_UP is 0

Question: Can some one explain why I get 0 as result for the first line?
System.out.println((new BigDecimal("1.0E+8")).divide(new BigDecimal(100000000), BigDecimal.ROUND_HALF_UP));
System.out.println((new BigDecimal("1.0E+8")).subtract(BigDecimal.ONE).divide(new BigDecimal(100000000), BigDecimal.ROUND_HALF_UP));

0E+7
1

Comment: Why is it "0E+7" and not "0"?
Comment: @user2864740 That *is* the output, but I think OP expected `1`.
Answer: It all has to do with the scales of the BigDecimals involved.
When you specify exponential format in the constructor that takes a String, the scale may be negative.  This indicates that the significant digits don't extend all the way down to unity.
BigDecimal oneEPlus8 = new BigDecimal("1.0E+8");
System.out.println(oneEPlus8.scale());

This outputs -7.
Using the constructor that takes an int yields a scale of 0.
BigDecimal oneHundredMillion = new BigDecimal(100000000);
System.out.println(oneHundredMillion.scale());

This outputs 0.
When you divide BigDecimals, the quotient takes the scale of the object on which divide is called.  So, the quotient's scale is also -7.  The result was calculated to be 1, but in the scale of -7, rounding only gives two options: 0 or 10000000, so ROUND_HALF_UP rounds to 0, giving output of 0E+7.
When you subtract BigDecimals, the difference takes the maximum of the scales of the numbers being subtracted.  So, the difference's scale is 0.  The result is calculated to be 1, and the scale of 0 doesn't force a rounding here.  The output is 1.
To get the result 1 without having to subtract 1, you can subtract 0, or you can call setScale(0) on oneEPlus8.
oneEPlus8 = oneEPlus8.setScale(0);
System.out.println(oneEPlus8.divide(oneHundredMillion, BigDecimal.ROUND_HALF_UP));

This outputs:
1

As an aside, you can use divide(BigDecimal, RoundingMode) to divide specifying a RoundingMode enum instead of the older int constants.


Binding's inside NavigationSplitView detail (TextField, TextEditor)

Question: I'm using a two-column NavigationSplitView. Trying to figure out how to update the data model via .onSubmit modifier and use a TextField view without Binding.constant.
Within the detail section, I have TextField and TextEditor.

How to avoid Binding.contant()? I mean, I need mutation.
This is a correct way to update value property in Model?

I need a single selection in List.
Here's my sample code (70 line's):
struct Model: Identifiable, Hashable {
    var id = UUID()
    var title: String = "Brand new"
    var value: String = ""

    func updateValue() async -> Model {
        return Model(id: id, title: title, value: "The boar  is running through the field happily")
    }
}

final class DataModel: ObservableObject {
    @Published
    var models: [Model] = [
        .init(title: "First", value: "fur"),
        .init(title: "Second", value: "meow"),
        .init(title: "Another", value: "Make SwiftUI, not war")
    ]

    @MainActor
    func updateModel(for model: Model.ID) async -> Void {
        var findModel = models.first { $0.id == model }
        findModel = await findModel?.updateValue()
    }
}

struct ModelView: View {
    @StateObject
    private var dataModel = DataModel()

    @State
    private var listSelection: Model.ID?

    private var selectedModel: Model? {
        guard let selection = listSelection else { return nil }
        return dataModel.models.first { $0.id == selection }
    }

    var body: some View {
        NavigationSplitView {
            List(dataModel.models, selection: $listSelection) { model in
                NavigationLink(model.title, value: model.id)
            }
        } detail: {
            if let selectedModel {
                VStack {
                    TextField("Title", text: .constant(selectedModel.title))
                        .padding()
                        .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 20))
                        .submitLabel(.go)
                        .onSubmit {
                            Task {
                                // Update Model.value by hit `Go`
                                await dataModel.updateModel(for: selectedModel.id)
                            }
                        }
                    TextEditor(text: .constant(selectedModel.value))
                }
                .padding()
                .navigationTitle(selectedModel.title)
            }
        }
    }
}

struct ModelView_Previews: PreviewProvider {
    static var previews: some View {
        ModelView()
            .colorScheme(.light)
    }
}

Comment: Does this answer your question? [How to pass binding to child view in the new NavigationStack.navigationDestination](https://stackoverflow.com/questions/72584427/how-to-pass-binding-to-child-view-in-the-new-navigationstack-navigationdestinati)
Comment: Watch out for a bug with texfield though, if you move cursor to start and type a letter cursor jumps to end, hopefully they'll fix that soon but it has been a while
Comment: @malhal nope. I need `detail` because this is iPadOS app.
Comment: But i have idea about  `func bindingToModel(_ model: Model.ID) -> Binding `
Comment: Put the same thing in detail
Answer: After a couple of days, I realized what I could do.
No one answered the question, so I solved the problem this way.
The final solution is below:
struct Model: Identifiable, Hashable {
    var id = UUID()
    var title: String = "Brand new"
    var value: String = ""

    func updateValue() async -> Model {
        return Model(id: id, title: title, value: "The boar  is running through the field happily")
    }
}

final class DataModel: ObservableObject {
    @Published
    var models: [Model] = [
        .init(title: "First", value: "fur"),
        .init(title: "Second", value: "meow"),
        .init(title: "Another", value: "Make SwiftUI, not war")
    ]

    @MainActor
    func updateModel(for model: Binding<Model>) async -> Void {
        model.wrappedValue = await model.wrappedValue.updateValue()
    }

    func bindingToModel(_ model: Model.ID) -> Binding<Model> {
        Binding<Model> {
            guard let index = self.models.firstIndex(where: { $0.id == model }) else {
                return Model()
            }
            return self.models[index]
        } set: { newModel in
            guard let index = self.models.firstIndex(where: { $0.id == model }) else { return }
            self.models[index] = newModel
        }
    }
}

struct ModelView: View {
    @StateObject
    private var dataModel = DataModel()

    @State
    private var listSelection: Model.ID?

    var body: some View {
        NavigationSplitView {
            List(dataModel.models, selection: $listSelection) { model in
                NavigationLink(model.title, value: model.id)
            }
        } detail: {
            if let listSelection, let bindModel = dataModel.bindingToModel(listSelection)  {
                VStack {
                    TextField("Title", text: bindModel.title)
                        .padding()
                        .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 20))
                        .submitLabel(.go)
                        .onSubmit {
                            Task {
                                // Update Model.value by hit `Go`
                                await dataModel.updateModel(for: bindModel)
                            }
                        }
                    TextEditor(text: bindModel.value)
                }
                .padding()
                .navigationTitle(bindModel.title)
            }
        }
    }
}

Binding’s inside NavigationSplitView detail (TextField, TextEditor)


Passando valores entre funções no PHP

Question: No Laravel é comum trabalharmos com funções como url()->to(string) ou redirect()->route(string) onde essa "segunda função" ->to(string) estende ou retorna um valor para a primeira função url().
Como isso é feito na prática em PHP?
Tentei fazer algo parecido mas não deu certo:
function to($path)
{
    return $path;
}

/**
 * Return the base theme url.
 *
 * @return string
 */
function url(string $path = null)
{
    if(isset($path))
        $path = "/{$path}";

    return get_template_directory_uri() . $path;
}

Execução:
url()->to('teste')

Comment: Possível duplicata de [O que é encadeamento de métodos?](https://pt.stackoverflow.com/questions/105259/o-que-%c3%a9-encadeamento-de-m%c3%a9todos)
Answer: O que acontece é que a função de auxílio url() do Laravel retorna um objeto do tipo Illuminate/Routing/UrlGenerator. Essa classe, por si só, possui o método to, que retorna uma string.
Fazer url()->to("/"), por exemplo, seria o mesmo que fazer:
$url = url();
return $url->to("/");

Onde $url é um objeto do tipo UrlGenerator, citado acima.

Passando valores entre funções no PHP


Collapsible list with a loadmore button to show all the items from this list

Question: I am developing a collapsible list that only shows the first five items and a load more button at first, and when I click the load more button, the full list should be shown. I am using scrollHeight to determine this collapsible list's height and it works fine to show the first five items and the load more button, but after I click the load more button, the height of this collapsible list does not change and the remaining items cannot be displayed due to the height constraint. Does anyone have an idea how to fix it? Thank you so much, I really got stuck here for this whole day.
This is how this collapsible list looks like the collapsible list
This is the code of collapsible list
<code>    const Collapsible = ({ showCard, loaded, children }) => {
      const collapsibleEl = useRef();
      const [scrollHeight, setscrollHeight] = useState();

      useEffect(() => {
        setscrollHeight(collapsibleEl.current.scrollHeight);
        console.log(collapsibleEl.current.scrollHeight);
      }, [loaded, showCard]);
      return (
        <>
          <div
            className={styles.collapsible}
            ref={collapsibleEl}
            style={
              showCard
                ? scrollHeight
                  ? { height: `${scrollHeight + 100}px` }
                  : { height: `${collapsibleEl.current.scrollHeight + 100}px` }
                : { height: "0px" }
            }
          >
            {children}
          </div>
        </>
      );
    };
    export default Collapsible;
</code>
Answer: I have figured it out, all I need to do is to use settimeout.
like this, just give it a little time to get the scrollheight and then re render.
<code>useEffect(() => {
    setTimeout(() => {
      setscrollHeight(collapsibleEl.current.scrollHeight);
    }, 300);
    console.log(collapsibleEl.current.scrollHeight);
  }, [showCard, loaded]);
</code>


Using WLS vs making the residuals homoscedastic to fit OLS regression

Question: I'm convinced that homoscedasticity (of errors) is not an assumption (at least not explicit) for OLS regression. Also, even though WLS is advocated for heteroscedastic errors, OLS is not particularly bad, at least when the heteroscedasticity is limited as has been discussed by Gung in his answer. However, let's say that I encounter, while fitting an OLS using a feature X and an outcome variable y, heteroscedastic errors and go on to transform the variables, say using log transformation on both - X and y - and thus be able to beget fairly homoscedastic errors. Should I now give the results of OLS credence? Is it even a good practice? Or should I use WLS regression instead?
------------------------------------------------------------------------------------------------------------
EDIT:
Earlier I took X and y for integer counts.
Comment: Hi @Ritik. To my knowledge, if you have count data - OLS is misspecified. There are count data based models designed for dealing with heteroskedasticity.
Comment: If your outcome variable is an integer count you probably should be using a generalized linear model appropriate to counts instead of OLS/WLS: Poisson, quasi-Poisson, negative binomial.
Comment: Thank you, didn't consider that while writing the question, I have edited it
Answer: Homoscedasticity is an assumption for the optimality of OLS (i.e., that it is the best linear unbiased estimator of model coefficients) and an assumption for the validity of the usual OLS standard errors.
It is important to note that a model fit using the original features and outc some and a model fit using transformed features and outcome are different models that make different assumptions about the relationship between the features and outcome. The coefficients in one model do not mean the same thing as the coefficients in the other model. The concept of homoscedasticity depends on the specific model used because the errors result from that model. Your first question should be, which model best captures the relationship between the features and the outcome?, or which model allows me to estimate the specific quantity I want to estimate? How to estimate the standard errors comes secondary and is a response to this question.
If your transformed model is the better model (in the sense that it captures the relationship you are after better), then use it, and if the assumption of homoscedasticity of errors is met with this model, then use that assumption. It may still be a good idea to use a robust standard error. As some in the comments have noted, there may be models better than OLS on the transformed variables that suits the data better, like as count models for integer data, such as the (quasi-)Poisson model.
Comment: Thank you @Noah. I wish to point out a few things; 1) I know that the coefficients in one model do not mean the same thing as the coefficient in the other. 2) Couldn't the variability be examined by comparing X against y? In that sense, heteroscedasticity could be examined before employing a model. 3) The question remains, having removed the heteroscedasticity to a huge extent by transforming the data, whether OLS could be preferred over WLS or not? Assume that the variables both before and after transformation are continuous.
Comment: @RitikP.Nayak Heteroscedasticity is of the errors, and errors result from a specific model. Some models will exhibit heteroscedasticity and some won't even when fit to the same data. Indeed, this is exactly the situation you are in. There is no heteroscedasticity "before and after" transforming the data; there is heteroscedasticity with the original model and maybe not with the second model. Whether there was heteroscedasticity in the first model has nothing to do with whether there is (and how it should be dealt with) in the second model; they are different models.
Comment: @RitikP.Nayak so if you are going to use a model on transformed data, it doesn't matter what occurred with the un-transformed data. Transforming data is the same as applying a specific model. If there is heteroscedasticity in a model, address it how you see fit. My preference is to use OLS with robust standard errors if all you care about are the regression coefficients.
Comment: Thank you @Noah, you have 'largely' answered my question. I have upvoted it. I would but like to seek one clarification though. Could you please elaborate your statement; _"If your transformed model is the better model (in the sense that it captures the relationship you are after better), then use it, and if the assumption of homoscedasticity of errors is met with this model, then use that assumption."_
Comment: @RitikP.Nayak Your choice of model should typically be that which represents the relationship you are seeking to describe best. If the relationship is best described by the transformed variable, then you should use the transformed variable. Independently of that, and independently of whether the was heteroscedasticity with some other model fit to the same data, you can evaluate whether heteroscedasticity is a problem in the present model and deal with it how you like. If there is none, then you don't have to deal with it.
Comment: You presented your question as: 1) in a model using the original variables, there is heteroscedasticity, 2) in a model using transformed variables, there is no heteroscedasticity; should I address heteroscedasticity in the second model? But 1) has nothing to do with 2).


linux disable_irq() and local_irq_save()

Question: I have a piece of code where there is:
disable_irq(irq_clk);
local_irq_save(flags);

I found that the disable_irq() disables a specific interrupt, on the other hand local_irq_save() disables all the interrupt.
So I wonder the meaning of the above code.
Answer: This makes sense, because interrupts are disabled at different levels.
disable_irq(irq_clk);

This code disables (masks) interrupt in interrupt controller. If you have disabled interrupt at this level, the interrupt wouldn't be passed to internal interrupt controller pipeline. It would not be prioritized, it would not be routed to the destination CPU.
local_irq_save(flags);

This code disables all interrupts at the level of CPU IRQ interface. Interrupts are passed to CPU IRQ interface after they have passed priority & routing pipeline of the interrupt controller and have been asserted to the CPU.


Which user does the Rules module execute as?

Question: I've set up a rule which is triggered by "after saving a new user account". This rule simply sends an e-mail. The e-mail contains various tokens, one of them is the field [account:field_country].
I've enabled "custom permission" for this field, and through the Field Permissions module I've configured the following permissions :
All users (selected permissions):

Create own value for field Country
View own value for field country.

Moderators (all permissions) :

Create own value for field Country
Edit own value for field Country.
Edit anyone's value for field country.
View own value for field Country.
View anyone's value for field Country.

The problem is : the [account:field_country] gets replaced with an empty string when the rule sends the e-mail. Only when I let all users View anyone's value for field Country does the rule properly replace the token with the actually selected country value.
Why do I need to do this? Which user does the rule module run as since the rule apparently need to View anyone's value for field Country to be able to get the value for that field.
Comment: You might find this interesting: [Rules action to impersonate a user](https://lists.drupal.org/pipermail/development/2013-January/038970.html). And I would think it runs in the context of the current session.
Comment: @J.Reynolds : i agree, I also thought that rules would run in the context of the current session - but then the original permissions should be sufficient.
Comment: Yes I agree. And to expand on your question, what if the Rule is executed in a scheduled Cron job?
Comment: Please enhance your question by including an export of your entire rule to send that eMail. That may help to help you understand what your actual problem in your rule is, and possibly also why your apparent permission work around prevents that problem from happening.
Comment: @J.Reynolds : I'd suggest you undelete your answer, and still refer to the module you mentioned. And add something like a rhetorical question like "it must be the user who triggered the Rule, because if not then what would be the reason-to-exist for this module? Get my point? Alternative: I post my own answer similar to that (together with some extra motivations to (try to) proof my point).
Comment: @Pierre.Vriens Okay I did but the OP's concern still remains: He also believes that the Rule executes in the context of the current user, but then there must be some bug. Refer comment #2 above.
Comment: @J.Reynolds: thx for undelete. And "I" believe that there is a bug in the Rule itself. Not to forget: the apparent security issue is that some value is BLANK (or something). NOT that some value is shown though this user does not have permission. If you're familiar with Rules, does that BLANK ring a bell? Therefor "I" want to see the (exported) rule. Until then, I "trust" Rules security checking is fine.
Answer: And here is a module that could assist:
Rules switch user

This module adds two new Rules actions:

Switch to another user
Switch back from another user

These actions could be useful when you have an operation that you want
  an unprivileged user to use but it fails because the user doesn't have
  sufficient permissions.

Create a fictitious user with sufficient permissions and switch to this user when performing the Rules action and switch back again when done.
EDIT This answer is just a workaround and does not speak to the question directly, namely why the current permissions doled out are not allowing the Rule to execute successfully.
Comment: I'm not asking for a new module which can solve a potential problem with the original module. I'm simply after a reasonable explanation of what's going on here. Either there is a good explanation for this, or it's an error. If it is the latter, then that problem must be fixed - and installing a new module is not a way to fix another module's bugs.
Comment: I somehow agree with @sbrattla that I wouldn't want to add a module like this as a work around. But at the same time I would massage this answer into something like "*Have a look at this module ... not to actually use it (as a work around), but as some kind of indication (proof?) that Rules does (should?) respect the permissions granted to the user who triggered a rule ... Because if that would not be the case, then why would anybody ever need this module?*". Feel free to reword / refine / enhance my suggestion here if you do want to consider it. PS: I would like to see "the" rule in the OP!
Answer: IMO your "issue" (that the value of your field is blank) is because of the event (= "after saving a new user account") you are using, which might simply not be the right event. If this user is still "blocked" (= in case your registration procedure requires admin approval), it could make sense for the Rules module to not show the content of this field yet.
Moreover, have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how Rules works ...).
A possible compromise to avoid these kind of issues, is to transform sending your eMail into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the new user account is for sure saved ... (so that can't be the reason anymore then why that field would still be blank ...).
Using this Rules Component approach, you might even take into consideration that you only want to have this eMail send if the user account is "no longer blocked" (if it is still blocked, add some extra Rules logic to reschedule the same component to re-execute somewhere later on).
And by the way: anything about Rules that uses the Rules Scheduler, runs for sure with "Anonymous" authorizations. There are cases (Rules Actions) for which that auth is insufficient of course (eg: create a new nod is not allowed by Anonymous). Even for these cases there is a way to resolve that also (if you want to know how to do that: post a followup question about it).


Allowing different variance of random intercepts in two different groups of subjects

Question: Is there a way to specify two different random intercept terms for two sub-groups of subjects within a single mixed model? The reason why I'm interested is that it seems that the inter-personal variability of one group of subjects on my task is greater than the inter-personal variability of the other. I'm using lmer and currently specifying the subject factor as a random intercept, which pools all my participants into a single estimate, but I would like to have two separate estimates for the two sub-groups.
Comment: I'm assuming you have some grouping in the data (e.g. repeated measurements on people) other than the two subgroups you were talking about. Call _that_ grouping `ID` and call the binary subgroup indicator `G`. Then, what I was suggesting was something like putting a `(1+G|ID)` term in your model.
Comment: Would a random slope in the group indicator do the job?
Comment: And then the variance of the slope estimate would be indicative of the differences between the variances between the groups?
Comment: It seems that it would not because I'm getting information about the average performance difference between the groups if I specify Group as a fixed factor. If I put Group in a random factor (1|Group), I don't seem to get an answer about the variability of group intercepts from the lmer summary.
Comment: Yes, that's right.
Answer: Using the "weights" argument in R's nlme you can allow for separate variances for each level of a grouping variable (heterogeneous variability).
For examples see:
https://quantdev.ssri.psu.edu/sites/qdev/files/ILD_Ch06_2017_MLMwithHeterogeneousVariance.html
https://fukamilab.github.io/BIO202/03-C-heterogeneity.html


Intent Filter of File Extension for specific activity

Question: I have 2 custom file extensions *.abc and *.xyz.
I have written Intent filters for activities where file having *.abc extension should be opened in Activity1 and *.xyz should be open in Activity2
Those files having serialized java objects and not plain text files.
These are intent filters for those activities in AndroidManifest.xml
<activity
    android:name=".ui.Activity1">
    <intent-filter tools:ignore="AppLinkUrlError">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />

        <data android:mimeType="*/*" />
        <data android:pathPattern=".*\\.abc" />
    </intent-filter>
</activity>
<activity
    android:name=".ui.Activity2">
    <intent-filter tools:ignore="AppLinkUrlError">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />

        <data android:mimeType="*/*" />
        <data android:pathPattern=".*\\.xyz" />
    </intent-filter>
</activity>

I am able to register those extension in android system and my app activities are showing in app chooser of Android System UI
I am printing URI info in logcat as follows
Timber.i(uri.toString())
val mimeType = contentResolver.getType(uri)
Timber.i(mimeType)

Logcat when file opened from WhatsApp
content://com.whatsapp.provider.media/item/5237
application/octet-stream

Logcat when file opened from Solid Explorer
content://pl.solidexplorer2.files/storage/emulated/0/Download/File1.abc
application/*

But when tap either of file (custom extension) it shows both Activities as openable Intent,
for eg. If click on file file1.abc it shows both Intent Filters of extensions as Activity1 and Activity2
I want to make those extensions Activity Specific
like if click on file with extension *.abc it should only have Activity1 in Intent Chooser of Android System UI
I have tried few methods explained in other answers but those doesn't seems to work properly for both file format with content type URI
Some solutions only working when file opened from File Browsers like Solid Explorer but doesn't work when open from apps like WhatsApp which uses MIME type as media
Intent filter below properly worked with Solid Explorer.
It is filtering activity based on custom file extension. But same Intent Filter won't work for Android System's Chooser dialog as it doesn't work in apps like WhatsApp or Gmail which uses Android System's Intent Chooser
<activity
    android:name=".ui.Activity1">
    <intent-filter>
        <data
            android:host="*"
            android:mimeType="*/*"
            android:pathPattern=".*\\.abc"
            android:scheme="content" />

        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>
</activity>
<activity
    android:name=".ui.Activity2">
    <intent-filter>
        <data
            android:host="*"
            android:mimeType="*/*"
            android:pathPattern=".*\\.xyz"
            android:scheme="content" />

        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>
</activity>

Any help will be appreciated.
Thanks.
Comment: Filtering on file extensions will be increasingly useless. There is no requirement for a `Uri` to have a file extension, let alone one that is meaningful. Stop relying on file extensions.
Comment: @CommonsWare so What do you suggest to do? How can I register those Activities for specific file type?
Comment: "How can I register those Activities for specific file type?" -- you don't. You cannot force other developers, let alone users, to use your custom file extensions, or even custom MIME types. IMHO, your decision to use Java serialization was **awful**. Had you used XML or JSON, you at least could have relied on some conventional MIME types. As it stands, whether you go with push (``) or pull (`ACTION_OPEN_DOCUMENT`, `ACTION_GET_CONTENT`), you will have to settle for requesting any type of file, in order to get any results.
Comment: @CommonsWare Actually I'm developing text encryption application so can't directly use XML or JSON like normal plain text data holders.
Yeah I need to settle for requesting any type of file. Isn't there another way to achieve this without depending on user to choose between them every time
Comment: Personally, in this situation, I would use pull: `ACTION_OPEN_DOCUMENT`, plus `ACTION_GET_CONTENT` if your `minSdkVersion` is below 19. These correspond to the "file-open" dialogs that you see in other GUI toolkits. That at least constrains the cases to where the user is in your app and is specifically wanting to load content into it. Using an accept-everything `` means that you keep showing up in places where the user may not want you, and it increases the chances that the user will accidentally choose your app.
Comment: @CommonsWare Yeah I have already implemented that Pull based approach using Storage Access Framework https://developer.android.com/guide/topics/providers/document-provider.html . But to make it more user friendly I wanted to register those activities for Intent Filtering
Comment: IMHO, that will be more user-hostile, given that filtering on custom file extensions and custom MIME types is impractical.
Comment: @CommonsWare Okay. Need to stick to pull based approach. Thanks for help
Answer: There is no direct solution to this issue by using Intent Filters per Activity, So I have created FileIntentActivity which accepts following Intent Filter
<intent-filter
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    tools:ignore="AppLinkUrlError">
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.EDIT" />

    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="*/*" />
</intent-filter>

This FileIntentActivity is used to accept any file format and then decides further action based on file extension converted from Content URI using Cursors referred from this answer
fun getFileName(uri: Uri): String {
    lateinit var cursor: Cursor
    lateinit var result: String
    try {
        cursor = appContext.contentResolver.query(uri, null, null, null, null)
        if(cursor!=null && cursor.moveToFirst()){
            result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
        }
        return result
    } finally {
        cursor.close()
    }
}

private fun getFileType(fileName: String): FileType {
    return when (fileExtension) {
        FileFormats.ABC_FILE_FORMAT -> FileType.ABC
        FileFormats.XYZ_FILE_FORMAT -> FileType.XYZ
        else -> FileType.UNKNOWN
    }
}

And open the Activity1 or Activity2 based on FileType
private fun openActivityByType(fileType: FileType) {
    when (fileType) {
        FileType.ABC -> startActivity1()
        FileType.XYZ -> startActivity2()
        FileType.UNKNOWN -> showFileUnsupportedMessage()
    }
}

This approach at least makes User Interaction less confusing by showing only 1 File Intent Activity instead of Multiple Activities of Single app in Android's Intent Chooser.


Generalizing $\sum \limits_{n=1}^{\infty }n^{2}/x^{n}$ to $\sum \limits_{n=1}^{\infty }n^{p}/x^{n}$

Question: For computing the present worth of an infinite sequence of equally spaced payments $(n^{2})$ I had the need to evaluate
$$\displaystyle\sum_{n=1}^{\infty}\frac{n^{2}}{x^{n}}=\dfrac{x(x+1)}{(x-1)^{3}}\qquad x>1.$$
The method I used was based on the geometric series $\displaystyle\sum_{n=1}^{\infty}x^{n}=\dfrac{x}{1-x}$ differentiating each side followed by a multiplication by $x$, differentiating a second time and multiplying again by $x$. There is at least a second (more difficult) method that is to compute the series partial sums and letting $n$ go to infinity.
Question: Is there a closed form for
$$\displaystyle\sum_{n=1}^{\infty }\dfrac{n^{p}}{x^{n}}\qquad x>1,p\in\mathbb{Z}^{+}\quad ?$$
What is the sketch of its proof in case it exists?
Answer: The general closed form is
$$\displaystyle \sum_{k=1}^{\infty} k^n x^k = \frac{1}{(1 - x)^{n+1}} \left( \sum_{m=0}^{n} A(n, m) x^{m+1} \right)$$
where $A(n, m)$ are the Eulerian numbers.  When I have time I will edit with a few more details.  If you only want the answer for a particular small value of $n$ then see Section 3 of my notes on generating functions.  I will also mention that for a particular value of $n$ one can deduce the answer by using the identity
$$\displaystyle \sum_{k=0}^{\infty} {k+n \choose n} x^k = \frac{1}{(1 - x)^{n+1}}$$
and writing $k^n$ as a linear combination of the polynomials ${k+r \choose r}$ (in $k$), for example using a finite difference table.
Comment: One nice fact is that the sequence of coefficients in the numerator is always palindromic.
Comment: Changing $x\longmapsto 1/x$ and for the exponent $n=2$, this formula gives the same as above!

$\sum_{k=1}^{\infty }k^{2}x^{-k}=\frac{1}{( 1-x^{-1})^{3}}(
A(2,0)x^{-1}+A(2,1)x^{-2}+A(2,2)x^{-3}) $

$=\frac{1}{\left( x-1\right) ^{3}}( x^{2}A(2,0)+xA(2,1)+A(2,2)) $

$=\frac{1}{\left( x-1\right) ^{3}}( x^{2}+x+0) $
Comment: For $n=3$ the sum is $\displaystyle\sum_{k=1}^{\infty}k^{3}x^{k}=\dfrac{x^{3}+4x^{2}+x}{(1-x)^{4}}$
Comment: @Américo Tavares: to clarify, the fact that the coefficients A(n, m) exist can be deduced from general principles, if that is what you mean by "closed form": just repeatedly differentiate with respect to x and multiply by x and you can prove this by induction.  What is surprising is that the coefficients A(n, m) are non-negative integers with nice combinatorial interpretations.
Comment: @Qiaochu Yuan: I am not sure if "closed form" is the correct designation for what I was thinking about. I just wanted to know whether, and how, the series might be evaluated in terms of elementary (rational) functions. Your reply assures it. I used the repeated differentiation and multiplication method to evaluate the $n=3$ case.
Answer: Here is a different look:
The differentiating and multiplying by $x$ gives rise to Stirling Numbers of the Second Kind.
Say you denote the operator of differentiating and multiplying by $x$ as $D_{x}$
Then we have that
$$(D_{x})^{n}f(x) = \sum_{k=1}^{n} s(n,k) f^{(k)}(x) x^{k}$$
where $s(n,k)$ is the stirling number of the second kind and $f^{(k)}(x)$ is the $k^{th}$ derivative of $f(x)$.
This can easily be proven using the identity $$s(n,k) = s(n-1,k-1) + k \cdot s(n-1,k)$$
Here is a table for the Stirling numbers of the second kind (from the wiki page):

n/k   0     1     2     3     4      5      6      7      8      9
0     1
1     0     1
2     0     1     1
3     0     1     3     1
4     0     1     7     6     1
5     0     1     15    25    10     1
6     0     1     31    90    65     15     1
7     0     1     63    301   350    140    21     1
8     0     1     127   966   1701   1050   266    28     1
9     0     1     255   3025  7770   6951   2646   462    36     1

So in your case, we can start with $ f(x) = \frac{1}{1-x}$ and obtain that
$$ \sum_{k=0}^{\infty} k^{n} x^k = \sum_{r=1}^{n} r! \cdot s(n,r) \frac{x^{r}}{(1-x)^{r+1}}$$
For example, in your case for $n=3$ we get
$$\sum_{k=0}^{\infty} k^3 x^k = \frac{1! \cdot 1 \cdot x}{(1-x)^2} + \frac{2! \cdot 3 \cdot x^2}{(1-x)^3} + \frac{3! \cdot 1 \cdot x^3}{(1-x)^4}$$
$$ = \frac{x(1-x)^2 + 6x^{2}(1-x) + 6x^3}{(1-x)^4} $$
$$ = \frac{x^3 + 4x^2 + x}{(1-x)^4} $$
Comment: Nice approach. I'm a bit partial to using $\left\{\begin{matrix}n\\\\k\end{matrix}\right\}$ instead of $s(n,k)$, but still, +1.
Answer: According to mathworld The $n^{th}$ moment of the geometric distribution with parameter $p$, which is $ \sum p (1-p)^n n^k $ can be expressed in terms of the polylogarithm function.
Comment: To be precise, the polylogarithm is given by the infinite series $\mathrm{Li}_n(z)=\sum_{j=1}^\infty \frac{z^j}{j^n}$ ; you can transform the series for the nth moment to match the form of the polylogarithm.


Swift app for solving factors of numbers and display

Question: i'm new the forum and also new to the swift language. I've been playing around with xcode and wanted to create an app that uses a fenceloop to display the factors of a number as a "solution." The app currently uses a label to display, a text for input, and a button to initiate. I have what i think to be functioning code but i can't see to get it to work because from what i understand, i have to convert the input that's a string into an int. If anyone has any ideas how to get this working; since i feel like i've done what i can.
The problem in particular i am getting is it is saying that "Cannot convert value of type 'UITextField!; to expected argument type 'Int'. What i intend to happen is that on the button click, it solves for the factors of whatever is in the text box and displays it as a string in the label. Any help is appreciated!
import UIKit

class ViewController: UIViewController {

@IBOutlet var input1 : UITextField!
@IBOutlet var label : UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func printFactors(n: Int) {
    var result: String = ""
    for i in 1...n {
        guard n % i == 0  else {continue}
        result += i == 1 ? "1" : " and \(i)"
    }
    print(result)

    let outputText = printFactors(n: input1)
    label.text = outputText
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Comment: Your IBAction can't have the signature you have at the moment. If there is a parameter, it must be the button.
Comment: any advice you/fixes you'd suggest or areas i should adjust? thank you for the heads up by the way!
Comment: It looks like you've connected the action target of your UITextField to the printFactors(n: Int) function. This is the wrong type signature for the target which will need to be something like printFactors(sender: AnyObject?). Then cast sender to an Int with something like let n = Int(sender).
Comment: @closetCoder No, you can't cast `sender` to an `Int`. Sender will be a `UIButton`.
Comment: @rmaddy, do you think you could show me what the fixes are in this case? are you able to edit my text on this website?
Comment: Well according to the error message it's a UITextField, so Int(sender.text!) should work.
Comment: @closetCoder But the `IBAction` is for the button handler so `sender` will be the button.
Comment: You are right, of course. :)
Answer: You have a lot of issues and confusion in your printFactors method. Lets split it up and setup things properly.
First, make a separate method to do the math:
func calculateFactors(n: Int) -> String {
    var result: String = ""
    for i in 1...n {
        guard n % i == 0  else {continue}
        result += i == 1 ? "1" : " and \(i)"
    }
    print(result)

    return result
}

Now lets setup the button action:
@IBAction func factorAction(sender: UIButton) {
    if let text = input1.text {
         if let num = Int(text) {
             let factor = calculateFactors(n: num)
             label.text = factor
         } else {
             // Show the user that the entered text isn't a number
         }
    } else {
         // There's no text
    }
}

Setup your button to use the new factoryAction: method instead of the old printFactors: method.
Comment: when you say set it up separately, do you mean as different files? or can i put it all in viewcontroller.swift?
Comment: You can put it in the same Swift file. It really depends on how it will be used. If more than one class needs to perform the same calculation I would suggest creating a "math util" class and putting your common math code there so it can be reused throughout your app.
Comment: so i pasted the @IBAction (i hope you dont mind that i did) and i got two errors. consequent declarations on the same line must be separated by a ';' and the other was "expected declaration." i'm running version 8.0 of xcode if that helps.
Comment: I had a typo - forgot the `func` keyword next to `factorAction` and had an extra colon (many years of Objective-c). See if that fixes it.
Comment: thank you so, so much. I see where i was going wrong in my attempt to simplify things. I've gone and connected the story board to the elements. It successfully compiles and launches; but when i enter "24," nothing displays in the label and i get a thread error on the line with "if let num = Int(text) {" - any idea why this would happen?
Comment: nevermind! once again, thank you so much rmaddy; i learned a lot. It seemed that my instance of xcode had an error in it and that was causing the thread issue. I restarted it and it worked!
Comment: any resources you'd recommend for really understanding the fundamentals of swift?
Comment: Sure. Start with Apple's [The Swift Programming Language](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/) book. Glad to help. Please don't forget to accept answers that solve your issue.
Answer: Swift 3
Can reduce this code down to two lines with some functional magic.
func factors(of number: Int) -> [Int] {
    return (1...number).filter { number % $0 == 0 }
}

print(factors(of: 24))

Comment: this will crash if `of number` is `0`. Maybe: `func factor(_ n: Int) -> [Int] { n != 0 ? (1...n).filter { n % $0 == 0 } : [] }`


Onchange function in dropdownlist and displaying corresponding value in textbox

Question: I want to display the value in texbox field everytime when I select data in dropdown field. Since I am a beginner to asp.net mvc its getting bit confused for me. Everytime I select some value from Item DropDown I want to display ts corresponding price value in price column.
Here is my view:
 @model Resturant.Model.OrderItemDTO
@using Resturant.Model;
@{
    ViewBag.Title = "AddItem";
}

    @{ Html.RenderPartial("OrderPartials/_OrderSidebar");}

        @{ Html.RenderPartial("OrderPartials/_OrderTopbar");}

                        @*@Html.ActionLink("Back", String.Format("CreateOrder/", Model == null ? 0 : Model.OrderIdFK));*@
                        @using (Html.BeginForm("AddItem", "Order", FormMethod.Post))
                        {
                            @Html.HiddenFor(x => x.OrderIdFK)

                            @Html.AntiForgeryToken()

Create New Order

                                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                                        Items

                                        @*@Html.LabelFor(model => model.ItemIdFK, htmlAttributes: new { @class = "control-label col-md-2" })*@

                                        @Html.DropDownListFor(x => x.ItemIdFK, (IEnumerable<SelectListItem>)ViewBag.Item)

                                        @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })

                                            @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                                            @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })

                                    @Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })

                                        @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })

                                        <input type="submit" value="Add Item" class="btn btn-default" />

                        }

My Controller Code:
[HttpGet]
public ActionResult AddItem(string id)
{
    OrderItemDTO orderItem = new OrderItemDTO();
    orderItem.OrderIdFK = int.Parse(id);
    ViewBag.Item = GetItem();
    //ViewBag.Order = GetOrder();
    return View(orderItem);
}

[HttpPost]
public ActionResult AddItem(OrderItemDTO orderItemDTO)
{
    var serializer = new JavaScriptSerializer();

    // For simplicity just use Int32's max value.
    // You could always read the value from the config section mentioned above.
    serializer.MaxJsonLength = Int32.MaxValue;
    IRestResponse response = APIHelper.InvokePOSTMethod(Constants.CreateOrderItem, orderItemDTO);
    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        orderItemDTO = serializer.Deserialize<OrderItemDTO>(response.Content);
        OrderItemsHub.BroadcastData();
    }
    //ViewBag.Error = "Data save successsful!";
    else
        ViewBag.Error = response.Content;

    //return RedirectToAction("ManageOrder");
    return RedirectToAction("ManageOrder", new { @id = orderItemDTO.OrderIdFK });
    //return RedirectToAction("AddItem");
}

Here is my OrderItem Model:
     public class OrderItemDTO
{
    public int OrderItemId { get; set; }
    public int OrderIdFK { get; set; }
    public int ItemIdFK { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }

    public virtual Item Item { get; set; }
    public virtual Order Order { get; set; }
}

Here is my Order Model:
 public class OrderDTO
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public OrderDTO()
    {
        this.OrderItems = new HashSet<OrderItem>();
    }
    public int OrderId { get; set; }
    public int TableId { get; set; }
    public Nullable<int> CustomerId { get; set; }
    public Nullable<System.DateTime> OrderDate { get; set; }
    public Nullable<int> Status { get; set; }
    public StatusEnum StatusType { get; set; }

    public virtual Furniture Furniture { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<OrderItem> OrderItems { get; set; }

}

Here is my Item Model:
 public class ItemDTO
{

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public ItemDTO()
    {
        this.OrderItems = new HashSet<OrderItem>();
    }

    public int ItemId { get; set; }
    public string ItemCategory { get; set; }
    public string ItemName { get; set; }
    public Nullable<decimal> Price { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<OrderItem> OrderItems { get; set; }

}

Answer:
You can add a onchange method for your item drop down like here :
@Html.DropDownListFor(x => x.ItemIdFK, (IEnumerable)ViewBag.Item,new { @onchange="BindTextBoxValue(this.value)")
And then implement the BindTextBoxValue Function in Jquery like this:

You can create a Action method to return the price for the Item based on Id.
Comment: I have implemented the given code in my project but its not working. How do I create an Action Method to return the price based on id? What does the code look like? @Shaheer_Ali
Comment: In your controller you can create a method like this In your controller :
[HttpPost]
public string postactionmethodname(int id)
{
//Code to get price by ID
return "Price";
}


Power of a composite test

Question: I know that power function is defined as $\beta(\theta)=P(\mathbf{X}\in R\mid\theta)$, where $R$ is the rejection region. For a composite test, $\Theta_0^c$ is a set. How do we define "the power of a test" in this scenario? Do we use $\inf_{\theta\not\in\Theta_0}\beta(\theta)$ or $\sup_{\theta\not\in\Theta_0}\beta(\theta)$?
Thanks!
Answer: The power of a test is $\mathbb{P}(reject  \ H_0 | H_A \ is \ true) = \mathbb{P}(\vec{X} \in R | \theta \in \Theta_A) = \beta(\theta)$ for the same $\theta \in \Theta_A$. This means that the power of a test depends upon the specific $\theta$. It is not necessarily the case that the test has a single value for the power. You might be confusing the size or level of a test with its power.
We could look at the best possible power or the worst possible power by taking $\inf$s or $\sup$s over $\Theta_A$ like you are thinking about but I haven't seen this done much. I think part of the reason this isn't done much is that the results are often not very useful. Suppose we are testing something like $H_0: \theta \leq \theta_0$ vs $H_A: \theta > \theta_0$. Then we'll get the worst power for $\theta$ just a tiny bit greater than $\theta_0$ and the best power for $\theta \rightarrow \infty$. This isn't particularly insightful or helpful. What would be more practically useful is asking what power we get for a set of $\theta$'s so that we can choose our sample size and whatnot. This reduces to computing $\beta(\theta)$.
Comment: I remember that I came across a scenario where the power is defined as the lower bound of the power function when the alternative hypothesis is true. But I forgot where I saw it. Your explanation is good. Whether or not defining the power as the lower bound does not make any fundamental difference.
Comment: With the test $H_0: \theta \leq \theta_0$ vs $H_A: \theta > \theta_0$, the critical region $R$ can be found by finding $\sup_{\theta\in\Theta_0}\beta(\theta)$. Since the power function is defined for $\theta\in\Theta_A$, why is one taking $\sup$ over $\Theta_0$?

Power of a composite test


How to find & fix memleaks inside Apache + PHP + Win2k3

Question: Alright folks,
We've got Apache 2.2.11 running mod_php 5.2.9-2 on a Windows Server 2003 (Small Business Edition) box, and each request spikes somewhere around 4 to 8MB of RAM, followed by approximately 2 to 6MB of freeing. Basically, the amount Apache releases is always notably less (by megabytes) than the amount it allocates during the request, and after a few hours the httpd.exe process ends up consuming all available RAM and the server hangs.
This behaviour doesn't occur at all on our Windows XP development boxes with the same codebase and following configs:

XP/Apache 2.2.11/PHP5.2.9-2/MySQL 5.1.34
XP/Apache 2.0.x (various)/PHP5.2.7/MySQL 5.0.67

Simple PHP scripts on the production server (Win2k3) don't appear to leak e.g:

Basic PHP echo functions
Creating and referencing classes
Output buffering
PDO with and without persistent connections

When running our full app, however, things start to leak. The only things we can think of that would cause this are the use of objects, session details, global variables - but how can I find out what the leak is? And what's causing it? Without disrupting too much the only machine we can duplicate the issue on??
Answer: PHP has it's own memory functions, and you can create __destroy magic functions to monitor objects. I personally would make a testing copy, make a few edits so you can monitor ram and see where it increases or decreases.
Personally I would have first assumed it was a caching issue, with the ram increasing, but if it renders the system unstable then it is clearly not so easy.
  echo "Before SomeStrangeObject == ".memory_get_usage()."
";
  $x = new SomeStrangeObject();
  echo "During SomeStrangeObject == ".memory_get_usage()."
";
  unset($x);
  echo "After SomeStrangeObject == ".memory_get_usage()."
";

And just look for obvious leeks. Sorry I can't be any more helpfull.
Comment: Hmm. We never do any explicit unset()ting or use __destroy. Our scripts themselves are using approx ~8MB after a call to memory_get_usage() right before the end of execution. We were assuming that Apache would be able to recover the memory from that particular request. I'm assuming it's not quite safe to assume this then?


Missing module error while running unit test

Question: I am trying to run a unit test for one of my contributed modules in my local development environment. But it keeps throwing an error:
<code>$:/path/to/web$ sudo -u www-data -E phpunit -c core/phpunit.xml profiles/abc/modules/contrib/entity_clone/tests/src/Functional/EntityCloneContentTest.php
PHPUnit 6.5.9 by Sebastian Bergmann and contributors.

Testing Drupal\Tests\entity_clone\Functional\EntityCloneContentTest
F                                                                   1 / 1 (100%)

Time: 8.49 seconds, Memory: 4.00MB

There was 1 failure:

1) Drupal\Tests\entity_clone\Functional\EntityCloneContentTest::testContentEntityClone
Unable to install modules entity_clone, block, node, datetime due to missing modules entity_clone.

/path/to/web/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php:481
/path/to/web/core/tests/Drupal/Tests/BrowserTestBase.php:578
/path/to/web/core/tests/Drupal/Tests/BrowserTestBase.php:406
/path/to/web/core/modules/node/tests/src/Functional/NodeTestBase.php:33
/path/to/web/profiles/abc/modules/contrib/entity_clone/tests/src/Functional/EntityCloneContentTest.php:50

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
</code>
Any idea what is wrong here? I have tried with a few other modules also, same error.
Do I have to do anything additional to add my profiles in the phpunit.xml?
BR/Pratip
Answer: We ran into the same issue with the 'cookies_etracker' submodule of 'etracker'.
I guess this happens, if you have a submodule AND a composer.json in your main module (not auto-generated by Drupal). Then I guess the dependencies for the tests are not auto-generated, while Drupal.org does it if no composer.json is present in the repo.
Someone had a similar problem described here:
https://www.drupal.org/forum/support/module-development-and-code-questions/2018-06-21/sub-module-dependencies and here https://github.com/acquia/coding-standards-php/issues/6
I think it's a bug / conflict in the Drupal.org Testbot:
https://www.drupal.org/project/drupalci_testbot/issues/3250126
Currently the only way to solve this is to remove the composer.json from the parent module entirely (which might not be wanted in most cases).
Comment: Appreciate your help. Will test it in a few days.
Comment: @PratipGhosh have you been successful? Would be nice for others here to know, if it helped or how you fixed it.


ARM Template 'type' property required

Question: I am trying to deploy a documentDb from the Azure-Cli (version 0.10.2) and so I exported the template directly from azure portal.
This resulted in an error of:

InvalidRequestContent : The request content was invalid and could not be deserialized: 'Could not find member 'defaultValue' on object of type 'DeploymentParameterDefinition'. Path 'properties.parameters.arm_document_db.defaultValue'

Changing those to "value" results in:

InvalidDeploymentParameterType : The type of deployment parameter 'arm_document_db' should not be specified. Please see https://aka.ms/arm-deploy/#parameter-file for details.

checking this page indicates that type is required, but is all in lowercase. This gave the same error.
removing "type" then gives me this error:

InvalidRequestContent : The request content was invalid and could not be deserialized: 'Required property 'type' not found in JSON. Path 'properties.template.parameters.arm_document_db'

<code>{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "22.214.171.124",
"parameters": {
    "arm_document_db": {
        "defaultValue": null,
        "type": "SecureString"
    },
    "arm_document_db01": {
        "defaultValue": "arm-document-db01",
        "type": "String"
    }
},
"variables": {},
"resources": [
    {
        "type": "Microsoft.DocumentDB/databaseAccounts",
        "kind": "DocumentDB",
        "name": "[parameters('arm_document_db01')]",
        "apiVersion": "2015-04-08",
        "location": "Japan West",
        "tags": {},
        "properties": {
            "databaseAccountOfferType": "Standard",
            "name": "[parameters('arm_document_db')]"
        },
        "dependsOn": []
    }
]
}
</code>
The aka.ms link shows that 'type' is required, however the error says that it isn't. Many thanks in advance!
Answer: The error is not for azuredeploy.json. It's for azuredeploy.parameters.json.
Remove the "type" field from your parameters file.

ARM Template 'type' property required


With $\alpha>0$, showing that $\int_0^1 t^\alpha(1-t^2)^kdt$ goes to $0$ as $k\to+\infty$

Question: My idea was to compute the derivative of the integrand, in order to find its maximum in $[0,1]$. It turns out it is attained at $t=\sqrt{\frac\alpha{\alpha+2k}}$. Then the claim follows from $$0<\int_0^1 t^\alpha(1-t^2)^kdt\le\left(\frac\alpha{\alpha+2k}\right)^{\alpha/2}\left(1-\frac\alpha{\alpha+2k}\right)^k\to0.$$
Is this correct? How else could one do it?
Answer: Your method seems fine to me.
Another way is as follow :
$$\forall t \in  [0,1], 0 \le t^\alpha(1-t^2)^k \le 1$$
But $1 \in L^1([0,1])$. So by dominated convergence theorem :
$$\lim_{k \to \infty} \int_0^1 t^\alpha(1-t^2)^kdt=\int_0^1 \lim_{k \to \infty} t^\alpha(1-t^2)^kdt=\int_0^10~dt=0$$
Answer: I suppose your $\alpha $ is positive. Your proof is correct. If you know measure theory you can  get it immediately from DCT: the integrand tends to $0$ because $1-t^{2}<1$ and the integrand is dominated by $t^{\alpha}$ which is integrable.
Answer: Alternative method.
Solution. $\blacktriangleleft$ Consider the upper limit. Compute as follows.
\begin{align*}
\varlimsup_k \left|\int_0^1 t^\alpha (1 - t^2)^k\mathrm d t\right| &\leqslant \varlimsup_k \left(\int_0^c + \int_c^1\right)t^\alpha (1 - t^2)^k \mathrm dt \quad [\text {the function} \geqslant 0, c\in (0,1)] \\
&\leqslant \varlimsup_k \int_0^c (1-t^2)^k\mathrm dt + \varlimsup_k \int_c^1 (1- t^2)^k \mathrm d t \quad [t^\alpha \leqslant1]\\
&\leqslant \int_0^c \mathrm dt + \varlimsup_k \int_c^1 (1-c^2)^k \mathrm dt \quad [1 \geqslant 1 -t^2 \searrow 0]\\
&=c + \varlimsup_k(1-c)(1 -c^2)^k\\
&= c + 0 \quad[1-c^2<1, (1-c^2)^k \to 0 \text{ as }k \to \infty]\\
&= c \to 0 \quad [c \to 0^+]. \blacktriangleright
\end{align*}
Answer: Another way via Beta and Gamma  functions $$\int_0^1 t^\alpha(1-t^2)^kdt= \int_0^1 t^{\alpha/2+1/2-1}(1-t)^{k+1-1}dt \\=B(\alpha/2+1/2,k+1)=\frac{\Gamma(\alpha/2+1/2)\Gamma(k+1)}{\Gamma(\alpha/2+k+3/2)}\to 0$$


How to solve probability

Question: A stationery bag contains five pencils, two erasers and five pens. If three stationeries are randomly selected from the bag (with replacement), what is the probability that
a) one pencil, one eraser and one pen
b) the three item selected either all pencils or all pens
c) none of the pencils is selected
Please help me to solve this question
Comment: Hint for a) The probability that a pencil, a eraser and a pen are selected in **that order** (with replacement) is $\frac{5}{12}\cdot \frac{2}{12}\cdot \frac{5}{12}$. But there are other possible orders like (eraser, pencil, pen), (pencil, pen, eraser), ... In total $3!=6$.
Answer: There is $\frac{5}{12}$ chance of choosing a pencil or a pen if only one item is selected. Similarly there is $\frac{2}{12}$ chance of choosing eraser.
Starting with (a):
Suppose I want to choose those elements IN ORDER. Then I can use the product rule to determine that there is $\frac{5*2*5}{12*12*12}$ chance of choosing a pencil, an eraser and a pen in this order. However the order was not required so I have to consider in how many different orders 3 items can appear - the answer is 3! - and then multiply this number by the previous one.
For (b) you can use multiplication rule again.
For (c) you can note that probability of not selecting a pencil i 1 - probability of selecting a pencil and use multiplication rule once again.
Comment: could you show me the steps to solve the (c) ?

How to solve probability


Centralize the Certificate Authority in puppet server version 4

Question: I am trying to create multiple puppet master servers with a central certificate authority using the following link:
https://docs.puppet.com/puppet/3/scaling_multiple_masters.html#option-1-direct-agent-nodes-to-the-ca-master
But this doc is according to puppet version 3, and with puppet 4 there is puppet server which runs over a JVM and jetty serving the requests. As in the above doc apache forwards all certificate URI's to central server, How do I create the same architecture with puppet 4.
Answer: It seems like it's only possible with Enterprise Puppet.
I think, than with open source one you can continue to use Apache/Nginx and proxy requests to CA or configure webserver.conf and user ca_server on all agents puppet.conf. I'm not sure what can be done with CRL revocation.
With Puppet 3.8 we use the following scheme and I think it should work with new puppetserver (it's kinda crazy though):

When certificate being cleaned on CA by someone we catch inotify
event with incron daemon.
incron runs curl with GET request to all puppet master
pwgen -1 > /tmp/crl
curl --data-binary '@/tmp/crl' http://puppetmaster:8887/crl

In nginx config on master we have the following:
server {
    listen 8887;
    server_name puppetmaster.net;
    root /var/www;
    location /crl {

        limit_except POST          { deny all; }

        client_body_temp_path      /srv/puppet/crl/;
        client_body_in_file_only   on;
        client_body_buffer_size    128K;
        client_max_body_size       128K;

        proxy_pass_request_headers on;
        proxy_set_header           X-FILE $request_body_file;
        proxy_set_body             off;
        proxy_redirect             off;
        proxy_pass                 http://localhost:8888;
    }
}
server {
    listen localhost:8888;
    server_name localhost;
    root /var/www;
}

So we saving request in a file and have one more incron daemon on master to catch this and run one more request to CA and download CRL via CA API
(see puppet doc). Reload httpd after. We do it as following:
#!/bin/bash

PID='/tmp/crlpid'
if [[ -f $PID ]]; then
    exit
else
    touch $PID
fi

function check {
    rm -f /srv/puppet/crl/*
    sleep 10
    COUNT=$(ls -1 /srv/puppet/crl | wc -l)
    if [[ $COUNT > 0 ]]; then
        check
    else
        return 0
    fi
}

if check; then
    STATUS='NOTSET'

    SSLDIR=`puppet config print ssldir`
    CERTNAME=`hostname -f`

    ENV=`puppet config print environment`
    URL="https://puppetca:8140/${ENV}/certificate_revocation_list/ca"

    CRT=`puppet config print cacert`
    CRL=`puppet config print cacrl`
    TMPCRL="/tmp/puppet_ca_crlpem.tmp"

    curl --output "${TMPCRL}" \
        --cacert "${SSLDIR}/certs/ca.pem" \
        --cert "${SSLDIR}/certs/${CERTNAME}.pem" \
        --key "${SSLDIR}/private_keys/${CERTNAME}.pem" \
        -H "Accept: s" "${URL}"

    openssl crl -text -in "${TMPCRL}" -CAfile "${CRT}" -noout > /dev/null 2>&1 && STATUS='VALID'

    if [[ "${STATUS}" == "VALID" ]]; then
        mv -f "${TMPCRL}" "${CRL}"
        chown puppet:puppet "${CRL}"
        systemctl reload httpd.service
    fi
    rm -f $PID
fi


Custom landing page for SaaS application

Question: I am building a SaaS based web application, to which users can connect using their own domain and apply their company branding to it.
How can I customize the landing page of my application based on domain from which it is being accessed. There is no login information to identify the customer.
Thanks.
Comment: What do you mean with "domain from which it is being accessed"? The users IP Address or the last Page the user has in his browser history? Hint: Both are not really useful to display a customized Landing Page.
Comment: @MatthiasS. I meant the URL can be different i.e. www.site1.com for one customer and www.site2.com for another. But they would be connecting to my server. So customers can point there own web domains to our servers and server will render their our UI with their branding.
Comment: Is there any authentication required to access your app? If there isn't how do you determine who is allowed to access it?
Comment: Its the landing page, so there is no authentication required. It's a SaaS application so customers can customize it and apply their branding. Each customer is given unique URL.
Answer: On your landing page, you can fetch request url and then customize the response accordingly.
You didn't mention the programming language, however in Java we can use ((HttpServletRequest)request).getRequestURL().toString() to get it.
Recently for one of my projects I used a third party service -  www.grooveui.com, it does something similar but without you having to write server side code.
Comment: Thanks. I found this grooveui.com promising.
Answer: You can try to put in your iframe such code:

and on server side you can try read and decode the wantedUrlEsc parameter.
Good luck!


Calculate tangent points of two circles.

Question: I have 2 circles with given center coordinates and radius.
And now I need to find the coordinates of all 8 tangent points to those circles?

I found this site explaining exactly what I want do to:
"The points of tangency t_1 and t_2 for the four lines tangent to two circles with centers x_1 and x_2 and radii r_1 and r_2 are given by solving the simultaneous equations"

That makes sense to me. But I can't solve that analytically.
Can you help me with that?
Comment: The accepted answer didn't make sense to me, but this did:  https://gieseanw.wordpress.com/2012/09/12/finding-external-tangent-points-for-two-circles/
Answer: rather than cranking through the algebra it's probably better to solve this as a "secular" geometry problem and then translate back to the plane.
let $d=|\textbf{x}_1-\textbf{x}_2|$
Define $\alpha$ as the angle measured from the line of centres of the radius to the first point of tangency ( where the tangent lies above both circles )
Define $\beta$ as the angle measured from the line of centres of the radius to the second point of tangency ( where the tangent lies above above the left circle and below the right circle. )
you get $ \cos \alpha = \frac{d}{r_1 - r_2}$  and $ \cos \beta = \frac{r_1 + r_2}{d}$
so the four points of tangency on the left circle have angles of $\pm \alpha$ and $\pm \beta$ relative to the line of centres. The corresponding points on the right circle are at angles $ \pm (\pi - \alpha) $ and at $\mp \beta$, again relative to the line of centres.
to find the co-ordinates of the first point of tangency the only extra bit of info you need is the angle of the line of centres to the horizontal.
$\tan \theta = $ the slope of the line joining $\textbf{x}_1$ and $\textbf{x}_2$
$ \textbf{t}_1= \textbf{x}_1 + r_1(cos( \alpha + \theta), sin(\alpha + \theta))$
follow an analogous procedure to determine the other seven points.
Comment: "the line of centres of the radius" - the what now?  "the first point of tangency" - first in what ordering?  "Define a as the angle measured from [a line] to [a point]" - how in the world do a line and a point form an angle?  "you get cos a = d/(r1-r2)" - how?


What is the theory behind a chord progression like E, Bm, C#, A#, G and B?

Question: I was playing the chords from Pyramania by The Alan Parsons Project. In the verse from 0:17 the chords are E, Bm7, E, Bm7, C#, A#, G, B. I get the first four chords, E and Bm7 fit in the same scale. But I don't understand how they can go from there to the following C# and the other chords. Please help? I want to understand how to write these genius progressions.
Here is a link to the song
Answer: As you said, the first four chords can be understood as chords from E mixolydian. Note that from then on the chords follow a downward movement in minor thirds (at least enharmonically): E => C# => A#/Bb => G and from there to B, the V of E. The downward movement in minor thirds is equivalent to going from a minor scale to its relative major scale (and that's also the way I hear it). Note that C# minor is the relative minor scale of E major; so by moving from E major / C# minor to C# major you effectively change from minor to major. This same 'trick' is done 3 times in a row.
Comment: @teije99zz: No, moving from minor to major or the other way around is very common, in classical music as well as in popular music.
Comment: The parallel scale/key of E maj. is Emin. Do you mean the relative ? Move from E to C#m = relative, then across to C# = parallel.I wonder if you can have a 'relative/parallel' change !!
Comment: @Tim: you're right, it's a language confusion (these terms are used differently in different languages). I'll fix it, thanks!
Comment: Thank you for the answer. I think I get it, but not totally. It still seems completely random to change from a minor chord to the parallel major chord, or am I seeing this wrong?
Answer: "Music Theory" — or more specifically, "Common Practice" or "Tonal" Theory — isn't designed with popular music in mind, and popular music frequently isn't constructed with music theory in mind.
View #1: Voice leading
In the case of this particular chord progression, I find it productive to consider it in terms of voice leading. That is, imagine sitting down at a piano and starting with a certain chord — E major in this case — and then just changing one or two notes at a time. Doing so can give a very coherent chord progression, theory aside. In this case, the fact that it eventually arrives at B major — the dominant chord relative to E major — gives an overall key-of-E-major sound, even though none of the other chords are native to that key.
Here is the chord progression itself, notated in E major to emphasize the "alien" nature of most of the chords, indicated by the need for accidentals.
X: 1
T: "Pyramania" chord progression
K: E
M: none
L: 1/1
"E"[EGB] | "Bm7"[=DFAB] | "C#"[C^EGc] | "A#"[^^C^E^A^^c] | "G"[=D=GB=d] | "B"[DFBd] ||

Here is the chord progression rewritten voice-by-voice without regard for key signature. Notice how each voice moves stepwise. (I've substituted enharmonically equivalent chords in some cases for ease of reading.)
X: 1
T: "Pyramania" voice leading
K: none
M: none
L: 1/1
[V:V1] "E"B | "Bm7"B | "Db"_d | "Bb"=d | "G"d | "B"^d ||
[V:V2] ^G | A | _A | _B | =B | B ||
[V:V3] E | ^F | =F | F | G | ^F ||
[V:V4] E | D | _D | =D | D | ^D ||

View #2: Root movement
Chord progressions in popular music, and jazz as well, are often constructed around the root movement of the chords, allowing that motion to define the overall sound, while allowing the chord qualities themselves to provide color.
Through that lens, the chords rooted on E and B are easily explained as serving tonic and dominant functions.
Note now that the roots of the other chords — Db, Bb, G — all come from an Edim7 chord (E G Bb Db).
Having stripped the chord progression down just to root movement, the progression can be explained in terms of more conventional theory.

E Bm7 E Bm7 now can be viewed as a prolonged tonic chord.
Db Bb G can be seen as a prolonged common-tone diminished chord.
B is the dominant chord.

Thus we have Tonic — CTdim7 — Dominant: a very reasonable "common practice" progression, but tied to common practice only in terms of roots of chords, not in terms of the expected chord qualities.
Answer:
E, Bm7, E, Bm7, C#, A#, G, B

E Bm7 that's a root progression by fifth, ordinary, just as you said. Eventually the B chord returns to E, and the melody dwells on E. We could say it's nominally in E, but with all the chromaticism, it isn't strictly E major.
The progression repeats so write that out for clarity...
E Bm7 E Bm7 C# A# G B | E...
The progression is quirky. What the writer was thinking isn't necessarily how you could analyze it, but...
C# A# and G B both are pairs of chromatic mediants which have a particular colorful sound. Except for the B chord, those chords aren't in E so the question is: where did the come from? Sometimes a chromatic mediant can be explained as a borrowed chord, but that doesn't really make sense in this case, only the G could be called a borrowed chord, G being the bIII chord in the parallel E minor key.
Some other explanation is wanted. Sometimes a progression can have a dominant chord inserted into it. For example a plain I IV V could have a secondary dominant added I IV V6/V V. With that understanding you can then remove a dominant from a progression for analysis purposes to look for some other basic pattern.
If you take the B out of C# A# G B | E... then you get...
C# A# G | E...
...where all of the root are moving by descending minor thirds (allowing for enharmonic re-spelling.) Actually, if you do the re-spelling it's easier to see all of the relations are chromatic mediants...
Db Bb G | E...
...it's interesting that when the B is put back in place that both G | E and G B |... are chromatic mediant changes.
So, you could say all those quirky chord changes are chromatic mediants sequenced around roots descending in minor thirds. That might sound like a mouthful of technical mumbo-jumbo, but IMO if you play around with sequences of chromatic mediant changes it becomes obvious. Just play any of the various chromatic mediant change types, repeat that change type a few times, and you get roots descending by all minor thirds or major thirds.
You could flesh out such a sequence by making one of the chords a "target/home/tonic" - whatever name you care to use - you could make a two chord vamp on the target, or insert it's dominant somewhere. For example...
Take the basic chromatic mediant sequence G B D#(Eb), make G the target, vamp it with a F chord, and also insert it's dominant D...
|: G F7 G G :|: B Eb/G D D :| G
...something like that (I tried a slash chord for the heck of it.) It sort of has the same quirky feel of the Alan Parson's Project progression.
Was the writer of that song thinking this way? I have no idea.
Answer: Chromatic Mediant!
Take any two major triads with roots a major or minor third apart.  They will always share one note between them.   They have a very distinct, fresh, fantastical sound.  The last four chords are all chromatic mediants.
C# to A#. Common tone is E#
A# to G.  Common tone is D (spelled C double sharp in the A# chord)
G to B.  Common tone is B.
(They're not new; they can be found plentifully in Beethoven and indeed much before.)
Answer: This relationship of chords in minor third distance was already used in Renaissance music: it is called in German QUERSTAND and in English FALSE RELATION
https://en.wikipedia.org/wiki/False_relation
like Aaron mentions the music theory and harmonic analysis for the common practice period doesn't fit to explain all Pop music and neither the early music of Renaissance and before...
Answer: Chords can 'go together well' in many ways.  Here are some of them.
If they are all constructed from notes of the same scale.  (Beginners sometimes think this is the only one.  But there's LOTS more possibilities!)
If both chords have one or more notes in common.
If a tension in the first chord is resolved, the surrounding notes can be pretty well up for grabs. Voice leading, to put it another way.
If both chords are the same shape. If they're adjacent - one step up or down - all the better. Cm9, Dm9, Em9 ...   Roots a minor 3rd apart also work well.  C - E♭ - G♭ ...  This could 'explain' a lot of the song in question.


Setting up primary and secondary dns on one server

Question: I'm configuring a vps to be used as webserver, and everything is going well, but now I am coming to the point of DNS. The VPS has two working IP Addresses assigned to it.
Now I need to get a primary DNS running on one, and a secondary DNS on the other IP Address (I know it is better and safer to run it on two different machines, but that I don't have).
I can find loads and loads of articles on the iNet on how to configure one DNS on one machine, or two on two different machines, but nothing about how to configure two dns'es on one single machine.
Anyone who can help me?
I'm using Centos 6.3
Comment: Or try [Hurricane Electric](http://he.net)'s free DNS service if you want to avoid companies that degrade women in their advertising.
Comment: Don't do that; use your registrars DNS service it will be much easier for you.
Comment: What's the point in configuring two DNS servers on one server? You're asking more trouble than help with that kind of configuration. If everyone knows you have only one DNS server, then let it be, and tell them to use that IP. Bind etc DNS software does not go down very easily, the event of your VPS going down is much more likely, and when it's down, your DNS is down.
Comment: Don't do this. Just use an external service; even GoDaddy's free DNS service would be better than this.
Answer: You can do what you want easily: Configure your DNS server to listen on both IP addresses.
The internet has no way of knowing whether it's one server or two - it's just happy you have two IP addresses serving your zone's information.
If you do this however you are intentionally disregarding the entire purpose of requiring two DNS servers.
There are plenty of companies out there that provide free secondary DNS <--- Google Phrase.
Take the time to understand WHY we requrie you to have two functioning DNS servers before you go about breaking the internet.
Please also purchase and read the latest edition of DNS and BIND before doing anything else.
This is required reading for anyone who wants to run a DNS server on the internet.
Comment: +1 for *DNS and BIND*. This should be required reading for anyone who is serious about maintaining DNS without a doubt, or for that matter some of those services that make very heavy use of DNS.


Fixed Matrices over finite field by a map

Question: Consider a set $M_n$ of all possible square matrices of dimension $n$ over a finite field $F_q$. Clearly the cardinality of the set $M_n$ is $q^{n^2}$. Let us consider a map $f:M_n$ $\longrightarrow$ $M_n$ defined as $f_C(X)=X^2+C$, $C$ $\in$ $M_n$. Here $X^2=X*X$, where  $'*'$ denotes the $q$-modulo matrix multiplications and $'+'$ is also standing for $q$-modulo addition.
I am interested to find out fixed points of the maps.
So I want to solve $f_C(X)=X$. It turns out a quadratic equation: $X^2+(-X)+C=0$.
Question is how many solutions are there of the equation in $M_n$? What are the solutions?
Comment: Edited as per your suggestion.
Comment: One approach is to complete the square, i.e. $(X - (1/2)I)^2 = (1/4)I - C$.  We would need characteristic not 2, obviously, and this would limit the possibility of solutions to cases $(1/4)I - C$ is the square of a matrix.
Answer: The algebraic matrix Riccati equation is given by
$$
XBX+XA-DX-C=0
$$
with given matrices $A,B,C,D$ over a field $K$. For $B=I_n$, $A=-I_n$ and $D=0$ we obtain the equation $X^2-X-C=0$, which you want. All information about solutions and other things can be found in the book of P. Lancaster, L. Rodman: Algebraic Riccati equations. Clarendon Press, Oxford (1995). One method is based on so-called Jprdan-chains.