Proof of Euler's Theorem without abstract algebra?

Question: Every proof I've seen of Euler's Theorem (that $\gcd(a,m) = 1 \implies a^{\phi(m)} \equiv 1 \pmod m$) involves the fact that the units of $\mathbb{Z}/m\mathbb{Z}$ form a group of order $\phi(m)$.  While this is a perfectly good proof, I have to wonder if it was the one that Euler used.  I know that there are fairly old precursors to group theory, but it still seems incongruous.
Thus, my question is: Are there proofs of Euler's Theorem that do not use group/ring theory?  In particular, what proof (if any; I don't know whether Euler actually discovered the theorem) did Euler use himself?
Comment: use \bmod for no space, and \pmod for parenthesis, i.e. $1 \pmod m$
Comment: Euler gave essentially the group-theoretic proof in Chapter 7 of his *Tractatus de numerorum doctrina*, 1849 (according to Weil).
Comment: http://f2.org/maths/nthproof.html check this link
Comment: possible duplicate of [Proof of the Euler Generalisation of Fermat's Little Theorem using modular arithmetic](http://math.stackexchange.com/questions/14084/proof-of-the-euler-generalisation-of-fermats-little-theorem-using-modular-arithm). I remember having written the same answer earlier and now I have found the question
Comment: Only tangentially related, but:  Is there a way to write congruences in LaTeX so that they look nice?  The spacing in the question is suboptimal.
Comment: @Siv Wasn't your answer simply copied from the prior answer? It appears to be word-for-word identical.
Comment: @Bill: I have proofs of some nice theorems typeset on my comp. And copy pasted it from there. I think I must have done the same for the earlier question as well. No wonder they are identical.
Comment: @Siv I've been in the same boat. Alas, often it's quicker to search one's own archives rather than to attempt to use the impotent MSE search tools (Googling with site: ... often works better).
Comment: I wouldn't call this a dupe, as that one only allows a specific kind of proof and this one disallows a specific kind of proof.
Answer: Consider the set of all numbers less than $n$ and relatively prime to it. Let $\{a_1,a_2,...,a_{\varphi(n)}\}$ be this set.
Consider a number $c < n$ and relatively prime to it i.e. $c \in \{a_1,a_2,\ldots,a_{\varphi(n)}\}$.
First observe that for any $a_i$, $c a_{i} \equiv a_{j} \pmod{n}$ for some $j$.
(True since $c$ and $a_i$ are themselves relatively prime to $n$, their product has to be relatively prime to $n$. This follows immediately from the definition).
If $c a_{i} \equiv c a_{j} \pmod{n}$ then $a_i = a_j$.
(True as cancellation can be done since $c$ is relatively prime to $n$).
Hence, if we now consider the set $\{ca_1,ca_2,...,ca_{\varphi(n)}\}$ this is just a permutation of the set $\{a_1,a_2,...,a_{\varphi(n)}\}$.
Thereby, we have $\displaystyle \prod_{k=1}^{\varphi(n)} ca_k \equiv \prod_{k=1}^{\varphi(n)} a_k \pmod{n}$.
Hence, we get $\displaystyle c^{\varphi(n)} \prod_{k=1}^{\varphi(n)} a_k \equiv \prod_{k=1}^{\varphi(n)} a_k \pmod{n}$.
Now, note that $\displaystyle \prod_{k=1}^{\varphi(n)} a_k$ is relatively prime to $n$ and hence you can cancel them on both sides to get
$$c^{\varphi(n)} \equiv 1 \pmod{n}$$ whenever $(c,n) = 1$.
Comment: Yes.  I think the correct answer may just be "the theorem is fundamentally group-theoretic, so all the proofs are fundamentally group-theoretic (or are disguised versions of such)", but I was hoping for some confirmation.
Comment: +1, very nice. By the way, this proof is in the Wikipedia article on Euler's theroem.
Comment: This answer doesn't explicitly use any abstract algebra or require any such knowledge on the part of the reader.  As paul garrett says, if you know any group theory then inevitably you will see the result itself in that light.  If this is not a satisfactory answer to the question, then perhaps the question should be clarified: what would constitute a less algebraic proof than this?
Comment: I do think that the first point is that Euler _did_ write as group-theoretic a proof as was possible at that date, and the second point is that, in any case, this result is a poster-child for group theory in number theory.
Comment: @Bill I disagree that this is the group theoretic proof. This argument only works in an abelian group.
Comment: @PeteL.Clark: when I have taught undergraduate abstract algebra, early in the course I prove two results about every element $g$ in a finite abelian group $G$: (i) $g^{|G|} = 1$ and (ii) the order of $g$ divides $|G|$. First I prove (i) and then I prove (ii) using (i). Later on I prove these same results in any finite group, but I have to switch the order of reasoning, to get (ii) first and then (i), since the method of cosets naturally leads to (ii).
Comment: But that *is* essentially the group theoretic way - which the OP seeks to avoid.
Comment: @David Of course I know that. But the question concerns only abelian groups.
Comment: FWIW, this is a very standard proof, probably the most common proof in elementary number theory texts.  Although now that I think about it, I remember that George Andrews' book gives a combinatorial proof of Fermat's Little Theorem.  Maybe that argument could be adapted here as well.  I remember thinking when I read that argument "Wow, this is longer and more complicated than any five other proofs of FLT I've ever seen, but at least he's having fun."
Comment: BTW, I (re)designed and taught a number theory course which does use some abstract algebra, but not very much, and in particular for which some students have seen little or no group theory.  So I wrote up some "crash course" style notes on basic group theory, including Lagrange's Theorem, which I proved (**how else**?) using cosets.  After a long time though I realized that I only ever used the special case of Lagrange's Theorem that the order of an element in a finite **abelian** group divides the order of the group.  This of course can be proven by exactly the same argument as given here.
Comment: When I teach the course I again I am planning on throwing away all references to "cosets" but instead just prove the above result -- which I have in my mind taken to calling **Lagrange's Little Theorem** -- in the standard "number theoretic" way.  In this way elementary number theory is applied to algebra, which is applied to slightly less elementary number theory.  (After a while one begins to disbelieve in a distinction between elementary number theory and elementary algebra.  I would love to teach a course that does both at once...)
Comment: I think this answer, coupled with Pete's first comment, is definitely a good answer.  While it still looks like the group-theoretic proof, that's only because I know group theory.
Comment: @Calvin: You might want to take a look at the proof by Arturo here. http://math.stackexchange.com/questions/14084/proof-of-the-euler-generalisation-of-fermats-little-theorem-using-modular-arithm/14086#14086.
But again it depends on how you want to view it.


Applied Linear Algebra |

Question: Question: Determine whether or not any column in the matrix is a linear combination of other columns. Provide a general method for answering the same question for any n x n matrix A.

My response:

Am I am in the right path or completely inaccurate?
Comment: what you have done is correct. you can also row reduce and see if you get pivots on all three rows.
Comment: It should be correct, but if you have for instance a 5x5 matrix, it's boring to calculate the determinant. So, you can check the linear independency of the columns/row by making elementary column/rows operation. I say columns/row because there is a theorem that assures us that the column rank is equal to the row rank, where the rank is just the numer of independent vectors inside the matrix.
Answer: Almost correct. You say:

If $|A| = 0$, then each column is a linear combination of the other.

You should say:

If $|A| = 0$, then some column is a linear combination of some others.
Answer: This is good. When at least, one row or column is linear dependent, the matrix determinant is zero. In other words, when dimension is greater than the range of the matrix.

Applied Linear Algebra |


What am i doing wrong in this Chi-square expectation problem?

Question: Let $X_{1},X_{2},..,X_{10}$ be 10 standard normal variates. Let us Define $T = X_{1}^{2}+X_{2}^{2}+..+X_{10}^{2}$. It is required to compute $E(\frac{1}{T})$.
Now, We know that T (sum of squares of standard normal) will follow chi-square with 10 dof. So, we can compute the expectation as:
$E(\frac{1}{T}) = \int_{0}^{\inf}\frac{1}{gamma(5)2^{5}}x^{5-1}e^{-\frac{x}{2}} * \frac{1}{x}dx$
Using the gamma integram, the above equation simply gives me $\frac{1}{2}$. But i am not getting the same answer as the answer key.
Someone please review my steps.
Answer: $$E[1/T]=\frac{1}{\Gamma(5)2^4}\int_0^\infty {1\over 2}x^3 e^{-x/2}dx$$
The integral is the third moment of exponential random variable with $\lambda=1/2$, and it is $3!/\lambda^3$. Therefore, the result becomes:
$$E[1/T]=\frac{3! 2^3}{\Gamma(5)2^4}=\frac{1}{8}$$
Comment: Thanks for your answer. I just figured one mistake while I was solving the integral.


Simplification in proof of OLS inconsistency

Question: I'm a little confused right now regarding the LLN "jump" from probability limits to expectations and variances/covariances:
Say we have a linear regression model of the form with $S$ observations:
$$ y = X\beta + \epsilon. $$
Thus,
$$ \hat{\beta}_{OLS} = (X'X)^{-1}X'y$$
and
$$
\text{plim} \hat{\beta}_{OLS} = \beta + \text{plim} \left(\frac{X'X}{S}\right)^{-1}\frac{X'\epsilon}{S} = \beta + E(X'X)^{-1}E(X'\epsilon). \ \ \ \ \ \ \ (1)$$
Assuming $X \in F^{S\times1}$, i.e. a column vector, and the model was demeaned, the term simplifies to
$$ \hat{\beta}_{OLS} = \beta + \frac{Cov(x_s,\epsilon)}{Var(x_s)}. \ \ \ \ \ \ \ (2) $$
My question now is the following:

if I cannot demean my model (because I'm in a panel setting and have to show inconsistency of OLS first), I cannot write it in a form like (2) but have to stick to the expectation form (i.e. (1)), right?
Comment: What does LLN mean? and pllim? and demean?!  What do you try to prove? What are the hypotheses? Is X a fixed design matrix or a random matrix? What do you know about $\epsilon$?
Answer: You can. By using partitioned-regression results (F-W-L theorem), if the model includes a constant term,
$$y = \alpha + \mathbf x' \beta + u$$
then the "slope coefficients" are in practice calculated by OLS as
$$\hat{\beta}_{OLS} = (\hat {\tilde X}'\hat {\tilde X})^{-1}\hat {\tilde X}'\hat {\tilde y}= \beta + (\hat {\tilde X}'\hat {\tilde X})^{-1}\hat {\tilde X}'u$$
Where $\hat {\tilde X} = X - \bar X$ (sample mean) and for later use $ {\tilde X} = X-E(X)$. Again, here $X$ does not  include a series of ones (but the model does). In other words, whether you demean a priori or not, OLS will demean the variables automatically to estimate the slope coefficients, if you also include a constant term in the model.
If you multiply and divide the above by sample size, you get the multivariate analog of $(2)$ since the variables are now in sample mean-deviation form and so these are estimated variance and covariance matrices (and in $(2)$ you should use hats, by the way).
Then
$$\text{plim}\big( \hat{\beta}_{OLS} -\beta\big) =  \text{plim}\left (\frac 1n\hat {\tilde X}'\hat {\tilde X}\right)^{-1}\text{plim}\left(\frac 1n \hat {\tilde X}'u\right)$$
The Law of Large Numbers does not "jump from probability limits to expectations": it is the very essence of the Law that the probability limit is the expected value. Then (under the necessary conditions)
$$\text{plim}\big( \hat{\beta}_{OLS} -\beta\big) =  E\left (\frac 1n\tilde X'\tilde X\right)^{-1}E\left(\frac 1n \tilde X'u\right)$$
Now the variables are in deviations from their true expected values, and these expected values are the true covariance matrices, and you can write for example,
$$\text{plim}\big( \hat{\beta}_{OLS} -\beta\big) = [ \text {Var}(\mathbf x)]^{-1}\cdot \text{Cov}(\mathbf x \cdot u)$$
which is the probability limit of the multivariate analogue of $(2)$.


Simplifying $\cos(x) \times \cos(y)$

Question: So I got a problem wrong on my homework because I simplified $\cos (x) \times \cos (y)$ to be $\cos (xy)$, and my teacher wrote on my paper that it can't be simplified. I was wondering if anyone could give me an explanation as to why you can't simplify those two.
Comment: Because that equation would have to be true for all real numbers $x,y$. In particular it must be true for $0, \pi$. Yet,  $$\cos(0)\cos(\pi) \neq \cos(0 \cdot \pi)=\cos(0)$$
Comment: I assume your teacher meant only that $\cos (x) \times \cos (y)$ can't be simplified the way you simplified it, because $\cos (x) \times \cos (y)= \cos x \cos y$ is not an identity. The product $\cos (x) \times \cos (y)$ is equal to various things, but $\cos(xy)$ is not one of them, and none of them is arguably "simpler."
Comment: Try graphing $\cos(x)\cos(y)$ and $\cos(xy)$. You'll see the difference.
Answer: It is depends what you mean by saying simplify...
Sometimes it can be useful to use this identity:
$\cos(x) \cos(y) = \frac{1}{2} \left[ \cos(x+y) + \cos(x-y)\right]$
Usually you can change trigonometric function multiplication to sum or backwards.
Multiplication of any two functions with different variables cannot be simplified into one function of one variable.
This kind of simplification is extremely rare:
(1) $f(x)f(y)=g(xy)$
Examples of function that fulfill (1) is $f(x)=ax$ or $f(x)=ax^n$.
Other function that fulfill (1) probably esoteric...
Comment: Why do you have $f$ on the LHS and $g$ on the right?  I think you mean $x^a$, not $ax$.
Comment: Fair enough, but if you allow arbitrary functions on the RHS then $ax$ is by no means the *only* differentiable solution as you claim.  What about $f(x) = ax^n$?
Comment: Yes, you are right...
Comment: If $f(x) = ax$, then $f(x)f(y) = axay = a^2 xy$, but $f(xy) = axy$, so isn't that not actually an example of the property you're talking about? I agree with the above commenter that $f(x) = x^a$ is a good example. Since $x^a y^a = (xy)^a$
Comment: yes, but $g$ not have to be equal $f$

Simplifying $\cos(x) \times \cos(y)$


Generate unique and random samples of a given list in Python for a given amount of times?

Question: Lets say L=[1,2,3,4,5]
How can I create 4 (or maximum of len(L)!) unique random orders of L?
Expected result should look like this:
[[2,1,3,4,5],[5,3,2,1,4],[4,3,2,1,5],[5,1,3,2,4]

Comment: Show what you have tried so far.
Comment: Look at [`random.choices`](https://docs.python.org/3/library/random.html#random.choices) and [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations)
Comment: would this `[[1, 2, 3, 4, 5],
[1, 2, 3, 5, 4],
[1, 2, 4, 3, 5],
[1, 2, 4, 5, 3]]` be valid result for you?
Comment: I did not look at itertools.
I tried random.choices but the problem was omitting the repeated random samples. There is no guarantee that two randomly generated samples are not the same.
Answer: As pointed out in this post, you can use itertools to generate all possible permutations of the list:
all_perms = list(itertools.permutations(L))

then if you only want 4 random choices (without replacement) of all possible permutations, you can do something like:
random.sample(all_perms, k=4)

Comment: That's going to generate a lot more permutations than necessary, though. That might not be a big deal with a length-4 list, but it's completely infeasible for something like length-20.
Comment: Yes, I was about to comment on your answer... its good to have a more efficient alternative for larger lists. I wonder if this can be solved with numpy.
Answer: Fairly standard approach: pick random samples and throw away duplicates for a small sample, or partial shuffle if you're generating a sample that covers most of the sample space.
import itertools
import math
import random

def n_random_permutations(n, l):
    if n * 3 < math.factorial(len(l)):
        # rejection sampling
        # generate samples and throw them away if we already picked them.
        samples = set()

        while len(samples) < n:
            sample = list(l)
            random.shuffle(sample)
            samples.add(tuple(sample))

        samples = list(samples)
        random.shuffle(samples)
        return samples
    else:
        # generate every possible permutation and pick n of them.
        permutations = list(itertools.permutations(l))
        return random.sample(permutations, n)

Comment: Good alternative for larger arrays! One thing to consider though is that `math.factorial(len(l))` might go out of range due to multiplication by `0.3` which casts it to `float`. Doing `if n/0.3 < math.factorial(len(l))` would solve overflow error for larger lists...


How to alter the visibility of a menu tab for a page created in Views?

Question: I have a View that is a primary tab on the user profile page. The user profile tabs look like this view | edit | menu-item-to-hide. If the person viewing the page is does not have role of admin or the owner of the profile page then they should not see the tab.
I assume that I use hook_menu_alter() but I'm not sure what the code should be.
Answer: I created a mini module called helper.
In helper.info I put
name = "Helper"
description = "Provides custom support functions."
core = "7.x"

First we need to get the helper_menu_alter() to be called after views_menu_alter so we use hook_module_implements_alter to pull the value of our module in the array and put it back in which will always be done at the end of the array.
<?php

function helper_menu_alter(&$items){
  $items['user/%/workbench']['access callback'] = 'helper_access';
  $items['user/%/workbench']['access arguments'] = array(1);
  $items['user/%/workbench/drafts']['access callback'] = 'helper_access';
  $items['user/%/workbench/drafts']['access arguments'] = array(1);
  $items['user/%/workbench/needs-review']['access callback'] = 'helper_access';
  $items['user/%/workbench/needs-review']['access arguments'] = array(1);
}

/**
 * Helper access callback.
 */
function helper_access($uid) {
  if ($uid) {
    if ($GLOBALS['user']->uid == $uid || user_access('view all unpublished content')) {
      return TRUE;
    }
  }
  return FALSE;
}

function helper_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // Move helper_menu_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['helper'];
    unset($implementations['helper']);
    $implementations['helper'] = $group;
  }
}

Comment: You shouldnd check if user has uid 1. `user_access` for user1 is always `TRUE`
Comment: You shouldn't change your weight to 99, in d6 this was a big problem where every module kept trying to one up each other. At the very least you should set your weight to whatever views is + 1. Also this is why hook_module_implements_alter was added in d7. To avoid every module trying to get a higher weight.
Answer: Hook_menu_alter is called when the menu is being rebuild so you shouldn't use it for these situations.
Normally you should set the permission on your page view to only allow the roles you want to see that view. The menu system will handle hidding the tab for you when the user doesn't have the right permission.
The one thing that's weird is that you want to restrict on a role and if the user is viewing his own profile. In this case you do want to use hook_menu_alter but not to hide the menu tab but instead to replace the access callback with your own.
In your custom access callback you want to do something like http://api.drupal.org/api/drupal/modules--user--user.module/function/user_view_access/7
So essentially you want to do the logic on the access callback not on the hook_menu_alter.
You're going to run into issues with weights because I'm sure views run last.
To work around this you should implements hook_module_implements_alter to designate your module to run after views only for the hook_menu_alter hook.
This doesn't required any weight changes and it helps resolve the problem where you might want your module to run before views in certain situations, yet after it in a different situation.
Comment: Yes, you're module needs to have a higher weight than views. Also you can get around this by implement hook_module_implements_alter. Which will let you designate your module to be ran after views. Instead of changing the system table.
Comment: i wrote this on a mobile device, so this answer could use some cleanup.
Comment: I had already figured out using the user_view_access() but I couldn't find a way to alter Views which was called by hook_menu_alter() after the callback in my module was. I needed to alter the system table in the database first.
Answer: Easiest way is to write custom Access Callback with Views Access Callback module.


How do I center text over an image in HTML?

Question: I have been trying to center my text over an image, however, it will not center. I have looked at various questions here on Stack Overflow, but none will work.

footer {
  align-content: center;
  justify-content: center;
}

.jumbotron {
  display: flex;
  align-items: center;
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Wave_Panorama.jpg/1024px-Wave_Panorama.jpg');
  background-size: cover;
  color: #ffffff;
  height: 500px;
  text-shadow: 0.25px 0.25px 0.25px #000000;
}

.jumbotron h2 {
  font-size: 60px;
  font-weight: 700;
  margin: 0;
  color: #fff;
  text-align: center;
  position: absolute;
  text-align: center;
  margin: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

By Me

I am quite new to HTML so if my code is messy/ confusing/ just plain wrong, that may be the reason. I was also trying to fix it with code snippets from Stack Overflow, so if some parts are unnecessary, please tell me so I can fix it.
Answer: Or, you know, just clean up the code a bit...
*removed the superflous
container, put flex: 1 1 0; where it should be, and removed some other non-sensical CSS as well.

.jumbotron {
display: flex;
text-align: center;
background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Wave_Panorama.jpg/1024px-Wave_Panorama.jpg');
background-size: cover;
color: #ffffff;
height: 500px;
text-shadow: 0.25px 0.25px 0.25px #000000;
}
.text-center {
  flex: 1 1 0;
  margin: auto;
}
.jumbotron h2 {
font-size: 60px;
font-weight: 700;
text-align: center;
}

By Me

Comment: *"just clean up the code a bit..."* - And that will magically fix it? Or did you make a fundamental change as well?
Comment: You should state what you did to "clean it up" and why the previous didn't work. Your solution is good because it's making use of flex-box feature without adding extra `position` declaration.
Comment: LOOK at the code - it's about 25 lines of code, it should be fairly obvious. But fine, I'll edit the description a bit.
Answer: Make position relative instead of absolute

footer {
align-content: center;
justify-content: center;
}

.jumbotron {
display: flex;
align-items: center;
background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Wave_Panorama.jpg/1024px-Wave_Panorama.jpg');
background-size: cover;
color: #ffffff;
height: 500px;
text-shadow: 0.25px 0.25px 0.25px #000000;

}

.jumbotron h2 {
font-size: 60px;
font-weight: 700;
margin: 0;
color: #fff;
text-align: center;
position: relative; /* MODIFICATION */
text-align: center;
margin: 0;

}

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

 By Me


Validação formulario

Question: Crie a classe de estilo CSS denominada"invalido", cuja formatação é ter a seguinte cor de fundo: #A00 e o texto de cor branca.  Altere  a  validação  de  formulário  de  forma  que,  caso  um  campo  de  formulário  esteja  inválido,  assuma  esta  classe.  Caso esteja correto, volte ao estilo padrão

  Nome:

  <input type="text" id="txtNome" name="txtNome" size="50" maxlength="100">

Este campo não pode ficar vazio!

if (document.getElementById("txtNome").value.length < 3) {
  alert('Por favor, preencha o campo nome');
  document.getElementById("txtNome").focus();
  return false
}

Ou seja altere o alert para o que está na no html, mas utilizando esses métodos citados.
Comment: Confuso... pode reformular?
Comment: sim, vou reformular :D
Comment: O modo como você descreveu sua pergunta me parece um exercicio acadêmico, estou correto?
Answer: Altere o evento (onkeyup) conforme sua necessidade (onblur, onfocus, ...).
Execute o código abaixo e comece a digitar letra por letra para entender:

var elementoValidar = document.getElementById('txtNome');

function valida() {
    if (elementoValidar.value.length < 3) {
     elementoValidar.className = "invalido";
    } else {
        elementoValidar.className = "ok";
    }
}
input[type="text"].invalido {
  background-color : #a00;
  color: #fff;
}

input[type="text"].ok {
  background-color : #0a0;
  color: #fff;
}

  Nome:

  <input type="text" id="txtNome" name="txtNome" onkeyup="valida()" size="50" maxlength="100" />

Este campo não pode ficar vazio!

Validação formulario


Do Domain Events in Domain Driven Design hide the intent?

Question: Using Domain Events is widely endorsed practice for DDD applications, but there are scenarios that prove tricky for me.
I was working recently on an application where business logic required that when new user is created, that user is also created in three separate subsystems. So basically if you use transaction script approach it would look something like:
public void CreateUser()
{
    CreateUserInSystemA();
    CreateUserInSystemB();
    CreateUserInSystemC();
}

The approach I was looking at was using Domain Events, so the entry point looked something like:
public void CreateUser()
{
    CreateUserInSystemA();
}

Then CreateUserInSystemA would raise a domain event when the user was created. Then handler for that event would create user in system B, raise another domain event, and another handler would run that will create user in system C.
All this was set up, during registration of DI container so this was pretty much hardwired.
So the question is:
1) Doesn't this approach effectively hides domain logic? It is not easy by looking at CreateUser method to see what we are really doing.
2) What if (as happened in our case), you will have a new workflow where you just need to create users in systems A and B - thusCreateUserInSystemC should not be called? If we used existing CreateUserInSystemB implementation, it will raise domain event and hard-wired CreateUserInSystemC will run regardless.
What is the best approach to handle this scenario in proper DDD way? Should we use Application Service layer and simply expose two separate methods for both workflows, and do not base flow on Domain Events?
Answer: To me, Domain is a sub-system on its own. In your case, you have several systems interconnected. In such a case, your event is an inter-system event, not a domain event.
Thus, fire an event depending on the relations between your sub-systems. From each Domain (sub-system) point of view, other sub-systems are integration layers, probably with their own domain models inside.
So, answers to your questions would be:
1) No, because the approach is completely related to the systems integration.
2) Flow changes require changes in the integration behavior, not to the sub-systems.
One more point: what I mean by sub-system is similar to the services. Each domain has a service that it interacts with. And services are usually connected with interactions (SOA system with multiple services is an implementation example). Plus, each domain can be a service as well, exposed through the service layer probably.


Change Related XML File Android Studio Java Class

Question: I'm new to Android development, and I'm having an issue where my RegistrationActivity Class is essentially pointing to the wrong XML file.
This is the error in logcat:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at arufolo.myapp.RegistrationActivity.onCreate(RegistrationActivity.java:45)

I found that the error is caused by the following:
When I go to my Registration class and click the little XML icon next to the class name, it shows that the related XML file is the login.xml (My Login Screen)... Instead, I want this to show registration.xml. How do I do this?
Answer: Please make sure that your Registration class uses the correct layout ID as the parameter to setContentView(). See the documentation for more information.
Comment: OMG I'm literally the dumbest person ever. Thank you so much @yole I spent so much time on this for no reason.


how do I pull Score from this MASSIVE json object?

Question: I want $result['score'] but It never returns true despite trying  $result->score, $result[0] and $result[stdClass]['score'];  All help is greatly appreciated.
Object(stdClass)#1 (9) { ["kind"]=> string(22) "pagespeedonline#result" ["id"]=> string(34) "https://www.google.com/?gws_rd=ssl" ["responseCode"]=> int(200) ["title"]=> string(6) "Google" ["score"]=> int(92) ["pageStats"]=> object(stdClass)#2 (9) { ["numberResources"]=> int(13) ["numberHosts"]=> int(5) ["totalRequestBytes"]=> string(4) "2295" ["numberStaticResources"]=> int(8) ["htmlResponseBytes"]=> string(6) "190230" ["imageResponseBytes"]=> string(5) "45452" ["javascriptResponseBytes"]=> string(6) "780563" ["otherResponseBytes"]=> string(4) "1867" ["numberJsResources"]=> int(4) } ["formattedResults"]=> object(stdClass)#3 (2) { ["locale"]=> string(5) "en_US" ["ruleResults"]=> object(stdClass)#4 (10) { ["AvoidLandingPageRedirects"]=> object(stdClass)#5 (3) { ["localizedRuleName"]=> string(28) "Avoid landing page redirects" ["ruleImpact"]=> float(7) ["urlBlocks"]=> array(2) { [0]=> object(stdClass)#6 (1) { ["header"]=> object(stdClass)#7 (2) { ["format"]=> string(96) "Your page has $1 redirects. Redirects introduce additional delays before the page can be loaded." ["args"]=> array(1) { [0]=> object(stdClass)#8 (2) { ["type"]=> string(11) "INT_LITERAL" ["value"]=> string(1) "2" } } } }

Here is a copy of a formatted pastebin of the object
Will do:
"{\n \"kind\": \"pagespeedonline#result\",\n \"id\": \"https:\/\/www.google.com\/?gws_rd=ssl\",\n \"responseCode\": 200,\n \"title\": \"Google\",\n \"score\": 92,\n \"pageStats\": {\n \"numberResources\": 12,\n \"numberHosts\": 5,\n \"totalRequestBytes\": \"2186\",\n \"numberStaticResources\": 8,\n \"htmlResponseBytes\": \"189695\",\n \"imageResponseBytes\": \"45452\",\n \"javascriptResponseBytes\": \"780569\",\n \"otherResponseBytes\": \"1595\",\n \"numberJsResources\": 4\n },\n \"formattedResults\": {\n \"locale\": \"en_US\",\n \"ruleResults\": {\n \"AvoidLandingPageRedirects\": {\n \"localizedRuleName\": \"Avoid landing page redirects\",\n \"ruleImpact\": 7.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"Your page has $1 redirects. Redirects introduce additional delays before the page can be loaded.\",\n \"args\": [\n {\n \"type\": \"INT_LITERAL\",\n \"value\": \"2\"\n }\n ]\n }\n },\n {\n \"header\": {\n \"format\": \"Avoid landing page redirects for the following chain of redirected URLs.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/AvoidRedirects\"\n }\n ]\n },\n \"urls\": [\n {\n \"result\": {\n \"format\": \"$1\",\n \"args\": [\n {\n \"type\": \"URL\",\n \"value\": \"http:\/\/google.com\/\"\n }\n ]\n }\n },\n {\n \"result\": {\n \"format\": \"$1\",\n \"args\": [\n {\n \"type\": \"URL\",\n \"value\": \"http:\/\/www.google.com\/\"\n }\n ]\n }\n },\n {\n \"result\": {\n \"format\": \"$1\",\n \"args\": [\n {\n \"type\": \"URL\",\n \"value\": \"https:\/\/www.google.com\/?gws_rd=ssl\"\n }\n ]\n }\n }\n ]\n }\n ]\n },\n \"EnableGzipCompression\": {\n \"localizedRuleName\": \"Enable compression\",\n \"ruleImpact\": 0.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"You have compression enabled. Learn more about enabling compression.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/EnableCompression\"\n }\n ]\n }\n }\n ]\n },\n \"LeverageBrowserCaching\": {\n \"localizedRuleName\": \"Leverage browser caching\",\n \"ruleImpact\": 0.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"You have enabled browser caching. Learn more about browser caching recommendations.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/LeverageBrowserCaching\"\n }\n ]\n }\n }\n ]\n },\n \"MainResourceServerResponseTime\": {\n \"localizedRuleName\": \"Reduce server response time\",\n \"ruleImpact\": 0.09,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"In our test, your server responded in $1. There are many factors that can slow down your server response time. Please read our recommendations to learn how you can monitor and measure where your server is spending the most time.\",\n \"args\": [\n {\n \"type\": \"DURATION\",\n \"value\": \"0.21 seconds\"\n },\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/Server\"\n }\n ]\n }\n }\n ]\n },\n \"MinifyCss\": {\n \"localizedRuleName\": \"Minify CSS\",\n \"ruleImpact\": 0.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"Your CSS is minified. Learn more about minifying CSS.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/MinifyResources\"\n }\n ]\n }\n }\n ]\n },\n \"MinifyHTML\": {\n \"localizedRuleName\": \"Minify HTML\",\n \"ruleImpact\": 0.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"Your HTML is minified. Learn more about minifying HTML.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/MinifyResources\"\n }\n ]\n }\n }\n ]\n },\n \"MinifyJavaScript\": {\n \"localizedRuleName\": \"Minify JavaScript\",\n \"ruleImpact\": 0.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"Your JavaScript content is minified. Learn more about minifying JavaScript.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/MinifyResources\"\n }\n ]\n }\n }\n ]\n },\n \"MinimizeRenderBlockingResources\": {\n \"localizedRuleName\": \"Eliminate render-blocking JavaScript and CSS in above-the-fold content\",\n \"ruleImpact\": 0.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"You have no render-blocking resources. Learn more about removing render-blocking resources.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/BlockingJS\"\n }\n ]\n }\n }\n ]\n },\n \"OptimizeImages\": {\n \"localizedRuleName\": \"Optimize images\",\n \"ruleImpact\": 0.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"Your images are optimized. Learn more about optimizing images.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/OptimizeImages\"\n }\n ]\n }\n }\n ]\n },\n \"PrioritizeVisibleContent\": {\n \"localizedRuleName\": \"Prioritize visible content\",\n \"ruleImpact\": 0.0,\n \"urlBlocks\": [\n {\n \"header\": {\n \"format\": \"You have the above-the-fold content properly prioritized. Learn more about prioritizing visible content.\",\n \"args\": [\n {\n \"type\": \"HYPERLINK\",\n \"value\": \"https:\/\/developers.google.com\/speed\/docs\/insights\/PrioritizeVisibleContent\"\n }\n ]\n }\n }\n ]\n }\n }\n },\n \"version\": {\n \"major\": 1,\n \"minor\": 15\n },\n \"screenshot\": {\n \"data\": \"_9j_4AAQSkZJRgABAQAAAQABAAD_2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj_2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj_wAARCADwAUADASIAAhEBAxEB_8QAHAABAAIDAQEBAAAAAAAAAAAAAAMIAgUGBAEH_8QAQxAAAQMCAgQKCQEGBgMBAAAAAAECAwQRBSEGEhMUFzFBUVJVYZLR0iJTVHGBkZOhogcVMjNCVmIjNHOx4fAllMHx_8QAGgEBAAIDAQAAAAAAAAAAAAAAAAECAwQFBv_EADERAQABAwIEAwUIAwAAAAAAAAABAgMREiEEMVFhBSJBE1KRoeEGFBVicYHB8DJC0f_aAAwDAQACEQMRAD8A0mj1JhNU6oTGa6SjRqNWJWNvrqt7ouS8WSkkeG4Q-VzFxpsaN1V2joXKjkc29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Hq3l_RT7jeXczTXVdGs0qSxzPhkRurrMRL2vexhBRTRTRvWunka1VVWPzR2Sp_z8ANpvL-i0by_op9yE1SYVKiNaldM1iLdGtyS9_fdfiBu95dzNG8v6LTTxUNUyojctfK6JllVq8blvmi9hsgP_2Q==\",\n \"height\": 240,\n \"mime_type\": \"image\/jpeg\",\n \"width\": 320\n }\n}\n"

As per request this is the output I get from changing my echo to echo "Score Speed is: ". print_r(json_decode($result[0]->score, true)) . "
";
(and also with echo "Score Speed is: ". print_r(json_decode($result[0]->score)) . "
";)
Score Speed is: 1
sorry it's not more descriptive.
Final Edit: thank you for your help everyone... this combination yielded my data:
    $formatted = json_decode($results, JSON_PRETTY_PRINT);

//I had the old version using True instead of JSON_PRETTY_PRINT
    echo "formatted data: " . $formatted[0]->score . "
";

//This ended up not working
    echo "2nd try: ". $formatted['score'];

//This one DOES work.
...
...
      //This is the [original piece of code I used as a reference point is here][2]
    echo '
';
    print_r(json_decode($results['score'],true));
    echo '
';

Comment: Could you supply the raw json dump?
Comment: I thought so too Scuzzy but alas that does not resolve either: http://puu.sh/oVNFS/d21d63efa6.png
Comment: That isn't json. That's a `var_dump()` of the data - In your screen shot I can see a `var_dump(json_decode())`. I just need the JSON
Comment: Darren would that not matter in this case though? if I removed var_dump the aim is still the same...it's there so I can determine the response outputs.  @adrin27 thank you I didn't know that I could do that - thought it was one or the other
Comment: Did it solve your problem? If not try to give us the `print_r()`
Comment: @aldrin27 no dice...right now I'm trying: `echo "Score Speed is: ". print_r(json_decode($result[0]->score, true)) . "";` that returns 1 (for true?) and not the actual value itself
Comment: @Frankenmint help us help you please ... dump the raw json. Purpose is for us to try to make sense of the stream and suggest best approach for extracting your Score. json_encode($result,JSON_PRETTY_PRINT), echo/log/print it somewhere and paste it here.
Comment: No it should return `92` only. Can you `print_r()` the data that supplied all of that object?
Answer: You're going about this the wrong way. You're trying to decode an already decoded value.
Simply try echo'ing out the value:
echo $result[0]->score;

That's the end step. I feel that every step before this is incorrect - leading you to this issue of you not being able to print out the expected value.
You should be running through a process like the following:
$data = FETCH_THE_JSON_FROM_DATA_SOURCE();
$json = json_decode($data);
// now we find data
echo $json[0]->score;

Note: Above code is pseudo code, you'll need to fill in your parts appropriately.
We can't tell you how to get it if we can't see the raw json data. So help us help you.
Comment: 2nd edit: found a typo that was likely a culprit.  hold on pls


Composite tangent function questions (domain and solving an equation)

Question: The question is as follows:

Let $h$ be the function such that $h(x) = \tan\left(\sqrt{\dfrac{1}{x+2}}\right)$. (a) Find the domain of $h$ and (b) find the values of $x$ such that $h(x)=1$.

For part a, I notice that $1/(x+2)$ is the argument of a square root function. My class defaults to functions having a domain and codomain of real numbers, so it follows that $1/(x+2)$ must be nonnegative. By interval testing, I determine that $x \in   (-2,\infty)$.
I also notice that tangent has undefined values, i.e. the undefined values of $\tan(x)$ are $x \in \pi/2 + \pi n, n \in \mathbb{Z}$. So this must also be considered in the domain: $$\sqrt{\frac{1}{x+2}} \ne \frac{\pi}{2} + \pi n, n \in \mathbb{Z}$$
If I square both sides and then isolate $x$, it results in $$ x \ne \dfrac{1}{\left(\frac{\pi}{2} + \pi n\right)^2} -2,\ n\in\mathbb{Z}$$
So the domain of $h$ is $$\left\{x \mid x\in\mathbb{R}, x\in (-2,\infty), x \ne \frac{1}{(\pi/2+\pi n)^2}-2, n \in\mathbb{Z} \right\} $$ Is this answer and set-builder notation okay?
For part b, solving $ \tan\left(\sqrt{\frac{1}{x+2}}\right) = 1$ lead me to $$ \sqrt{\frac{1}{x+2}} = \frac{\pi}{4} + \pi n,\ n\in\mathbb{Z}$$ and squaring both sides and solving for $x$ gives $$ x = \frac{1}{\left(\frac{\pi}{4} + \pi n\right)^2} - 2,\ n\in\mathbb{Z}$$
This seems to hold for $n\ge 0$, but for negative $n$, this results in a wrong result (leading to $h$ giving values of $-1$ instead of $1$). How could I have predicted an extra restriction for $n$?
Answer: $\displaystyle\sqrt{\frac{1}{x+2}} = \frac{\pi}{4} + \pi n,\ n\in\mathbb{N}$ because you should only consider natural number values of n (including 0), otherwise you are equating a square root to a negative number, and you're only looking at real domains/codomains.
Comment: Just realized what you really meant. The reason that negative values of $n$ in the expression $x \neq \frac{1}{\left(\frac{\pi}{4} + \pi n\right)^2} - 2,\ n\in\mathbb{Z}$ also give an undefined tangent is because for every negative $n$, you can find a positive $n$ that gives the same value. For example, $n=-1$ is the same as $n=0$. $n=-2$ is the same as $n=1$. In other words, the negative $n$ are an exact copy of the positive $n$.
Comment: Would this also be necessary for finding the domain in part (a) when solving $\sqrt{\frac{1}{x+2}} \ne \frac{\pi}{2} + \pi n, n \in \mathbb{Z}$? It seems interesting that for part (a), the negative values of $n$ still work out in terms of getting an undefined tangent
Comment: The negative values of $n$ also result in undefined $h(x)$ because they are outside the domain of $\sqrt \frac {1}{x+2}$. Take for example, $n = -1$. Your statement says $ \sqrt \frac {1}{x+2} \neq - \frac {\pi}{2}$, which is redundant given the fact that you're looking at real domain only. This isn't unique to negative integers. Take for example $n = -1.6$ (although not in $\mathbb{Z}$), which also causes $h(x)$ to be undefined. However, positive values of $n$ correspond to where $h(x)$ "blows up".


Mostrar noticias de feed rss uma de cada vez com fade

Question: Tenho o seguinte código php para ir buscar o feed de noticias de um determinado site:
<?php
    $rss = new DOMDocument();
    $rss->load('http://feeds.jn.pt/JN-ULTIMAS');
    $feed = array();
    foreach ($rss->getElementsByTagName('item') as $node) {
        $item = array(
            'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
            'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
            'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
            'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
        );
        array_push($feed, $item);
    }
    $limit = 3;
    for ($x = 0; $x < $limit; $x++) {
        $title       = str_replace(' & ', ' & ', $feed[$x]['title']);
        $link        = $feed[$x]['link'];
        $description = $feed[$x]['desc'];
        $date        = date('l F d, Y', strtotime($feed[$x]['date']));
       echo '

'.$title.'
'.$description.'

';
    }
 ?>

queria que em vez de mostrar as noticias todas apenas me mostra-se uam de cada vez fazendo um fade in e um fade out com jquery, neste momento está me a mostrar uma lista com as 3 noticias.
echo '

'.$title.'
'.$description.'

';

Answer: Creio que isso resolve seu problema e pode servir para muita gente:
<!doctype html>

    <meta charset="utf-8">
    <title>Notícias</title>

<?php
$mes = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
$wda = ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'];

$rss = new DOMDocument();
$rss->load('http://feeds.jn.pt/JN-ULTIMAS');

$feed = [];
foreach ($rss->getElementsByTagName('item') as $node) {
    $item = array(
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
        'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
    );
    array_push($feed, $item);
}

$limit = 10;
for ($x = 0; $x < $limit; $x++) {
    $title       = str_replace(' & ', ' & ', $feed[$x]['title']);
    $link        = $feed[$x]['link'];
    $description = $feed[$x]['desc'];
    $dt          = strtotime($feed[$x]['date']);
    $date        = $wda[0+date('w', $dt)].', '.date('d', $dt).' de '.$mes[date('n', $dt)-1].' de '.date('Y', $dt);

    echo '

'.$title.'
'.$date.'
'.$description.'

';
}
?>


Time Series equivalent of the Generalised Linear Model

Question: I have a time series $y_t$ which is measured at regular intervals over a long period of time. The values of $y$ are between $0$ and $1$, it represents a proportion, and these values change slowly over time. I want to predict the value of $y$ at future time periods.
I wanted to start in the most simple way possible, so I creates a linear regression based on the previous time period:

$y_t \sim y_{t-1}$

This can be extended to include $y_{t-2}$ and some covariates.
To account for the fact that the dependent variable is between $0$ and $1$, I subsequently turned this into a generalised linear model by including a logit link function:

$logit(y_t) \sim logit(y_{t-1}) + logit(y_{t-2}) + covariates$

This already works quite well for predicting future values of $y$.
However, I realise linear regression and GLM are not appropriate for time series. Why not though? What assumptions are violated if one used such models on times series data with autocorrelation?
What would be an equivalent simple model to use for such time series? A model able to deal with a dependent variable between $0$ and $1$, but otherwise as simple as possible.
Answer: You are already using a popular and often very effective time series model: an autoregressive model of order two, typically referred to as AR(2). The only non-standard part of your procedure is that you have logit-transformed your data.
You can assess the validity of your AR(2) model by examining the residuals in the same way as you would for any other regression model. For example the residuals of your AR(2) model should not be heteroscedastic or serially correlated.
Autoregressive models belong to a wider class of linear time-series models called autoregressive-integrated-moving-average or ARIMA. These models are generally more complicated to fit than simple autoregressions, but statistics software packages such as R should be able to fit them out-of-the-box.
Answer: First of all, there's no assumption made when you fit a linear regression, i.e. optimize its coefficients to minimize some risk function. There are a few assumptions made when you want to apply tests over the coefficients.

However, I realise linear regression and GLM are not appropriate for
  time series. Why not though? What assumptions are violated if one used
  such models on times series data with autocorrelation?

You said it yourself. Independence of error terms is often violated when you perform a hypothesis test on the value of the coefficient. There are remedies to this though.

This already works quite well for predicting future values of $y$

If this was your objective all along, it's performing well on out of sample data, and you do not intend to perform hypothesis tests, then by all means keep with the linear regression.


If a function is measurable with respect to the completion then it is equal to some measurable (with respect to the measure space) function a.e.

Question: Exercise: Let $(X, \mathcal{A}, \mu)$ be a measure space and $(X, \tilde{\mathcal{A}}, \tilde{\mu})$ its completion. Suppose $\tilde{f}: X\to \mathbb{R}$ is $\tilde{\mathcal{A}}-$measurable. Show that there exist $f:X\to \mathbb{R}$ $\mathcal{A}-$measurable and $M\in \mathcal{A}$ with $\mu(X-M) = 0$ such that $\tilde{f}(x) = f(x)$ for all $x\in M$.
My try: Let $r_1, r_2, ...$ be an enumeration of all the rationals. For each natural number $n$, we know $\tilde{f}^{-1}((-\infty, r_n)) = A_n\cup M_n$, where $A_n\in \mathcal{A}$ and $M_n\subseteq M_0^n$ with $\mu(M_0^n) = 0$. The idea is to try and define $f$ in such a way that $f^{-1}((-\infty, r_n))$ is $\mathcal{A}-$measurable for all $n\in \mathbb{N}$ and $f(x) = \tilde{f}(x)$ for all $x$ except maybe those in $\bigcup_{n\in \mathbb{N}} M_0^n$. I can't complete the proof though.
Any suggestions are greatly appreciated.
Answer: Let $(r_n)_{n \in \mathbb{N}}$ an enumeration of $\mathbb{Q}$. A function $f:X \to \mathbb{R}$ is $\mathcal{A}$-measurable iff $$\forall n \in \mathbb{N}: f^{-1}((-\infty,r_n)) \in \mathcal{A} \tag{1}$$
Since $\tilde{f}$ is $\tilde{\mathcal{A}}$-measurable, we have $$\tilde{f}^{-1}((-\infty,r_n)) = A_n \cup M_n$$ where $A_n \in \mathcal{A}$, $M_n \subseteq M_0^n \in \mathcal{A}$ such that $\mu(M_0^n)=0$. As a countable union of null sets, the set $$N:= \bigcup_{n \in \mathbb{N}} M_0^n$$ is also a null set and $N \in \mathcal{A}$. Define $f:X \to \mathbb{R}$ by $$f(x) := \begin{cases} \tilde{f}(x) & x \notin N \\ 0 & x \in N \end{cases}$$ Then $[f \not= \tilde{f}] \subseteq N$, thus $f=\tilde{f}$ almost everywhere since $\mu(N)=0$. Moreover, $$f^{-1}((-\infty,r_n)) = \begin{cases} A_n \cap (X \backslash N) & n \in \mathbb{N} \, \text{such that} \, r_n \leq 0 \\ A_n \cup N & n \in \mathbb{N} \, \text{such that} \, r_n > 0 \end{cases} \quad \in \mathcal{A}$$ From $(1)$ we conclude that $f$ is $\mathcal{A}$-measurable.
Comment: Why is $$f^{-1}((-\infty,r_n)) = \begin{cases} A_n & n \in \mathbb{N} \, \text{such that} \, r_n < 0 \\ A_n \cup N & n \in \mathbb{N} \, \text{such that} \, r_n \geq 0 \end{cases} \quad$$ ?
Comment: @TuringMachine There was a misprint, I corrected it. Let $n$ such that $r_n<0$. Then $$f^{-1}((-\infty,r_n)) = (A_n \cup M_n) \cap (X \backslash N) = A_n \cap (X \backslash N)$$ since $M_n \cap (X \backslash N) \subseteq N \cap (X \backslash N) = \emptyset$ by definition of $N$. Similar proof works for $n$ such that $r_n \geq 0$.
Comment: These two details don't affect the correctness of your proof but I think $[f \neq \tilde{f}]$ is not necessarily measurable, so one should write instead that $[f \neq \tilde{f}] \subseteq N$ and $\mu(N) = 0$. Also, when $r_n = 0$, $f^{-1}((-\infty, r_n)) = A_n\cap (X\setminus N)$. I was thinking the proof would be more complex, which kind of served as a "mental block" for me to complete it. Thanks a lot for helping me out!
Comment: @TuringMachine Yes, of course, you are right.


react navigation not rendering screens

Question: I currently building a simple react native app which has two screens. I am using a react navigation to navigate between screens and when I tried following this guide https://reactnavigation.org/docs/en/hello-react-navigation.html, It doesn't render anything, just displaying a blank screen. Maybe I'm missing something that's why it doesn't render. Here's my js files:
App.js
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Login from './src/components/screens/login';
import Order from './src/components/screens/order';

const AppNavigator = createStackNavigator(
  {
    Login: Login,
    Order: Order
  },
  {
    initialRouteName: 'Login',
  }
);

export default class Sales extends Component {
  render() {
    return (
      <View>
        <App />
      </View>
    );
  }
}

login.js
class Login extends Components {
  static navigationOptions = {
    headerShown: false,
  };

  render() {
    return(
      <View>
        <Button title="Login"
          onPress={() => this.props.navigation.navigate('Order')}
        />
      </View >
    );
  }
}

order.js
class Order extends Component {
  static navigationOptions = {
    headerShown: false,
  };
  render() {
    return (
      <View>
        <View style={styles.button}>
          <Button
            title="Create Order"
            color='#65639E'
          />
        </View>
      </View>
    );
  }
}

Comment: https://reactnavigation.org/docs/en/common-mistakes.html#wrapping-appcontainer-in-a-view-without-flex
Answer: const AppNavigator = createStackNavigator(
  {
    Login: Login,
    Order: Order
  },
  {
    initialRouteName: 'Login',
  }
);

export default class Sales extends Component {
  render() {
    return (
      <View>
        <App /> // this is worng.. As there is no app component. Never wrap
   //AppNavigator inside a view
      </View>
    );
  }
}

The right thing should be. Just trying to tempelate your requirement.
class Login extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Login Screen</Text>
      </View>
    );
  }
}

class Order extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Order Screen</Text>
      </View>
    );
  }
}

const AppNavigator = createStackNavigator({
  Login: Login,
  Order: Order
});

export default createAppContainer(AppNavigator);

I hope I'm able to make my point. If any confusion do mention in the comment. More than happy to help you out.
Answer: The way i fixed this for myself was by removing align-items: center and justify-content: center from the main app container.
Answer:     export default class Sales extends Component {
   render() {
     return (
       <View>
        <App /> // This code right here
       </View>
     );
  }

 }

You're rendering <App /> but you don't have an App Component. Maybe try using <Login />
Comment: I forgot to include const App = createAppContainer(AppNavigator);
Comment: @ana What's the url when you run the project?
Comment: how to find the url? did you mean 10.0.2.2:8081 ?
Comment: When you open the project in the browser? What's the url? Is it `http://localhost:8081` or `http://10.0.2.2:8081`? Try adding /Login in the url because the initial route name is 'Login'
Comment: when I run the project in the browser with both http://localhost:8081 /Login and http://10.0.2.2:8081/Login this was shown: cannot Get /Login
Comment: I just found why it's not rendering, I changed the render part in app.js export default class Sales extends Component {
  render() {
    return ;
    );
  }
}
Answer: try this
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Login from './src/components/screens/login';
import Order from './src/components/screens/order';

const AppNavigator = createStackNavigator(
{
    Login: Login,
    Order: Order
},
{
    initialRouteName: 'Login',
}
);

class Sales extends Component {
render() {
    return (
        <View>
            <AppNavigator />  --> pass here your navigation
        </View>
    );
}

}

export default createAppContainer(AppNavigator);

react navigation not rendering screens


Blocking custom toast from package in Android

Question:
NotificationService     system_server                        W  Blocking custom toast from package com.example.androidtest due to package not in the foreground at time the toast was posted
Blockquote

When I try to show a custom Toast right after request for permission
On Android >= 11, I got the above warning and the custom Toast won't show
private val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->

}

override fun onCreate(savedInstanceState: Bundle?) {
    ...

    buttonCamera.setOnClickListener {
        requestPermissionLauncher.launch(android.Manifest.permission.CAMERA)
        makeCommonToast("ABc").show()
    }
}

private fun makeCustomToast(message: CharSequence): Toast {
    return Toast.makeText(context, "", Toast.LENGTH_LONG).apply {
        val rootView = LayoutInflater.from(context).inflate(R.layout.my_custom_toast, null)
        view = rootView
        val textView = rootView.findViewById<TextView>(R.id.text_message)
        textView.text = message
    }
}

I thought the app still in foreground but the Toast won't showing
Answer: The above  warning which I got is from NotificationManagerService#checkCanEnqueueToast

And, here is the **isPackageInForegroundForToast** function

There are many cases which will block the custom Toast showing, and in my above case, it because I show Toast behind a translucent Activity (which is Request Permission activity)
The solution for this can be

Not using custom Toast, use standard text toast
Show custom Toast later, when app in foreground


How were chi-squared levels calculated in Feller's Vol 1, VI.7 Table 5?

Question: Here is the table from An Introduction to Probability Theory and Its Applications:

I tried to use this approach:
x <- c(753, 266, 49, 5)
m <- c(752.3, 267.1, 47.4, 6.2)
chisq.test(x, p=m/sum(m))

which gives me
  Chi-squared test for given probabilities

 data:  x
 X-squared = 0.2914, df = 3, p-value = 0.962

i.e. close but still different from 95% in the table.
For the last row in the table we get:
x <- c(444, 252, 59, 1)
m <- c(461.6, 227.7, 56.2, 10.5)
chisq.test(x, p=m/sum(m))

 Chi-squared test for given probabilities

 data:  x
 X-squared = 12, df = 3, p-value = 0.00739

Comment: Using the *raw* data (which, being counts, are exact) and the posted mean of $ 0.35508$ (which has 5 significant figures) I obtain a chi-squared statistic of $0.27245$ with a p-value of $0.96513$ (with 3 df), which is all the precision the information is able to support.  But scanning the table shows Feller was posting p-values only to the nearest $0.05.$  It's unrealistic to suppose that 11 experimental chi-squared statistics would all be exactly multiples of $0.05$ anyway.
Comment: Presumably Feller (or an assistant) was just using published tables and not even interpolating. It's a small historical puzzle of which tables were being used (e.g. Fisher and Yates?) and (depending on taste) a slightly amusing question of checking the results given and of seeing whether there are gross errors. Now as you exemplify we can get P-values directly but otherwise what is the precise goal of your question?
Comment: Now that's a different question. Using quite different software I too get a chi-square test statistic of 0.2914 and  $P =$  0.962 for the first calculation, so I guess you are using R correctly, which isn't always on-topic here.
Comment: @NickCox If Feller had R would he put values from R I got into the table 5? Am I using chisq.test correctly?
Comment: @whuber That's the answer - I like it a lot!
Answer: I cannot reproduce the rightmost column in the table.
It is evident that each row summarizes a table of counts by giving the frequencies $f_i$ of 0, 1, 2, and 3 or more, of which there are $N$ altogether.  It uses Maximum Likelihood to fit a Poisson distribution to these frequencies: the Poisson parameter estimates are the numbers $\lambda$ in the $Np(k;\lambda)$ expressions at the left and the corresponding expected frequencies $e_i$ appear to its right, beneath the data.  One would therefore suppose the "$\chi^2$ levels" at the right are upper tail areas of the chi-squared(df=3) statistics $\chi^2=\sum (f_i-e_i)^2/e_i,$ aka p-values.
Here is an accurately computed rendition of part of the table, as printed in R (with suitable rounding):
    lambda    0   1  2  >2    N   chi.sq     p
--  ------  --- --- --  -- ----  ------- -----
1  0.35322  753 266 49   5 1073  0.27030 0.966
2  0.45455  434 195 44   9  682  0.27970 0.964
3  0.27717  280  75 12   1  368  0.23118 0.972
4  0.11808 2278 273 15   0 2566  0.74954 0.861
5  0.25296  593 143 20   3  759  1.34312 0.719
6  0.21059  639 141 13   0  793  1.42313 0.700
7  0.28631  359 109 13   1  482  0.70899 0.871
8  0.33572  493 176 26   2  697  1.25717 0.739
9  0.39867  793 339 62   5 1199  3.33269 0.343
10 0.40430  579 254 47   3  883  3.70138 0.296
11 0.49339  444 252 59   1  756 11.99290 0.007

I checked the first and last p-value by invoking chisq.test as shown in the question: mine agree with it exactly, indicating I am using the correct degrees of freedom, etc.
Some of the p-values are nowhere close to those in the original table, even accounting for the evident reporting to the nearest 5% in the original.  Because the columns of p-values are qualitatively similar, tending to decrease down the table, I suspect erroneous computation of the p-values in the original.  Perhaps a crude approximation was used.
This is the R code I used.
#
# Negative log likelihood.
#
ll <- function(theta, x) {
  lambda <- exp(theta)
  n <- length(x) - 2
  -sum(c(dpois(0:n, lambda, log=TRUE), ppois(n, lambda, lower.tail=FALSE, log.p=TRUE)) * x)
}
X <- do.call(rbind, args=lapply(list( c(753, 266, 49, 5),
                                      c(434, 195, 44, 9),
                                      c(280, 75, 12, 1),
                                      c(2278, 273, 15, 0),
                                      c(593, 143, 20, 3),
                                      c(639, 141, 13, 0),
                                      c(359,109,13,1),
                                      c(493,176,26,2),
                                      c(793,339,62,5),
                                      c(579, 254, 47, 3),
                                      c(444,252, 59, 1)
), function(x) {
  names(x) <- as.character(seq.int(x)-1)
  names(x)[length(x)] <- paste0(">", length(x)-2)
  fit <- nlm(ll, log(sum(x * seq.int(x)) / sum(x) - 1), x=x)
  lambda <- exp(fit$estimate)
  N <- sum(x)
  e <- c(dpois(0:(length(x)-2), lambda), ppois(length(x)-2, lambda, lower.tail=FALSE)) * N
  chi.sq <- sum((x-e)^2/e)
  p.value <- pchisq(chi.sq, length(x) - 1, lower.tail=FALSE)
  data.frame(lambda=round(lambda, 5), as.list(x), N=sum(x),
             chi.sq=round(chi.sq, 5), p=round(p.value, 3))
}))
print(X)


Why "Cassandra" uses "StatefulSet" instead of "Deploymdnt" file for "Kubernetes"?

Question: I am trying to deploy Cassandra on my local Kind cluster running on my Ubuntu 22.04 machine. The only instruction I found is this, that uses a StatefulSet for that. I am just wondering to know, isn't a Deployment file something newer? Why they didn't use Deployment file instead of StatefulSet? If it is better to use a Deployment file, can anybody help me to convert this StatefulSet to a Deployment file?
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: cassandra
  labels:
    app: cassandra
spec:
  serviceName: cassandra
  replicas: 3
  selector:
    matchLabels:
      app: cassandra
  template:
    metadata:
      labels:
        app: cassandra
    spec:
      terminationGracePeriodSeconds: 1800
      containers:
      - name: cassandra
        image: gcr.io/google-samples/cassandra:v13
        imagePullPolicy: Always
        ports:
        - containerPort: 7000
          name: intra-node
        - containerPort: 7001
          name: tls-intra-node
        - containerPort: 7199
          name: jmx
        - containerPort: 9042
          name: cql
        resources:
          limits:
            cpu: "500m"
            memory: 1Gi
          requests:
            cpu: "500m"
            memory: 1Gi
        securityContext:
          capabilities:
            add:
              - IPC_LOCK
        lifecycle:
          preStop:
            exec:
              command:
              - /bin/sh
              - -c
              - nodetool drain
        env:
          - name: MAX_HEAP_SIZE
            value: 512M
          - name: HEAP_NEWSIZE
            value: 100M
          - name: CASSANDRA_SEEDS
            value: "cassandra-0.cassandra.default.svc.cluster.local"
          - name: CASSANDRA_CLUSTER_NAME
            value: "K8Demo"
          - name: CASSANDRA_DC
            value: "DC1-K8Demo"
          - name: CASSANDRA_RACK
            value: "Rack1-K8Demo"
          - name: POD_IP
            valueFrom:
              fieldRef:
                fieldPath: status.podIP
        readinessProbe:
          exec:
            command:
            - /bin/bash
            - -c
            - /ready-probe.sh
          initialDelaySeconds: 15
          timeoutSeconds: 5
        # These volume mounts are persistent. They are like inline claims,
        # but not exactly because the names need to match exactly one of
        # the stateful pod volumes.
        volumeMounts:
        - name: cassandra-data
          mountPath: /cassandra_data

  # These are converted to volume claims by the controller
  # and mounted at the paths mentioned above.
  # do not use these in production until ssd GCEPersistentDisk or other
  # ssd pd
  volumeClaimTemplates:
  - metadata:
      name: cassandra-data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: fast
      resources:
        requests:
          storage: 1Gi
---
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: fast
provisioner: k8s.io/minikube-hostpath
parameters:
  type: pd-ssd

Answer: A StatefulSet is different from a Deployment. From the documentation:

Like a Deployment, a StatefulSet manages Pods that are based on an identical container spec. Unlike a Deployment, a StatefulSet maintains a sticky identity for each of their Pods. These pods are created from the same spec, but are not interchangeable: each has a persistent identifier that it maintains across any rescheduling.

You use StatefulSets when your pods need to maintain some sort of unique state -- for example, the volumeClaimTemplates section of the manifest means that each pod gets a unique PersistentVolumeClaim. This isn't possible using a Deployment.
In general you cannot convert a StatefulSet into a Deployment unless you only plan on having a single replica.
Comment: That's correct (because each mysql instance will e.g. need its own volume for data, which you can do with a statefulset but not with a deployment).
Comment: Thank you so much for clarifying. But for `mysql` for example, it also needs a persistent volume memory, but still they use `deployment` file for it as you can see here https://kubernetes.io/docs/tasks/run-application/run-single-instance-stateful-application/ .... What is the difference?
Comment: The title of that page is "Run a Single-Instance Stateful Application". That reflects what I said in my answer: you can only use a Deployment to run stateful application if you only have a single replica.
Comment: So this is not specific to `cassandra` and even for `mysql` we need a `StatefulSet` instead of `deployment` file if we want to have more than one `mysql` instance.
Comment: I tried to also use `StatefulSet` for deploying `mysql` on multi-nodes and I think I did it sucessfully, but I am interested to know why do I see `READY 2/2` when I try `kubectl get pods`? Because for `cassandra clusters I see `READY 1/1`. This is the first time I see `2/2`. What are they?
Comment: You might want to open a new question. Include both the output of `kubectl get pods` and the YAML manifest used to create the pods.
Comment: I opened a new question and also asked my previous question there: https://serverfault.com/questions/1119154/crashloopbackoff-while-deploying-mysql-on-multi-node-cluster


Select comparação dias com data atual não funciona

Question: Eu tenho este select que trás os dados da seguinte forma, se DataCobranca for 10, e hoje for o dia 05, ele vai buscar todos os clientes que for dia 10, pois vai ser gerado 5 dias antes, ou caso DiaEspecificoMarcar for true e DiaEspecifico for igual o dia de hoje, ele também vai aparecer neste select
var contrato = db
    .Contrato
    .Include(a => a.PedidoVenda)
    .Include(a => a.Cliente)
    .Where(a => a.PedidoVenda.EmpresaID == model.EmpresaID &&
                a.Cancelado == false &&
                DateTime.Parse(a.PrimeiraCobranca.ToString("dd/MM/yyyy")) >= DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy")) &&
                a.DiaEspecificoMarcar == true && a.DiaEspecifico == int.Parse(DateTime.Now.ToString("dd"))) ||
                (a.DiaEspecificoMarcar == false && (int.Parse(a.DataCobranca.Substring(1, 2)) - a.PedidoVenda.Empresa.DataProcessamentoNota) == int.Parse(DateTime.Now.ToString("dd")))
    ).ToList();

Só que quando o DataCobranca for 05, ele precisa ser gerado 5 dias antes, ou quanto estiver no parâmetro, então como estou usando data retroativa, no dia 31/03 e no dia 01/04, onde deveria puxar os do dia 05, mas ele sempre puxa zerado.
Na verdade, porque a DataCobranca = 5, e o DataProcessamentoNota = 5, como ele faz a conta, ele verifica 5-5 = 0, no caso ele deveria pegar o último dia do mês, ou então outro caso, se DataProcessamentoNota = 10 ele deveria fazer a conta 5 - 10, e então seria -5. Sendo que o resultado deveria ser 10 dias antes. Como calcular como dias mesmo. Como posso verificar?
Comment: `int.Parse(DateTime.Now.ToString("dd"))` é só `DateTime.Now.Day`
Comment: `DateTime.Parse(a.PrimeiraCobranca.ToString("dd/MM/yyyy"))`, que parse maluco é esse? a primeiraCobranca não é um datetime? tipo e também o que faz isso nada? Veja tem problemas no seu código
Comment: Mariana a.PrimeiraCobranca é do tipo `DateTime`? Qual é a versão do `EntityFramework`? se for não é assim que se faz !
Comment: Sim, é do tipo `DateTime`, a versão do EntityFrameworkCore é `2.1.4`
Comment: onde você fez isso: `DateTime.Parse(a.PrimeiraCobranca.ToString("dd/MM/yyyy"))` é só isso `a.PrimeiraCobranca.Date`.
Comment: @VirgilioNovic eu preciso de verificar se a data da primeira cobrança é maior ou igual ao dia que está sendo gerado. é sim, estou pegando somente a date, e não as horas.
Comment: @VirgilioNovic até então quando não fica negativo funciona, eu preciso fazer a parte do `int.Parse(a.DataCobranca.Substring(1, 2)) - a.PedidoVenda.Empresa.DataProcessamentoNota` que é  a que está dando problema quando gera um negativo, pois está sendo tratado como `int` e não `DateTime`
Comment: suas conversões estão todas erradas! esse é o problema também, e outro assunto gera conversões a nivel do cliente é ruim essa pesquisa.
Comment: Aqui você precisa pegar o dia? `a.DataCobranca.Substring(1, 2)` ???? o correto é `a.DataCobranca.Day` internamente ele faz a conversão.
Comment: No caso a `DataCobranca` é do tipo string, ela salva o T05, T10, etc, por isso utilizo o `Substring` para pegar os dois números.
Comment: então esse pode ficar como está! `DataCobranca`
Comment: Vou te dar uma dica! faz um pesquisa somente com o tipo 10  e depois faz uma só com o tipo 5, restringe dessa forma. Se precisa juntar essas duas no final é fácil, mas, do jeito que está muito confuso entender até a sua pergunta ... !!!
Comment: @VirgilioNovic mas até então não resolve o meu problema, já que o problema está aqui `int.Parse(a.DataCobranca.Substring(1, 2)) - a.PedidoVenda.Empresa.DataProcessamentoNota`, o que me passou melhora o código, mas não resolve o problema.
Comment: A melhoria do código foi bom para você ver o caminho errado que estava tendo, mas, ai nessa linha `int.Parse(a.DataCobranca.Substring(1, 2)) - a.PedidoVenda.Empresa.DataProcessamentoNota` tem outro problema, mas, diz ai qual é o problema dessa linha?
Comment: O problema é data, ele está comparando a `DataCobranca = T10` com a `DataProcessamentoNota = 5`, ou seja pegando o `Substring` 10 - 5 = 5 ele saberia que para gerar a nota no dia 5, agora quando é menor, por exemplo `DataCobranca = T05` e `DataProcessamentoNota = 05` 05-05 ele daria 0, ou 05-10 = -5, que ele vai comparar com o dia atual, para ver se é o dia correto, no caso 05-05, ele deveria gerar no ultimo dia do mes anterior, e 05-10, ele deveria gerar no dia 26. Não sei se deu pra entender.
Answer: Pode ser feito desta forma
var contrato = db
.Contrato
.Include(a => a.PedidoVenda)
.Include(a => a.Cliente)
.Where(a => a.PedidoVenda.EmpresaID == model.EmpresaID &&
            a.Cancelado == false &&
            DateTime.Parse(a.PrimeiraCobranca.ToString("dd/MM/yyyy")) >= DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy")) &&
            a.DiaEspecificoMarcar == true && a.DiaEspecifico == int.Parse(DateTime.Now.ToString("dd"))) ||
            (a.DiaEspecificoMarcar == false && ((int.Parse(a.DataCobranca.Substring(1, 2))
    - a.PedidoVenda.Empresa.DataProcessamentoNota)<=0?DateTime.Now.Date.AddDays(int.Parse(a.DataCobranca.Substring(1, 2))
    - a.PedidoVenda.Empresa.DataProcessamentoNota).Day:int.Parse(a.DataCobranca.Substring(1, 2)) - a.PedidoVenda.Empresa.DataProcessamentoNota) == int.Parse(DateTime.Now.ToString("dd")))
).ToList();


Counting permutations with given condition

Question: I need to find number of permutations $p$ of set $\lbrace 1,2,3, \ldots, n \rbrace$ such for all $i$ $p_{i+1} \neq p_i + 1$.
I think that inclusion-exclusion principle would be useful. Let $A_k$ be set of all permutation that for every permutation $a$ in this set $a_{k+1} \neq a_k + 1$. So our answer would be $| A_1 \cap A_2 \cap \ldots \cap A_n |$. Could you help me with completing the proof?
Answer: We can complete Penitent's induction argument as follows:
Denote the number of valid permutations of $k+1$ elements by $a_k$. There are two ways to generate a valid permutation of $k+1$ elements from a permutation of $k$ elements: Either by inserting $k+1$ into a valid permutation of $k$ elements at any of the $k+1$ gaps except the one behind $k$; this yields $ka_k$; or by inserting $k+1$ into a single consecutive pair that made the permutation invalid, thus making it valid. Each permutation of $k$ elements with a single consecutive pair corresponds to exactly one valid permutation of $k-1$ elements obtained by merging the pair and suitably renumbering the remaining elements. This yields a contribution $(k-1)a_{k-1}$, since each of the $k-1$ elements in each of the $a_{k-1}$ valid permutations of $k-1$ elements can be expanded into a pair. Thus we have the recurrence relation
$$
a_{k+1}=ka_k+(k-1)a_{k-1}
$$
with the initial values $a_1=a_2=1$. We can rearrange the recurrence relation
$$!(k+2)=(k+1)(!(k+1)+!k)$$
for the number $!k$ of derangements of $k$ elements to
$$
\frac{!(k+2)}{k+1}=k\frac{!(k+1)}k+(k-1)\frac{!k}{k-1}\;.
$$
This is our present recurrence relation with $a_k=\frac{!(k+1)}k$, and the initial values coincide, so this is a "closed form" for $a_k$, though since the number of derangements is usually counted using inclusion-exclusion, it's not really more "closed" than what you'd get directly using inclusion-exclusion in the way Rob outlined.
I posted this new question asking for a combinatorial proof of the count $a_k=\frac{!(k+1)}k$.
By the way, this is OEIS sequence A000255, shifted by one.
Answer: I would recommend initially counting the set of all of those permuttations and
then using inclusion-exclusion on this set by systematically removing
the sets $B_k$ which we can define as the set of all permutations where
$p_k = p_k+1$. I.e. We can account for the set of all permutations as
$$|S| = n!,$$
and count each $A_k$ given that there are $n-1$ options of $p_k$ and $n-2$
free variables left as
$$|A_k| = n-1 \times (n-2)! = (n-1)!.$$
Performing inclusion-exclusion by using the $A_k$'s as removal sets should
follow cleanly.
Answer: I believe an induction proof might work nicely.
The base case $ n=1 $ is easy enough, so consider the step from $ n=k $  to  $ n=k+1 $:
Of the $ k+1 $ gaps you could place the number $ k+1 $, only one will be illegal (immediately after $k$).  So we get $|A_{k+1}|=k|A_k|$, $|A_1|=1$
It doesn't take long to generate $|A_n|=(n-1)!$
Comment: You missed the fact that you could place $k+1$ into an invalid permutation, breaking up the only pair that made it invalid. For instance, for $n=3$, there is $1,3,2$ in addition to the two permutations you counted.


Asymptotic distribution of "plug-in" variance estimator for Bernoulli data

Question: I am stuck at the following exercise:

Let $(X_k)_k$ be a sequence of i.i.d. Bernoulli$(p)$ distributed RVs with $p=1/2$. We want to estimate $Var(X_1) = p(1-p) = p^2 =: \tau_p^2$ by directly plugging in the natural estimator $\widetilde{p} := \frac{1}{n}\sum_{i=1}^n X_i$ of $p$. We call this estimator for the variance $\widetilde{\tau}^2_{p,n}$. Examine the limit distribution of $\widetilde{\tau}^2_{p,n}$.

I do not see how I could do this. I recognise that we are basically looking at a uniform distribution of two events and I see that  $\widetilde{\tau}^2_{p,n}$ has a rather nice formula
$$\widetilde{\tau}^2_{p,n} = \frac{1}{n^2} \biggl(\sum_{i=1}^n X_i \biggr) ^2 = \overline{X}^2,$$
but I do not see how to proceed now.  Intuitively I would say that $\widetilde{\tau}^2_{p,n}$ should also be uniformly distributed, but how can I prove this?
Comment: To see that your intuition is incorrect, consider that the distribution of $\tilde p$ must be $1/n$ times a Binomial$(n,p)$ distribution, which for $n\gt 1$ is far from uniform, suggesting (correctly) the distribution of $\tilde{\tau}^2_{p,n}$ is nonuniform, too.  BTW, the limit distribution of $\tilde{\tau}^2_{p,n}$ is the constant $1/4$ -- but that's a trivial and almost worthless observation.  The question likely wants you to *standardize* the distribution.
Comment: Could you use a Monte Carlo simulation?
Answer: Firstly, let's start by fixing your estimator.  Although $p(1-p)=p^2$ in the special case where $p=\tfrac{1}{2}$, in the context of parameter estimation, we don't know the parameter $p$, and so we don't know that $p(1-p)=p^2$.  Consequently, the plug-in variance estimator is $\tilde{\tau}^2_{n} = \tilde{p}_n (1-\tilde{p}_n)$, not $\tilde{p}_n^2$.  I will show an asymptotic approximation derived using the central limit theorem to approximate the true distribution function for the estimator.  This is quite a tricky problem, and it has a few parts, but it leads to quite a useful asymptotic form.

Let's start by writing the variance estimator out in terms of the number of "successes" in the underlying Bernoulli random variables.  Let $K_n \equiv \sum_{i=1}^n X_i$ denote the number of successes.  Then we can write the plug-in estimator as:
$$\tilde{\tau}^2_{n}
= \tilde{p}_n (1-\tilde{p}_n)
= \frac{1}{n^2} (n K_n - K_n^2).$$
We will also note that, in the present case where $p=\tfrac{1}{2}$, we can use the central limit theorem to obtain the asymptotic distribution:
$$Z_n \equiv 2 \sqrt{n} \Bigg( \frac{K_n}{n} - \frac{1}{2} \Bigg) \sim \text{N}(0,1).$$
The range of possible values for the variance estimator is $0 \leqslant \tilde{\tau}^2_{n} \leqslant \tfrac{1}{4}$.  For all $0 \leqslant t \leqslant \tfrac{1}{4}$, the cumulative distribution function for this estimator is given by:
$$\begin{align}
\mathbb{P}(\tilde{\tau}^2_{n} \leqslant t)
&= \mathbb{P}(n K_n - K_n^2 \leqslant t n^2) \\[14pt]
&= \mathbb{P}(K_n^2 - n K_n + t n^2 \geqslant 0) \\[8pt]
&= 1 - \mathbb{P} \Bigg( \frac{1 - \sqrt{1-4t}}{2} < \frac{K_n}{n} < \frac{1 + \sqrt{1-4t}}{2} \Bigg) \\[6pt]
&= 1 - \mathbb{P} \Bigg( - \frac{\sqrt{1-4t}}{2} < \frac{K_n}{n} - \frac{1}{2} < \frac{\sqrt{1-4t}}{2} \Bigg) \\[6pt]
&= 1 - \mathbb{P} \Bigg( - \sqrt{(1-4t)n} < 2 \sqrt{n} \Bigg( \frac{K_n}{n} - \frac{1}{2} \Bigg) < \sqrt{(1-4t)n} \Bigg) \\[8pt]
&= 1 - \mathbb{P} \Big( - \sqrt{(1-4t)n} < Z_n < \sqrt{(1-4t)n} \Big). \\[6pt]
\end{align}$$
(The third step in this equation follows from re-arrangement of the quadratic inequality; full working shown below.)  When $n$ is large we have the asymptotic approximation $Z_n \sim \text{N}(0,1)$ so we get the asymptotic approximation $\mathbb{P}(\tilde{\tau}^2_{n} \leqslant t)
\approx F_\text{asymp}(t)$ given by:
$$F_\text{asymp}(t)
= 1 - \frac{\Phi ( \sqrt{(1-4t)n} ) - \Phi ( -\sqrt{(1-4t)n} )}{\Phi (\sqrt{n}) - \Phi (-\sqrt{n})}.$$
(Note that I have added a denominator here to obtain a distribution function that is valid for all $n$ over the range $0 \leqslant t \leqslant \tfrac{1}{4}$.  This form ensures that we get zero probability when $t=0$ and unit probability when $t = \tfrac{1}{4}$.)  Differentiating then gives the asymptotic density:
$$\begin{align}
f_\text{asymp}(t)
&= \sqrt{\frac{n}{2 \pi (1-4t)}} \cdot \frac{\exp ( - (1-4t)n/2 )}{\Phi (\sqrt{n}) - \Phi (-\sqrt{n})} \cdot \mathbb{I}(0 \leqslant t \leqslant \tfrac{1}{4}) \\[6pt]
&= \frac{\mathbb{I}(0 \leqslant 1-4t \leqslant 1)}{\Phi (\sqrt{n}) - \Phi (-\sqrt{n})} \cdot \text{Ga} \Big( 1-4t \ \Big| \ \text{Shape} = \frac{1}{2}, \ \text{Rate} = \frac{n}{2} \Big). \\[6pt]
\end{align}$$
This means that our estimator has an asymptotic distribution that is a truncated gamma distribution:
$$1 - 4 \tilde{\tau}^2_{n} \overset{\text{Asymp}}{\sim} \text{TruncGamma} \Big( \text{Shape} = \frac{1}{2}, \ \text{Rate} = \frac{n}{2}, \ \text{Upper Bound} = 1 \Big).$$
This gives you an asymptotic density function based on approximating the binomial random variable $K_n$ using the central limit theorem.  The asymptotic form is a continuous approximation to a discrete distribution, but it should give quite a good approximation to the true distribution when $n$ is large.

Working for the quadratic inequality: Using quadratic formula we can find the roots of the quadratic form shown in the inequality, which are:
$$r = n \cdot \frac{1 \pm \sqrt{1-4t}}{2}.$$
Consequently, we can write the quadratic form as:
$$K_n^2 - n K_n + t n^2
= \Big(K_n - n \cdot \frac{1 - \sqrt{1-4t}}{2} \Big) \Big( K_n - n \cdot \frac{1 + \sqrt{1-4t}}{2} \Big).$$
The quadratic inequality $K_n^2 - n K_n + t n^2 \geqslant 0$ occurs when both terms are non-negative, or both terms are non-positive.  This excludes the range:
$$\frac{1 - \sqrt{1-4t}}{2} < \frac{K_n}{n} < \frac{1 + \sqrt{1-4t}}{2}.$$


Integral of absolute value of Brownian motion

Question: I know it is a really stupid question and it should be quite easy, but how can I show that $\int_0^{\infty}|B_t|\mathbb{d}t=\infty$ a.s. with $B_t$ being a standard brownian motion?
I just don't get it.
What I tried so far: I know that $\limsup_{t\rightarrow\infty}|B_t|=\infty$ and the liminf being 0. Hence I know that for a given $K$ there is a sequence $t_n$ s.t. $B_{t_n}>K$. But by continuity I only know that for every $t_n$ there is a $\delta_n>0$ s.t. $B_t>K$ for $t\in t_n\pm\delta$. But I don't know that these $\delta_n$ won't converge to $0$...
Answer: Hint: For every $t$ there exists $s\geqslant t$ such that $|B_s|\geqslant2$. Then, the first hitting time of $1$ after time $s$ has a constant distribution. Then sum these contributions.
Another argument is to note that by scaling $(B_{2t})$ is distributed like $(\sqrt2B_t)$ hence the integral $K=\int_0^\infty|B_t|\mathrm dt$ is distributed like $2\sqrt2K$. Since $K\gt0$ almost surely, this implies that $K=+\infty$ almost surely.
Edit: About the last implication, consider some random variable $Z$ such that $P[Z\gt0]=1$ and $Z$ equals $aZ$ in distribution, with $a\gt1$. Then for every $z\gt0$, $P[Z\gt z]=P[aZ\gt z]$ hence $P[Z\gt z]=P[Z\gt z/a]=\cdots=P[Z\gt z/a^n]\to1$ when $n\to\infty$. This implies that $Z\gt z$ almost surely, for every $z\gt0$. Thus, ...
Comment: Thanks again Did! And there is no problem in using the scaling property to show this a.s. equivalence (since they only coincide in distribution)? Because I worried a bit about using it here.
Btw is the equality $\mathbb{P}[\sup_{s\in[0,t]}|B_s|]=\mathbb{P}[\sup_{s\in[0,t]}|\sqrt{s}B_1|]>0$ true? I don't think so, since the SUP of these guys doesn't have to have the same law, right?
Comment: See Edit. About the second part of your comment: no indeed, since $(B_s)_s$ and $(\sqrt{s}B_1)_s$ differ in distribution.


Insert data into server using webservice through android

Question: I have a web method in .net "InsertData("parameter1,"parameter2"")" .how can I implement it through android.
              How can I insert data directly in server through android using .net webservice.
How can I pass parameter values?
Answer: maybe that helps:
How to call a .NET web service from android?


Implement Method Gauss Jordan Elimination in Delphi

Question: This is my homework from my school to make Gauss-jordan elimination in delphi, but..I got some problem here...
I Made like this :
procedure TForm1.Button3Click(Sender: TObject);
var
  n,i,j,k,bar,kol:integer;
  a:array [1..100,1..100]of real;
  x:array [1..100]of real;
  faktor:real;
begin
  memo1.Clear;
  n:=stringgrid2.RowCount-1;
  kenalmatriks;
  StringGrid2.RowCount := baris;
  StringGrid2.ColCount := kolom;

  for i:=1 to n do
  begin
    for j:=1 to n+1 do
    begin
      a[i,j]:=strtofloat(stringgrid1.cells[j,i]);
    end;
  end;

  for k:=1 to n do
  begin
    faktor:=a[k,k];
    for j:=1 to n+1 do
    begin
      a[j,k]:=a[j,k]/faktor;
    end;
    for i:=1 to n do
    begin
      if i<>k then
      begin
        faktor:=a[i,k];
        for j:=1 to n+1 do
        begin
          a[i,j]:=a[i,j]-faktor*a[k,j];
        end;
      end;
    end;
  end;

  for bar:=1 to n do
  begin
    for kol:=1 to n+1 do
    begin
      stringgrid2.cells[kol,bar]:=floattostr(a[bar,kol]);
    end;
  end;
end;

The result must like this :
1   0   0   2
0   1   0   7
0   0   1   -3

But, mine :
--   --   --   --
--   1    0    15.33
--   0    1    2

I hope I can finish this... :(
anyone...please help...
Comment: why are you using `strtofloat` if you want whole numbers?
Comment: Did you try to use a debugger?
Comment: We now know the expected output but have no clue what the input values are.  Please make an effort and show a complete example.
Comment: Seems you have more than one problem here, your array starts at 1,1 but you access values from a stringgrid which would start at 0,0 (stringgrid1.cells[0,0] would be the top left value). As long as we dont know what your stringgrid looks like I would say you miss some values.
Comment: You must do what I have told you at least once already. Make an SSCCE. A complete program. That contains the input hard coded. With no GUI. A console app that prints output to console. That we can paste into our compiler. Gauss-Jordan is simple enough. Once you supply SSCCE we'll be able to correct. Remember to keep the numerical code separate from the output. Don't mix maths and GUI. Ever.
Answer: Disclaimer: I don't know anything about Gauss-jordan elimination and never heard of it.
The answer is clear though!
Either your math is off, or you are grabbing the wrong numbers.
As was suggested by manuell in the first comment to your post, you need to see what numbers are being used.
A simple way to debug in console that I use is: writeln('whatever variable: ' + VARIABLE).
you can use a MemoList if you are in a GUI development to do the same thing. You will be surprised of the results sometimes.
Also use the right functions for what you want floatToStr and strToFloat are not what you want probably.
Edit:
Looked up Gauss-jordan elimination also known as row reduction and it turns out to be simple matrices algebra.
I never knew that is what is called likely because although attributed to Gauss, it was already known to Chinese mathematicians in 179 AD.
A good example is found here: http://www.youtube.com/watch?v=Xc37YM59vVA
A good example in Delphi, although written in an earlier version: Delphi-3 programming language, with source code is found here
Another example but has much more than Gaussian elimination so you have to look at the code can be found here
Here is an example in C++
So now I am sure you have solved it or lost your login to SO. Good luck and enjoy the process as that is the best part.


Under what condition on a set $S$ does $f$ exist such that $f \cdot S_k$ has the same value for all $S_k\in S$?

Question: this is my first time using this site so I apologize if I'm unclear or using poor convention.
I'm working on a problem with wireless power transfer, which long story short involves a set of transfer functions, which I will call S, which can be thought of a vector of length n. There are k such transfer functions. I want to pick a constant nontrivial frequency vector f of length n that will result in the same value for all transfer functions.
I believe the best way to write out this problem is:
Find $f$ such that $f \cdot S_k = C,  \forall k $, where $C$ is a constant.
I know this f exists for certain conditions of S because I have found it using a GA, but I am unsure how best to characterize this, or how to prove that a GA is required, if it is.
Under what conditions of S does an f exist that meets my conditions? After determining this my next step would be determining if f can be found analytically if S is known for all k.
Any advice would be greatly appreciated.
Comment: What is GA? genetic algorithm?
Comment: Correct, Genetic algorithm, sorry for not clarifying. It starts with a randomly generated vector of length n and maximizes the constant C.
Answer: It seems the following.
If I understood you right, I can formulate your question as follows. When for a given $n\times k $matrix $S=(S_1,\dots, S_k)^t$ there exists a vector $f$ such that $Sf=Ce$, where $e=(1,1,\dots, 1)$ and $C\ne 0$? Without loss of generality we may suppose that $C=1$. Then such a vector $f$ exists iff $\operatorname{rank} S=\operatorname{rank} (S|e)$, where $S|e$ is a matrix obtained from $S$ by concatenating the vector $e$ to the right side of $S$. And provided such a vector $f$ exists, you can find it analytically by solving a linear system $Sf=e$.
Comment: +1 for deciphering the question. But I think your conclusion is that a solution $f$ exists if the system specifying $f$ has a solution, which is not a great advance. But of course the fact that it is a linear system should make solving it not too impossible.
Comment: @MarcvanLeeuwen I worked with non mathematicians, which applied mathematics. And to solve their problem it was essentially to build a good and clear mathematical model of it. :-)
Comment: Thanks for you input, I am indeed a non mathematician and am looking for help formulating my question as much as a solution.

@Alex Ravsky: If I understand you correctly, the solution of $ Sf=e $ solving for f would give $ f = S^-1 e $ where $e$ is a $n$ length vector of 1s?
Comment: @user3838540 Not necessarily. The matrix $S$ may be degenerated (that is, $\det S=0$) or even not square, and then the matrix $S^{-1}$ does not exist.
Comment: Ah yes, $det(S) = 0$ would be a problem, which is a great constraint to look at. Perhaps a pseudo inverse method would be more efficient than my GA, maybe Neumann series would be appropriate, not that I'm familiar with those methods much but its a great direction to look at. Thanks!