Real valued continuous function is the unique difference of two positive functions

Question: Let $X$ be a compact Hausdorff space and let $f: X \to \mathbb{R}$ be a continuous function. I want to prove that we have a unique decomposition
$$f= f_1 - f_2$$
where $f_1 f_2 = 0 = f_2 f_1$.
where $f_1, f_2: X \to \mathbb{R}$ are continuous positive functions. I managed to show the existence, but I'm not sure how I can prove the uniqueness.
Comment: Intuitively, thanks to continuity on some interval $I$ then $f=f_1$ since $f_2=0$ there. Similarly $f=g_1$ on $J$. So $f_1=g_1$ on $I\cap J$. you may want to show that $I=J$ in fact.
Answer: Let us show that $f_1(x)$ must be $\max \{f(x),0\}$. First let $f(x) \geq 0$. Then $f_1(x) \geq f_2(x) \geq 0$. If $f_1(x)=0$ we get $f_1(x)=f_2(x)=0$ so $f_1(x)=0=\max \{f(x),0\}$.
Otherwise $f_2(x)=0$ (because $f_1(x)f_2(x)=0$) so $f_1(x)=f(x)= \max \{f(x),0\}$.
Now let $f(x) <0$. Then $f_1(x) <f_2(x)$. This implies that  $f_1(x)=0$ (by hypothesis and the fact that $f_2(x) >0$). Hence $f_1(x)=0= \max \{f(x),0\}$.
We have proved that $f_1$ is unique. It follows that $f_2=f_1-f$ is also uniquue.
Comment: Why must $f_1(x) \geq f_2(x)?$
Comment: @user745578 Because I am assuming that $f\geq 0$ in the first case.
Comment: Alright! Thanks for the answer!
Answer: Uniqueness easily follows from the condition $f_1f_2=0$. This means that for every $x \in X$ you have $f_1(x)=0$ or $f_2(x)=0$ and $f(x)=f_1(x)-f_2(x)$, this implies if $f(x)>0$ then $f(x)=f_1(x)$ while $f_2(x)=0$ and vice versa $f(x)<0$ implies $f(x)=-f_2(x)$. If $f(x)=0$ then $f_1(x)=f_2(x)$ and their product must be zero: that is $f_1(x)=f_2(x)=0$.
Existence is an easy application of the pasting lemma, since you said you already proved it I won't go into detail.
Edit: since you asked in the comments I am going to explain how the pasting lemma can be used to provide the maps. Since $f$ is continuous $N=f^{-1}((-\infty, 0])$ and $P=f^{-1}([0, +\infty))$ are both closed subsets of $X$. The pasting lemma states that if you have two continuous function $g,h$ defined on closed subsets of a topological space and they coincide on the intersection then gluing them together you get a continuous function on the whole space.
In our case you can take $g\colon P \rightarrow \mathbb{R}$ to be $g=f|_P$ and $h\colon N \rightarrow \mathbb{R}$ to be the zero function. Applying the lemma you obtain a function which is your $f_1$.
Comment: @user745578 You can see it as both. If you don't want to show in general that $\max$ is a continuous function, you can also note that $$f_1(x)=\begin{cases} f(x)& x  \in f^{-1}[[0,\infty)] \\ 0 & x \in f^{-1}[(-\infty, 0]]\end{cases}$$ and both domain parts are closed as $f$ is continuous. Similarly for $f_2$.
Comment: Just one clarification: Existence: One can check that $f_1 = \max\{f,0\}$, $f_2 = \max\{-f,0\}$ works. How does this use pasting lemma? More like composition of continuous functions is continuous.
Comment: @Henno Brandsma. Thanks. Now I get it
Comment: @user745578 You're welcome. The usual notation (in any algebraic lattice, like $C(X)$ is, is $f^+$ and $f^-$, the positive and negative parts of $f$. $f^+ + f^- = |f|$ as well. Gillman and Jerrison treat it very briefly in the classic book "rings of continuous functions" as useful background facts.


Removendo uma imagem via unlink não funciona

Question: Eu tenho o seguinte código abaixo:
//carrega a imagem anterior
$img = $db->prepare("select ipco_descr_multimidia,ipco_arquivo from ipco_multimida where ipco_id_questao_fk = :id ");
$img->bindParam(':id',$id);

//executa a query
$img->execute();

//recupera os valores da tabela
$resultado = $img->fetchAll();
$caminho = $resultado['ipco_arquivo'];
$nome = $resultado['ipco_descr_multimidia'];

//apagar o arquivo antigo da pasta
if(file_exists($caminho.$nome)) {
    @unlink($caminho.$nome);
    //exit;
}

Tabela multimídia:
ipco_descr_multimidia | ipco_arquivo
1413297340.jpg        | ./img/upload/

Quando executo o código, não apaga a imagem que esta dentro da pasta img/upload.
Comment: **CUIDADO** A função de PHP [`file_exists()`](http://php.net/manual/en/function.file-exists.php) devolve `TRUE` se o caminho terminar numa diretoria, ou seja, se a variável `$nome` estiver vazia, o código atual entra na mesma no `IF`. Usar a função [`is_file()`](http://php.net/manual/en/function.is-file.php) é a forma mais segura de verifcar se o ficheiro existe.
Comment: Começe removendo o `@` que suprime o erro em `unlink` e talvez você comece a ter mais pistas do que está errado...
Comment: O problema está mais relacionado a remoção do arquivo que do banco de dados. Verifique as permissões da pasta. Coloque o sistema operacional que está usando.
Comment: Resolvido,  faltou adicionar a posição do array $ipco_descr_multimidia = $resultado[0]['ipco_descr_multimidia'];
Comment: Ele está encontrando o arquivo? Ou seja, a instrução `file_exists($caminho.$nome)` está retornando `TRUE`? Pode ser também um problema de localização. Como está sua estrutura de pastas, o arquivo que você está executando está no mesmo local da pasta `img`?
Comment: @hulckb coloque como resposta o procedimento que você executou para resolver o problema.
Answer: Pelo teu código, existem algumas coisas podem ser melhoradas de forma a existir maior coerência entre o que pretendes e o que estás a fazer. Por outro lado, algumas das sugestões visam resolver potenciais problemas de segurança:

Usa a declaração de PDO fetch() que te devolve uma linha ao invés da fetchAll().
Este ponto resolver o problema que te levou a colocar a pergunta.

Usa a função is_file() para verificar se o ficheiro existe pois a mesma só devolve TRUE se existir um ficheiro e for de fato um ficheiro.

Verifica os valores antes de os utilizares, como podes ver em baixo fazendo uso da função empty().

Não escondas os erros do sistema, o teu código deve estar preparado para lidar com os mesmos. A função unlink() devolve FALSE quando algo corre mal. Se algo correu mal, deves agir em conformidade quer informando o utilizador quer tomando medidas alternativas para a tarefa em questão.

Exemplo do teu código com o descrito em cima:
/* Carrega a imagem anterior
 */
$img = $db->prepare("
  SELECT ipco_descr_multimidia, ipco_arquivo
  FROM ipco_multimida
  WHERE ipco_id_questao_fk = :id
");
$img->bindParam(':id', $id);

// executa a query
$img->execute();

// recupera os valores da tabela
$resultado = $img->fetch();

$caminho = $resultado['ipco_arquivo'];
$nome = $resultado['ipco_descr_multimidia'];

/* apagar o arquivo antigo da pasta
 */
if (!empty($caminho) && !empty($nome) && is_file($caminho.$nome)) {

    if (!unlink($caminho.$nome)) {
      die("Ups... correu mal!");
    }
}

Comment: Muito Obrigado Zuul


Why doesn't this represent a normal approximation to the binomial?

Question: Suppose the registrar's office at a college reports 58% of the students live on campus.  An intern working in the administration building is unaware of this 58% parameter value.  He designs a study in which he will take a random sample of 200 students and estimate the population proportion of all students that live in the college dorms using the resulting sample proportion.
If he were to repeat his study many times, the possible values of the sample proportion would vary by about __ away from the expected value of __, on average.
I understand the first blank is the standard deviation and the second is the mean, but why can't I approximate them using $\mathcal{N}(np, (np(1-p))^.5)$, which is the normal approximation to a binomial distribution?  So that I have $\mathcal{N}(116, 6.98)$?  So the first blank is 6.98 and the second is 116?
Comment: Is this homework? If so, it should have the homework tag.
Comment: Ponder this: when you computed 6.98 and 116, did you need to make a Normal approximation to anything?  Can you pinpoint where, if anywhere, you actually use a Normal approximation in this answer?
Comment: Possible duplicate of [Is the normal distribution a better approximation to the binomial distribution with proportions near or far from 0.5?](https://stats.stackexchange.com/questions/256357/is-the-normal-distribution-a-better-approximation-to-the-binomial-distribution-w)
Answer: The short answer is that you specified the normal approximation to the binomial distribution of the counts and the question is asking about the distribution of the proportions.  Since the proportion is just the count divided by the sample size it is an easy conversion from your answer to the correct answer.
Answer: Consider the R code below which shows what the answer is through simulation.  You will see that the variance is actually $\dfrac{p(1-p)}{n}$.  As the number of samples gets large the distribution of sample proportions is asymptotically normal with distribution $\mathcal{N}(p,\sqrt{\dfrac{p(1-p)}{n}})$, as we would expect.  It should be fairly evident why this is the case, but it is helpful to see in the data...
<code>reps <- 1000
p <- .58
pop <- rbinom(size=1,n=10000,p=p)
samp.prop <- rep(0,reps)
for(i in 1:reps){
  samp.prop[i] <- sum(sample(pop,size=200))/200
  }
mean(samp.prop)
var(samp.prop)
p*(1-p)/200
hist(samp.prop,breaks=20)
</code>
Comment: To reduce the risk of miscommunication, I edited your answer to conform to the OP's convention of specifying the standard deviation rather than the variance in the normal distribution. One subtle issue in your answer concerns the sense in which something can "converge" to $p(1-p)/n$ when $n$ itself is the index that is getting arbitrarily large!  (You might want to use the language of asymptotics instead of convergence.)


C++ Compound Logical Operators not Working with Comparison Operator

Question: I have two cases in a program I am writing where i am using compound logical operators to compare a variable against multiple values efficiently. One of the is working just fine. I have an array of characters, and I want to check if one of the elements is equal to one of two values without having to restate the variable. I also have an integer called hourInt, but this is not important. The code I used for the conditional is as follows:
 if (charArray[8] == 'P' || 'p' && hourInt != 12){
    hourInt += 12;
 }
 if (charArray[8] == 'A' || 'a' && hourInt == 12){
    hourInt -= 12;
 }

And both of these conditionals perform their job correctly - they check whether charArray[8] is equal to one of the two values. But then, later on in the program, I tried using compound logical operators again. I have a two-character string called meridies, and I want to see whether it is not equal to one of four values. I set up a conditional with compound logical operators as follows:
if (meridies != "AM" || "am" || "PM" || "pm"){
    cout << "Error: Unknown value for the meridies." << endl;
    return inputTime();
}

Unlike the first conditional, which correctly compared the values, this second one always returns true, even if meridies is indeed equal to one of the four cases. I know I could just set this up as four different comparisons each with their own logical operator, but I am just wondering why this second conditional doesn't work whereas the first one does.
Comment: None of them work.
Comment: Where did you learn the concept of "compound logical operators"? They simply don't exist in C++. `&&` and `||` take two **boolean** arguments and return a boolean argument. They aren't a replacement for the English words "and" and "or".
Comment: @AlexanderZhang I thought that code worked so I called it 'Compound Logical Operators', as if it worked it must exist, but as you'll see in my comment to the accepted answer, the conditional didn't work.
Answer: Yeah, you might need to read up on how operators work (and operator precedence).
Firstly, this is a nonsense:
charArray[8] == 'P' || 'p'

You are saying, if (charArray[8] == 'P') is true, or 'p' is true. 'p' will always be true, because it is not zero. It's not entirely clear what you are trying to do with that code, but I assume something along these lines?
if ( (charArray[8] == 'P' || charArray[8] == 'p') && hourInt != 12)

As for this:
if (meridies != "AM" || "am" || "PM" || "pm")

IF meridas is a std::string, then it should be:
if (meridies != "AM" && meridies != "am" && meridies != "PM" && meridies != "pm")

If however meridies is a char array, then you should be doing:
if (strcmp(meridies, "AM") != 0 &&
    strcmp(meridies, "am") != 0 &&
    strcmp(meridies, "PM") != 0 &&
    strcmp(meridies, "pm") != 0)

Comment: Yeah I see that now, thank you. I thought that the first conditional looked weird when I typed it in as I learned a while ago that stuff like that should not work, but it seemed to do its job so I left it. Turns out that another part of the code was just doing the work of the conditional for it (it was a spaghetti-code program I wrote at 2am). Thanks for the answer - I'll accept it when it lets me.


Is it possible to cut a String from a specific word to another?

Question: I have a long text that i want to cut into pieces. In the text there are unique sections i can use to identify one piece. Ive looked into this
TestString = TestString.Substring(0,TestString.IndexOf('-')).Trim()
but this only allows for one character and I need 10 so it wont work. The String I want to start cutting and to stop looks like this:

"12.32.4214"

Has anyone found a souluion to this problem ?
Comment: Provide the input and output strings and will help you
Comment: have you tried the `split` method in `String`?
Comment: on what basis you want to split the string? do you mean `split("-")`?
Comment: Your comments that there are "unique sections i can use to identify one piece" makes me think that you probably want use Regular Expressions to locate your "specific word" (In RegEx terminology this would be a matching group).
Answer: Seems you are asking if you can use indexOf() to identify a 10 length sequence in your string.
Yes, you can.
int indexOf(String str)

You can search by a string in this way
TestString = TestString.Substring(0,TestString.IndexOf('-234265789')).Trim()


Line equation from ray form

Question: Given a ray r = u + (v)t where u is a bounded vector representing an origin point and v is a free vector representing direction, how can the equation for the line in the form y = mx + b be derived?
Given:
$$u = \langle 0, \frac{-3}{4} \rangle$$
$$v = \langle 1, \frac{8}{9} \rangle$$
How does one arrive at:
$$y = \frac{8}{9}x + \frac{3}{4}$$
Comment: 1. This is not appropriate for the algebraic geometry tag. 2. Please use \langle and \rangle instead of < and >.
Answer: So you have a vector $v$ that starts from point $u$. It means that the line is going to be parallel to $v$. We know that any vector ($a$) parallel to $v$ will have cross product $a \times v= 0$. But $a$ needs to be shifted by $u$ meaning:
$$
a=\langle x - 0, y + \frac{3}{4}\rangle
$$
Now cross product (a.k.a. $2\times2$ matrix determinant) would be:
$$
\begin{vmatrix}
x && 1 \\
y + \frac{3}{4} && \frac{8}{9}
\end{vmatrix} = 0
$$
$$
\frac{8}{9}x - (y + \frac{3}{4}) = 0
$$
$$
y = \frac{8}{9}x - \frac{3}{4}
$$
The sign in your answer was wrong, you can check that if you set $x=0$ , then the expression should give $- \frac{3}{4}$ since $u=\langle 0, - \frac{3}{4}\rangle$

Line equation from ray form


Network Visualisation for huge dataset composed of many unconnected clusters

Question: I have a dataset which consists of 190,455 nodes and 1,241,638 edges. These can be broken down into a set of 2300 subgraphs which are not connected to each other. I am having trouble creating visualisations for this using tools such as Gephi (Yifan-Yu seems to work best) as the layout takes a very long time and doesn't seem to separate the subgraphs well.
Is there a tool which performs a layout for such a dataset well? It would seem best to plot each subgraph individually, and then perform some merging at the end to avoid overlap while the algorithms seem to be trying to plot and arrange everything at once.
Thanks!
Comment: There was a similar post here: http://stackoverflow.com/questions/243616/visualization-tools-for-huge-graphs
Comment: not there anymore
Answer: What you need to do is use a layout algorithm that recognizes the clusters and places them individually. There are two interactive network visualization tools I know of that will do that for you, though both will take quite a while to handle such a large network.
Cytoscape is a Java tool built mainly for biologists, but will automatically separate disconnected components into their own sections of the screen and lay them out individually, like in this image. Sometimes it isn't very space-filling.

NodeXL is a template for Excel 2007/2010 for network analysis that includes a new Group-in-a-Box layout that separates groups into their own region of the screen, whether the groups are components, clusters, or manually created. You would want to use this approach if you have any connections between your clusters at all. The interactive tool may be too slow for such a large network, but it does have a C# library you can use to run these algorithms yourself. Below are some examples and a reference for the associated paper. Disclaimer: I am an advisor and developer on the project.

Rodrigues, E. M.; Milic-Frayling, N.; Smith, M.; Shneiderman, B. & Hansen, D. Group-in-a-Box layout for multi-faceted analysis of communities SocialCom '11: Proc. 2011 IEEE 3rd International Conference on Social Computing, 2011, 354-361. DOI:10.1109/PASSAT/SocialCom.2011.139
Answer: I've had good experiences with Graphviz, and while I've never drawn graphs that large myself, I know that it's supported. See this page and this page.


Including Fonts with SCSS and Create React App

Question: I'm building a simple create-react-app and using SCSS. I downloaded a custom font and I have the .otf, .ttf, and .woff files. I was only planning on using the .otf file, but one way or another, I can't figure out where my relative reference for the file will be. Here is my directory structure:
app
|__public
|__src
   |__css
   |__fonts
   |__img
   |__sass
      |____abstracts
           |__(_fonts.scss)

In the _fonts.scss file, here is my code:
@font-face {
    font-family: 'LeagueGothic';
    src: local('LeagueGothic'), url(../../fonts/LeagueGothic-Regular.otf) format('otf');
}

I have a CSS selector in my _base.scss:
body {
    box-sizing: border-box;
    font-family: 'LeagueGothic', sans-serif;
    font-weight: 400;
    font-style: normal;
}

Here is a screenshot of the app being run on a dev server (note the LeagueGothic reference):

I'm not getting compilation errors or anything like that but the font isn't being applied. I'm studying webpack right now to see if I can dissect the build process and figure out where my files end up so I know where to reference. I'm sure there is an easier work-around I just can't find the direct answer.
Comment: Are you applying the font? Like: `html, body {font-family: 'LeagueGothic';}`
Comment: @AdriSolid yes I am. Sorry, I should've put that. Going to add now.
Comment: Yes i think applying font might be the solution
Comment: No I had already done that in my code. I just hadn't included it in the post. I don't think I'm referencing the file right. I'm pretty sure that's the problem I just don't know the solution.
Answer: Try specifying your format as format('opentype') as per the available types:

The available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg".

source: https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src


$f:\Bbb{R}\mapsto\Bbb{R}$ and $f$ is twice differentiable.

Question: $f:\Bbb{R}\mapsto\Bbb{R}$ and $f$ is twice differentiable such that $f(0)=2, f(1)=1, f'(0)=-2$. Prove that $\exists$ a $\varepsilon \in (0,1)$ such that $f(\varepsilon)f'(\varepsilon)+f''(\varepsilon)=0$.
Suppose $g(x) = \frac{2}{f(x)}-1-x$. Then $g(0)=g(1)=0\implies \exists$ $c \in (0, 1)$ such that $g'(c)=0$ by Rolle's theorem.
$g'(x) = \frac{-2f'(x)-f(x)^2}{f(x)^2}$. Then $g'(0)=g'(c)=0$
$2f'(x)+f(x)^2=0$ for $x=0, c$. Suppose $h(x)=2f'(x)+f(x)^2$. Then $h(0)=h(c)=0\implies \exists$ $k \in (0, c)$ such that $h'(k)=0$ by Rolle's theorem.
$h'(k) = 2f''(k)+2f(k)f'(k)=0 \implies f''(k)+f(k)f'(k)=0$ for $k \in (0, c) \subset (0, 1)$. Hence, Proved.
But what to do if $f(k)=0$ for some $k \in (0, 1)$. Either a new function is to be found out or we need to prove that $f(x)$ is non-zero in the interval.
Answer: Consider $h(x)=2f'(x)+f(x)^2$.
You might guess there is two cases.
Note that $h(0) = 0$.

First: $\displaystyle{\min_{x\in[0,1]}}f(x) = 0$
Let $f(c) = 0$. Then since $f$ attains minimum at $x=c$ and differentiable, $f'(c) = 0 (\,\,\Rightarrow h(c) = 0)$.
Then by Rolle's theorem, $\exists c'\in(0,c)$ such that $h'(c') = 0.$

Second: $\displaystyle{\min_{x\in[0,1]}}f(x) = -\alpha <0.$
let us set $f(c_2) = -\alpha.$
Also here exists $c_1 \in(0,c_2)\,$ such that $f(c_1)= 0$, $f'(c_1)\leq0$. $(*)$
(This follows from $f(0),f(1) > 0$ but $f(c_2)<0$)

$f'(c_1)<0$

Then $h(c_1) = 2f'(c_1) <0 $ and $h(c_2) = {\alpha}^2 >0$.
Thus there exists $c_4 \in (c_1,c_2)$ such that $h(c_4) = 0$. (IVT)
Finally, we get $\exists c_5 \in (0,c_4)$ satisfies $h'(c_5)=0$ By Rolle's theorem.

$f'(c_1) = 0$

In this case $h(c_1) = 0$,
we get $\exists c_5 \in (0,c_1)$ satisfies $h'(c_5)=0$ By Rolle's theorem.

Proof for $(*)$:
First, by IVT, $A = \{x\in(0,c_2) :f(x) = 0\}$ is nonempty.
EDIT: Previous answer was logically right, but not mathematically clean. So I modified my answer a bit again.
Assume $f'(w) >0 $ for all $w\in A$. (In another case ($\exists w\in A \text{ s.t. } f'(w)\leq 0$), such $c_1$ clearly exists.)
let $x_0 = \inf(A)$. Then $f(x_0) = 0$ by continuity of $f$. ($\Rightarrow x_0 \in A$)
Now $f'(x_0) > 0 $, there exists small $\epsilon >0 $ such that $f(x_0 - \epsilon) <0.$
Then by IVT between $[0,x_0-\epsilon]$ ,
 there is $x_{-1} \in (0,x_0-\epsilon)$ such that $f(x_{-1}) = 0$. This contradicts with $x_0 = \inf(A)$.
Indeed, the case is impossible.
Comment: @Riemann Is that correct now?
Comment: In that case, the argument given in the question works.
Comment: In that case,  f is always positive. Then author's method will do the job.
Comment: why $f'(c_1)<0$ and $f'(c_3)>0$?
Comment: @Riemann I will edit answer soon.


Extracting Data from an ArrayList

Question: I am trying to code a very simple blackjack game and I am currently stuck at a point where I am trying to determine a "winner".
I have an ArrayList which represents a deck of cards (deckOfCards) and I have an ArrayList that represents the cards dealt to n players (playersCards).
The idea of the ArrayList, playersCards, is that up to every 6th spot of the list represents a a different player's hand. For example, if only 2 players were playing it would look like this.
playersCards[1,2,6,8,6,10,4,6,5,6,3,9]
And that list would split into, player1's hand [1,2,6,8,6,10] and player2's hand [4,6,5,6,3,9].
I am having trouble splitting the playersCards arrayList into n different lists like so.
Any help would be appreciated!
Comment: This block of text is very hard to read. Use blank lines to separate the text into short paragraphs. Use back-ticks to surround code - such as `ArrayList`. Why not use a `List>` in the first place? This is not how cards are dealt in 21 and it does not make sense to represent them in this way.
Comment: Why on Earth do you not simply have a list for each player? Create a `Player` class that has a `hand` field which is a list of that player's cards. Object Orientation: You're doing it wrong.
Comment: What delineates the point between hands?  For example, if there are 2 players and 3 cards have been dealt how do you break the list? Instead of a single ArrayList could you instead use a list of lists, with one inner list per player?  Like so: `ArrayList>`
Answer: A lot of ways to do this. One of them is with sublist():
List<Integer> hand1 = playersCards.subList(0, 6);
List<Integer> hand2 = playersCards.subList(6, 11);

Be aware that this gives a view of the ArrayList. This means that any changes to the ArrayList will be reflected in the view.
Comment: There are 6 cards for each, not 5
Comment: @BoristheSpider, sublist 1 would have indices 0, 1, 2, 3, 4 and sublist 2 would have indices 5, 6, 7, 8, 9.  That looks correct to me.  It's more helpful to point out the mistake rather than assert a mistake has been made.
Comment: What @JaqenH'ghar said.

Extracting Data from an ArrayList


Why does //div[@title='value'] may not work?

Question: I'm trying to get this div, but for some reason it doesn't work:

Do you have any idea why this happens?
Answer: I guess that's because of inconsistent quotes usage (apostrophe might be recognized as closing single quote)
Try to put title value into double quotes:
<code>//div[@title="Best Aliexpress Women's Watches"]
</code>
Comment: Thank you very much! I didn't know about quotes differences.
Comment: If I'd like to make it universal why it does not allow me to write like this: `//div[@title="Best Aliexpress Women's Watches"] | //div[@title='Best Aliexpress Women's Watches']`?
Comment: @F.Vosnim , as I said apostrophe recognized as closing single quote, so your expression is not valid because for parser it looks like `//div[@title='Best Aliexpress Women'` - no closing square brackets for predicate. So even if your first XPath returns element adding `| //div[@title='Best Aliexpress Women's Watches']` will make the whole expression invalid
Comment: thank you for your answer. Is there anything I can do to make it valid for bouth cases: `//div[@title="Anything"]` and `//div[@title='Anything']` with XPATH?
Comment: @F.Vosnim , I'm not sure why you need that, because in XPath `"Anything" == 'Anything'`
Comment: I need that because some divs which I'd like to get have `'` in their title name, others have `"` inside.
Comment: @F.Vosnim you can try back-slash as escaping character: `"//div[@title=\"Best Aliexpress Women's Watches\"]"`


In 4-part harmony, Vii's 5th note (V7's 7th note) should also resolve down?

Question: In 4-part harmony, isn't the Ⅴ7's 7th note supposed to resolve by going a step down? If so, because the ⅶ is the substitute of the Ⅴ, shouldn't the ⅶ's 5th note (Ⅴ7's 7th note) also resolve down?
ex: A7's (Ⅴ7) G should resolve to F♯ (F natural if it's in D minor), so shouldn't the G of C♯m-5's (ⅶ⁰) resolve to F♯ (or F) as well?
But in this example it doesn't, the 5th of ⅶ resolves upwards.

( second bar's ⅶ )
Comment: Is there an F♯ accidental missing, or is the **Ⅰ** mistakenly capitalized?
Comment: @leftaroundabout It's surely not meant to be an F#! Must be a mistake.
Comment: Yes, you are right. There are parallel unequal fifths, which some composers avoided.  These are not in the top or bottom voices though, so the crime is a small one!
Answer: Generally speaking yes, and in particular if this were in the bass then you would have to have quite strong arguments to not resolve it downwards. But in a middle voice, the leading-tone qualities always stand out much less strikingly, so that's usually where the rules are bent in order to smoothen voice leading elsewhere. Presumably, the start of the next bar relies on the soprano coming from the F note (or, d-e-f is simply what the main melody does, can't change that just to cater to some small middle-voice issue!), and another rule is not to double thirds except as a deliberate effect, so that's why you don't give the alto an F there. You could pull it all the way down to D, but both bass and tenor have D already so that's not a good option either. Therefore, the best compromise in this case is to have the alto go up instead of the in itself more natural down direction.
Comment: I noticed that there is a lot pratice examples in this book that the vii's 5th going upwards. I guess it is allowed because its in  vii chord rather then V7 ?..


Find a Möbius transformation that maps part of a circle to the first quadrant

Question: I found this question whilst preparing for an exam:

Let $S = \{ z\in \mathbb{C} | |z-1|<5 , \mathrm{Re}(z)>0 \}$.
Find a Möbius transformation that sends $S$ to the first quadrant $\{ z \in \mathbb{C} | \mathrm{Re}(z) >0 , \mathrm{Im}(z) > 0\}$.

I am puzzled because it seems to me that I have to map the circle and the imaginary axis to the real and imaginary axis, but they make different angles.
Comment: By symmetry I would try to send the real axis to the line $y=x$. I'm not sure that it'll work.
Comment: Hang on, I think one of us has something wrong. I think you are right: the question as posed is not possible. I would guess there is a misprint of Re instead of Im: if it is Re, the angles do not allow you to do a Möbius transformation, as you say.
Comment: Yeah that's what i thought. Probably Re should have been Im and then your answer would be correct.
Answer: With the question as posed, the answer is not possible by Möbius transformations: you are correct. I think that the question should mean "Im>0", rather than "Re>0". The below runs through that calculation.
Consider the map
$$ T(z) = \frac{z+6}{4-z}. $$
Where did I get this from? The two "corners" of the domain are at $z=4$ and $z=-6$. I want to send one to $0$ and one to $\infty$, the "corners" of the region I wish to map to.
Notice that the real axis is a diameter of the circle, therefore they meet at right angles, just as the real and imaginary axes do. Since Möbius transformations are conformal, these angles will be preserved. Further, $T$ clearly maps the real axis (with $\infty$) to itself since the coefficients are all real. Therefore it should map the circle through $4$ and $-6$ at right angles to the real axis to the circle through $0$ and $\infty$ at right angles to the real axis, i.e. the imaginary axis.
Next, I need to check $T$ maps to the right parts of the axes. Clearly for $-6<z<4$ $T(z)>0$, so it maps the diameter to the positive real axis. If $z=-1+5e^{it}$, then
$$ T(z) = \frac{-1+5e^{it}+6}{4+1-e^{it}} = \frac{5(1+e^{it})}{5(1-e^{it})} = \frac{(1+e^{it})(1-e^{-it})}{(1-e^{it})(1-e^{-it})} = \frac{2i\sin{t}}{2(1-\cos{t})}, $$
which is clearly both purely imaginary and with imaginary part larger than zero for $0<t<\pi$.
The last thing to check is that the interior has ended up in the right place. I'm sure you can manage that yourself: just check any one point inside the circle goes to one in the first quadrant. Continuity gives you the rest.
Comment: Yes. Angles are always preserved by Mobius transformations: only powers of $z$ can change angles at isolated points.
Comment: Those aren't the two corners of the domain, are they? The circle $|z-1|=5$ and the line $\mathrm{Re}(z)=0$ meet at $\pm i\sqrt{24}$.
Comment: @ThomasAndrews Quite: see my edit. I thought it worth leaving the calculation there, with the proviso that it is based on the assumption of a misprint to render the question possible.


Angular Material with Angular 7

Question: I'm new to angular, but we are implementing Angular material for the popup functionality.
In the app.module.ts I'm importing the MatButtonModule and MatDialog module with the following import statements.
import {MatButtonModule} from "@angular/material/button/typings/button-module";
import {MatDialogModule} from "@angular/material/dialog/typings/dialog-module";

For some reason when I compile, using ng build, I get the error message below.
ng build

Date: 2020-05-04T18:47:12.434Z
Hash: 9bec1eb21effd8a26717
Time: 10607ms
chunk {main} main.js, main.js.map (main) 426 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 425 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 200 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 5.56 MB [initial] [rendered]

ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve '@angular/material/button/typings/button-module' in
'C:\Code\AFI\bugs\68550\Hpfc.Afi.Web\src\app'
ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve '@angular/material/dialog/typings/dialog-module' in
'C:\Code\AFI\bugs\68550\Hpfc.Afi.Web\src\app'

Here are my versions
Angular CLI: 7.3.9
Node: 12.16.2
OS: win32 x64
Angular: 7.2.15
... common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.13.9
@angular-devkit/build-angular   0.13.9
@angular-devkit/build-webpack   0.13.9
@angular-devkit/core            0.7.5
@angular-devkit/schematics      0.7.5
@angular/animations             7.2.16
@angular/cdk                    7.3.7
@angular/cli                    7.3.9
@angular/material               7.3.7
@ngtools/json-schema            1.1.0
@ngtools/webpack                7.3.9
@schematics/angular             7.3.9
@schematics/package-update      0.7.5
@schematics/update              0.13.9
rxjs                            6.5.4
typescript                      3.2.4
webpack                         4.29.0

What am I missing or not doing correctly to get those error message?
Answer: In order to import these modules you also need to add them to the module where you want to use them, E.g: app.module.ts
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, MatButtonModule, MatDialogModule],
  providers: [],
  bootstrap: [AppComponent]
})

Then you should be able to use both of them in all the components that belong to that module

Angular Material with Angular 7


Must Declare Scalar Value?

Question: I am working with SQL and c# for my assignment. For this assignment I am running a movie database and I am stuck on this part where I have to check out a movie. I keep getting a 'must declare scalar value' but I am unsure how to do that.
My code:
 <asp:Panel ID="panel5" runat="server" Visible="false">
        <asp:GridView id="one_data" AutoGenerateColumns="false" runat="server" DataKeyNames="MovieID">
            <Columns>

                <asp:BoundField DataField="MovieTitle"
                    HeaderText="Movie"/>
                <asp:BoundField DataField="DateChecked"
                    HeaderText="Date Checked"/>
                <asp:BoundField DataField="CheckedOut"
                    HeaderText="Checked Out"/>
            </Columns>
        </asp:GridView>
        <asp:Button runat="server" Text="Choose another Movie" OnClick="GoBack" />
        <asp:Button runat="server" Text="Check Out" OnClick="CheckOut" />
    </asp:Panel>

Panel 5 gets a selected movie that the user chooses and when they hit the check out button the fields 'DateChecked' and 'CheckedOut' are supposed to be filled with the date and a 'Y' for yes.
CS Code:
public void CheckOut(object sender, EventArgs e)
    {
        get_connection();
        try
        {

            connection.Open();
            command = new SqlCommand("UPDATE Content SET DateChecked=@DateChecked, CheckedOut=@CheckedOut WHERE MovieID=@MovieID", connection);
            command.Parameters.AddWithValue("@DateChecked", DateTime.Now);
            command.Parameters.AddWithValue("@CheckedOut", 'Y');

            reader = command.ExecuteReader();
            one_data.DataSource = reader;
            one_data.DataBind();

            reader.Close();
        }

I left out the catch part because it's unimportant. When I hit the checkout movie button I keep getting the error and if I remove the WHERE clause, it works except that all movies are updated instead of the one I chose. What would be the fix for this?
Comment: You're not adding a SQL parameter for the `@MovieID` value
Comment: @Igor `ExecuteNonQuery` makes more sense.  `ExecuteScalar` is really meant for a query that you expect to get one row and one column.
Answer: Your UPDATE command has three values, which are defined using @
You have specified two of them, but you didn't specify the @MovieID
command = new SqlCommand("UPDATE Content SET DateChecked=@DateChecked, CheckedOut=@CheckedOut WHERE MovieID=@MovieID", connection);
            command.Parameters.AddWithValue("@DateChecked", DateTime.Now);
            command.Parameters.AddWithValue("@CheckedOut", 'Y');

As a result it won't be able to form some valid SQL. You need to add the movie ID
command.Parameters.AddWithValue("@MovieID", movieId);
Presumably you'll get this from your boundfield for movie title.
Comment: How would I get the the movieid from the boundfield?
Comment: There are several steps you need to understand here, basically you need to use the RowCommand event to get the specific row, if you have one button per row, instead of OnClick, then in your RowCommand you can access all the values in the gridview row and retrieve the ones relevant to you.

Must Declare Scalar Value?


Quando da erro 404 no header, e redirecionar para uma pagina especifica?

Question: Tenho essa pagina com link OFF: https://uploadbr.com/1j1w
Porem não adianta eu fazer isso com .htaccess, porque eu ja tentei e não vai, quero fazer com php.
Tentei algo como isso:

if($httpCode == 404) {
    /* REDIRECT AQUI */
}

Mas não funcionou, como faço isso ?
Comment: Esse site é seu, ou você obtém informações dele e quer verificar se o mesmo está off?
Answer: Você tentou da seguinte forma no .htaccess?
ErrorDocument 404 /pagina-a-mostrar.php
Se não funcionar, essa forma que você está tentando fazer com if seria assim: https://pastebin.com/QLVTG4EP


«A cycle is a product of transpositions» $\iff$ «Rearrangement of $n$ objects is the same as successively interchanging pairs»

Question: I am following John B. Fraleigh -- A first course in abstract algebra. On page 90 of the 7th edition he say that
-- Decomposition of a cycle into products of transposition is possible since it is just the same as seeing that rearrangement of $n$ objects can he achieved by successively interchainging of pairs.
Now, I understand that rearrangement of $n$ objects can he achieved by successively interchainging pairs, but I cannot for the life of me see that this rationalizes cycle decomposition into compositions of transpositions.
Here are my attempts:
(1) Consider the cycle $(2,3,1) = (2,1)(2,3) = (2,1)\circ(2,3)$.
If I start with (1,2,3) and first transpose (2,3), and then (2,1) I get this:
Starting with :
(1,2,3),     then by transposing (2,3) gives
(1,3,2),     then by transposing (2,1) gives
(2,3,1)

Which seemed to work in some sense. But the same algorithm fails for
(2) Consider the cycle $(1,3,5,4) = (1,4)\circ(1,5)\circ(1,3)$
Starting with :
(1,3,4,5),     then by transposing (1,3) gives
(3,1,4,5),     then by transposing (1,5) gives
(3,5,4,1),     then by transposing (1,4) gives
(3,5,1,4)

But $(3,5,1,4) \neq (1,3,5,4)$, so the algorithm failed.
Can you help me to understand that the rearrangement of object by successive interchanges of pairs is the same as decomposing cycles into products of transpositions? A somewhat 'pictorial' explanation why these concepts are the same, would be best.
Answer: Your problem is a very common misconception that I have found even in lecture notes written by professors. The explanation lies in the following line:
The transposition $(i,j)$ does not swap the numbers $i$ and $j$. It swaps whichever numbers are currently in positions $i$ and $j$ in the arrangement.
When you consider $(1,3,5,4)$, it means the map that takes whichever object is first into the third placeholder, then the third object that was just kicked off goes to the fifth, and so on. It corresponds to the map $\left(\matrix{1&2&3&4&5\\3& 2& 5& 1& 4}\right)$ written here as a table of values.
If you start from $(1,2,3,4,5)$ and transpose the first and third objects you get $(3,2,1,4,5)$. Transpose then the first and fifth to get  $(5,2,1,4,3)$, and finally the first and fourth to get  $(4,2,1,5,3)$. In the end $1$ went to the third placeholder, $3$ to the fifth, etc. as expected.
Note for completeness that in cycle notation $(1,3,5,4)$ is also equal to the product $(1,3)(3,5)(5,4)$, which I personally find more fun and easier to remember.
Comment: Yes, the fourth has moved to the first, the first has moved to the third,  the third has moved to the fifth, and the fifth has moved to the fourth.
Comment: Thank you for your answer. I am loving your personally preferred way of decomposing cycles to transpositions, it is easier to remember. But I am still a little confused. I was expecting to recover the cycle (1,3,5,4) in the end. Is (4,2,1,5,3) somehow equal (1,3,5,4)?
Comment: Yes, that is the meaning of the sentence "*In the end 1 went to the third placeholder, 3 to the fifth, etc. as expected*." $(4,2,1,5,3)$ indicates the final position of each number after applying the permutation to $(1,2,3,4,5)$.
Answer: Remember that the transpositions refer to indices, not the numerical value. Additionally, note that transpositions are applied right-to-left—you already know this. So, consider the following diagram.

The cycle $(1, 3, 5, 4)$ looks like this: $x_4 \mapsto x_1 \mapsto x_3 \mapsto x_5 \mapsto x_4$.
Now, $(5,4)$ maps $x_4 \mapsto x_5 \mapsto x_4$, $(3,5)$ maps $x_5 \mapsto x_3 \mapsto x_5$, and $(1,3)$ maps $x_3 \mapsto x_1 \mapsto x_3$.
Chaining these together, we see that $(1,3)(3,5)(5,4)$ acts on $x_4$ in the following way(see the black and red arrows). $x_4 \to x_5 \to x_3 \to x_1$, so the final image is $x_4 \mapsto x_1$. Besides that, the images of $x_1, x_3, x_5$ are unchanged, so the total result is
$$x_4 \color{red}\mapsto x_1 \mapsto x_3 \mapsto x_5 \mapsto x_4$$
which shows the two are the same.


Three-prisoner problem and Bayes rule

Question: Here is the wiki of Three-prisoner problem, in which only one prisoner is pardoned, and the Bayes solution is given in the wiki.
My problem is pretty much the same, except that only one prisoner is executed. Here is the description:

A, B, C are three prisoners, two of which will be pardoned, A asks the
  warden to tell him which ONE will be pardoned other than himself. A
  thinks that before asking, he has a chance of $\frac{2}{3}$ to be
  pardoned, but if he asks, the chance goes down to $\frac{1}{2}$. A's
  calculation is wrong, explain why.

I wanted to do it the Bayes way, let $A,B,C$ be the event that A,B,C will be pardoned repectively, and let $b$ be the event that the warden mentions B will be pardoned.
The prior here is $P(A) = \frac{2}{3}$, and after observing $b$, the posterior of $A$ is
$$P(A|b) = \frac{P(b|A)P(A)}{P(b)}$$
. I think $P(b|A)P(A) = \frac{1}{2}\frac{2}{3}$, since if $A$ happens, the warden should not mention $A$, he should mention the other one who will be pardoned, which has probability $\frac{1}{2}$ for B. And
$$P(b) = P(b|A)P(A) + P(b|B)P(B) + P(b|C)P(C)$$
, right? How to calculate this?
Answer: The way you've defined them, $A$, $B$, and $C$ are not disjoint events ($A$ and $C$ can happen at the same time, for example), so the equation $P(b)=\sum_{X\in{A,B,C}} P(b|X)$ doesn't work.
It would be nicer to define $A$ as "A is executed", $B$ as "B is executed", and $C$ as "C is executed". This way $A,B,C$ are disjoint and cover the whole probability space $P(A)+P(B)+P(C)=1$.
Assuming that we are looking from A's point of view, we leave $b$ meaning "A finds out that B is pardoned".
So we have $P(A)=P(B)=P(C)=\frac{1}{3}$.
$P(b|A) = \frac{1}{2}$ since the warden could mention either B or C to A.
$P(b|B) = 0$ since if B is executed, the warden won't tell A that B is pardoned.
$P(b|C) = 1$ since if C is executed, the warden has no choice but to tell A that B is pardoned.
$$P(A|b) = \frac{P(b|A)P(A)}{P(b|A)P(A) + P(b|B)P(B) + P(b|C)P(C)}$$
$$P(A|b) = \frac{P(b|A)}{P(b|A) + P(b|B) + P(b|C)}$$
$$P(A|b) = \frac{\frac{1}{2}}{\frac{1}{2} + 0 + 1}$$
$$P(A|b) = \frac{1}{3}$$
So knowing $b$ doesn't change A's chances of being executed.

Three-prisoner problem and Bayes rule


Converting string to int problems in C++

Question: Sorry for any mistakes, first time questioning here.
so i have this function where i have a vector  type with names and scores of players of a game, while im trying to make a ranking wall.
in this specific part of the program i need to convert a string to a int. the string part is actually a number in the string vector and i need it to be int so i can compare it with other numbers, so here it is:
void exibir_ranking(vector<string> &ranking) //dentro do laco, procura qual o maior score, imprime ele na tela juntamente com o nome correspondente no outro vetor depois apaga o valor e o nome dos vectors
{
    int k;
    vector <string> nomes;
    vector <int> pontuacoes;

    for(int i=0;i<ranking.max_size();i++) {
        if(i==0 || i%2 ==0) nomes.push_back(ranking[i]);
        else if(i==1 || i%2!=0) {
            int aux = atoi(ranking[i].c_str);
            pontuacoes.push_back(aux);
        }
    }

    cout << "\n\n\t\tRANKING:\n\n";
    while(pontuacoes.size()!=0){
        int maior =0;
        for (k=0; k< pontuacoes.max_size(); k++){
            if(pontuacoes[k] > maior) maior = pontuacoes[k];
        }
        cout << k << "- " << "Nome: " << nomes[k] << "\tScore: "<<pontuacoes[k] << endl;
        nomes.erase (nomes.begin()+k);
        pontuacoes.erase (pontuacoes.begin()+k);
    }
    cout<<"\n----------------------------";

}

so, visual studio is telling me the problem is exactly here:
else if(i==1 || i%2!=0) {
    int aux = atoi(ranking[i].c_str);
    pontuacoes.push_back(aux);
}

as is says:

Error 4 error C3867: 'std::basic_string<_Elem,_Traits,_Alloc>::c_str': function call missing argument list; use '&std::basic_string<_Elem,_Traits,_Alloc>::c_str' to create a pointer to member   c:\users\user\google drive\mackenzie\projeto programacao\projeto\projeto\jogo.cpp   247

can anyone help me with this?
Comment: Why are you using `max_size()`? Just use `size()`.
Comment: `int aux = atoi(ranking[i].c_str);` - I suppose you meant to **call** that member function? like `c_str()`?
Answer: Use () to call a function, c_str is a function not a variable:
ranking[i].c_str()
                ^^

In addition, having C++, you can use std::stoi to stop using c_str, it also throws exception if the entry is not valid to convert to an integer:
int aux = stoi(ranking[i]);

And, replace max_size() by size() to get the real size of the vector, not the maximum possible size.
Answer: c_str() is a function, so you must call it:
aux = atoi(ranking[i].c_str());
//                         ^^

And like I said in the commments, I also see that you're using max_size(). This is probably causing a lot of problems in your program as this method returns the maximum size a vector can hold, not the amount of elements current residing in it. When you access the element at the index greater than the size of the container, and dereference it, you will get Undefined Behavior for accessing an out of bounds address.
The correct method to use is size():
for (int i = 0; i < ranking.size(); ++i)
//                  ^^^^^^^^^^^^^^


How to add callback for appending text to TextArea or other stuff in a class that performs parsing?

Question: I would like to know what is the best way in Java to add a callback (perhaps as argument since I'm using public static methods most of the time), to an external function, to do something like appending text to a text area control. I don't want to pass references to the text area though.
I'm fairly new to Java, hence the lame question.
Answer: Ok from what I understand, you want to be able to call a method which updates text area, without directly invoking it.
i.e you simple want to send the name of the method.
In the code display the output, (you can add code here, to display it in specific text area)
But we do not want to call methods directly, we let the program invoke the methods based on call back information provided.
We use concept of Reflections to initialize classes, invoke methods etc
Class: MainCallBack.java

we pass the name of the method to invoke,
the function displayAnswer( int, String) will take the number to be displayed, and also the method that has to be called. (not sure if this is what you mean by CallBack)

I have added comments in each line to explain what the function does.
the following line of code within displayAnswer does the actual invocation.
methods[i].invoke(classObject, answer);

If you want to invoke a static method, use "null" in place of the "classObject"
methods[i].invoke(null, answer);

Created classes in package com.callback
In order to reduce number of lines of code, I using the Exception instead of specific exceptions.
Class MainCallBack.java
package com.callback;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MainCallBack {

    public static void main(String[] args)
    {

        MainCallBack mainCallBk = new MainCallBack();

        String sCallBackMethodName = "displaySumInTextArea"; //this is the name of the callback method.

        int z = 11 ;
        mainCallBk.displayAnswer( z , sCallBackMethodName );
    }
    private void displayAnswer(Integer answer , String sCallBackMethod)
    {
        try {
            Class className = Class.forName("com.callback.CallBackClass"); //will assume that we know the class name
            Constructor classConstructor = className.getConstructor(); // get the constructor of the class.
            Object classObject = classConstructor.newInstance(); //create an instance.

            Method[] methods = className.getDeclaredMethods();   //get all methods within the class.

            for (int i = 0; i < methods.length; i++)
            {
                String dataMethod = methods[i].getName();   // iterate through array of methods and get each name
                if(dataMethod.equalsIgnoreCase(sCallBackMethod))  //comparing callbackname with every method in class.
                {
                    methods[i].invoke(classObject, answer);     // invoke the method if they match with what the user is calling.
                                    // if 'displaySumInTextArea( int )' was static then we would use 'null' (without quotes) in place of the classObject.
                }
            }

        } catch (Exception e) {
            e.printStackTrace(); //use specific exceptions here
        }
    }
}

class CallBackClass.java
package com.callback;

public class CallBackClass {

    public void displaySumInTextArea(Integer sum)
    {
        System.out.println("Sum = " + sum);
    }
}

I hope this answers your question
Comment: Is there any 'cleaner' method for doing this? Can you pass a method by reference or such? I don't know but walking the whole method list seems a bit suboptimal. I appreciate the effort put into answering, though.
Comment: @soze I don't think there is an inbuilt method in Java to do this. You will have to hack together something, or search and see if there is any third party libraries doing this. But even the third part libraries would be doing similar stuff, as I mentioned in my answer.
Comment: I ended up using interfaces which is a cleaner/more accurate way to do this, like in C#. However since I lack the time to elaborate an answer of my own I accepted yours.


Is there a set of axioms governing the properties of derivatives in calculus that include this particular axiom and what would it be?

Question: Moved from Math Overflow due to not being regarded as a high degree of research
Note: I am looking in particular at real valued/real input functions at all values regardless of differentiability.
In this question a series of axioms or postulates governing calculus are proposed. Granted, that is abstract calculus rather than real number calculus.
Is there any known way to write a similar set of postulates governing real number calculus involving derivatives, integrals, and (ideally) allowing the construction of differential equations but with the following statement selected as one of the axioms without redundancy or contradiction?

"if and only if a function is constant does it have a derivative of 0 for all real numbers"

My ultimate purpose is to negate the aforementioned axiom and so having a complete set of axioms would make it convenient for me to convey the actual meaning behind negating the statement since one can ultimately fall back upon the statements similar to how we developed non-Euclidean geometry.
Some potential axioms that might be relevant that I thought of were:

"All elements of a derivation set are the inverse of the antiderivative where defined"
(might be better proposed as a conjecture) The derivation set of any function may not equal the empty set.

Update:
After discussing this with a few others more deeply, and noticing some non-uniqueness properties and things I've realized that the derivative need not be unique given the sort of things I would want to exist. Therefore, the following definitions deal with that issue:

A derivation set is a set of a functions that can potentially result from differentiation being applied to some function.
A derivative is an operator whose results from being applied to some function is some element of the derivation set for that function.

In this sense altered forms of derivatives would be solutions sets of functions that satisfy some equation rather than necessarily a unique operator. However, the equation itself is probably not something trivially apparent by my guess or something one could derive in a quick manner.
Comment: The original MO question is http://mathoverflow.net/questions/258375/is-there-a-set-of-axioms-governing-calculus-that-include-this-particular-axiom-a
Comment: You should probably start at the epsilon-delta method of limits.
Comment: Not too much, but perhaps linear functions?
Comment: I'm not good with axioms and all, but it is the case that if $P(x)$ is a polynomial with arbitrary rational exponents and is non-linear, then $Q(x)$ is the derivative of $P(x)$ for $x\in A$ iff $P(x)-Q(c)x-b$ has a root of multiplicity greater than or equal to $2$ at $x=c$ for all $c\in A$.  This can then probably be extended to give statements about derivatives of analytic functions.
Comment: I would mention that In normed vector spaces you define the derivative for a dense subset (e.g. the polynomials or the analytic functions) and extend it by linearity and norm closure. ([$L^p, L^\infty$](https://en.wikipedia.org/wiki/Lp_space),[$H^1$](https://en.wikipedia.org/wiki/Sobolev_space#The_case_p_.3D_2)..) @SimpleArt
Comment: I do not see the connection.  Note my comment requires $P(x)$ to be non-linear, so a constant function is actually beyond its grasp.
Comment: See also http://mathoverflow.net/questions/44774/do-these-properties-characterize-differentiation and http://mathoverflow.net/questions/157847/algebraic-characterization-of-real-differentiation and https://en.wikipedia.org/wiki/K%C3%A4hler_differential
Answer: Disclaimer: Not a full answer, my notation is bad, and I'm horrible with this axiom stuff.  See to the end for a half-decent explanation of why this works and I hope it ends up useful.
If $P(x^d)$ is polynomial with integer exponents (including negative) and non-linear for some natural number $d$, then $Q(x)$ is the derivative of $P(x)$ over the domain if $f(x^d)$ has a root of multiplicity greater than or equal to $2$ at $x^d=c$, where $f(x)=P(x)-Q(c)x-b$ and $b=P(c)-Q(c)c$.
For example, if $P(x)=x^2$ and $Q(x)=2x$, then, notice that
$$f(x)=x^2-2cx+c^2=(x-c)^2$$
It has a root with multiplicity $2$ at $x=c$, so $Q(x)$ is the derivative of $P(x)$.
Similarly, if $P(x^2)=x$ with $x\in[0,+\infty)$ and $Q(x)=\frac12x^{-1/2}$, then
$$f(x^2)=x-\frac12c^{-1/2}x^2-\frac12c^{1/2}=-\frac12c^{-1/2}(x^2-c)^2$$
which has a root of multiplicity $2$ at $x^2=c$.
It is also not necessary that this be used merely for checking derivatives, for example, if $P(x)=x^3$, then
$$f(x)=x^3-Q(c)x-c^3+Q(c)c\equiv(x-a)(x-c)^2$$
this guarantees a root of multiplicity greater than or equal to $2$ at $x=c$.  Upon expanding and such, you should find $Q(x)=3x^2$.
If one is able to derive that $Q(c)$ is unique from this, then the sum of derivatives rule is derivable.

So I thought of this when I first entered a Calculus class, whereupon I got to see the fundamental definition of a derivative in what I would call regular space or beginner space.  The definition was basically that a derivative is the slope of a tangent line, which is by definition, the limit of secant lines.
But rather than evaluating limits, I looked at the more algebraic side of this and realized that if we are differentiating an algebraic function, then it is necessarily the case that I can solve for where the secant line intersects the original function.  And by the conjugate roots theorem, I can deduce how many roots (not necessarily distinct) there are, or how many times it crosses the function.
But clearly, if we are taking the limit as two roots approach $x=c$, then it is the case that a tangent line should have a root of multiplicity equal to or greater than $2$ at $x=c$.
And then I modified this for arbitrary rational exponents and negative exponents.
This is also clearly correct for analytic functions thanks to Taylor's theorem, though I haven't seen it useful there since you can't "factor" functions that aren't polynomials.
Comment: @TheGreatDuck oh, ok.  Thanks, I suppose.  :-)
Comment: @TheGreatDuck Glad it helps in some strange way, as strange as it is.
Comment: @TheGreatDuck This does not have double root at $c$.  It has two roots of multiplicity $1$ each at $x=c,x=-c$.
Comment: @TheGreatDuck What do you mean?  Are you saying that my "axiom" forces only constant functions to have $0$ as the derivative?  Note that my "axiom" is restrained to polynomials.
Comment: @TheGreatDuck But mine does not imply the converse.  Mine is independent of yours, is it not?
Comment: @TheGreatDuck What do you mean by negating?  Are you saying that by having the derivative of some non-constant function to be $0$ that my statement is false?  But what if this non-constant function is not within the scope of my statement?  I see no contradictions one way or another.
Comment: Keep in mind, I'm not used to logical statements, so if what you say is blatantly obvious, I apologize in advance.
Comment: @TheGreatDuck And thus almost concludes the bounty sadly.  :-(
Comment: @TheGreatDuck If you want, I can re-apply the bounty (can I do that when I've already answered this question?)
Comment: Ah, its nice to see at least some progress be made.
Comment: XD Ok then.  :-P  Sucks when bounties go unanswered IMO... maybe I should focus on them a bit.
Comment: @TheGreatDuck Or they are on vacation.
Comment: @TheGreatDuck Lol, you should put it in your profile description.  That way it gets more attention in the future ;-)


Polymorphic database design : does this approach have a name?

Question: I have a base enitiy (items) that will host a vast range of item types (>200) with totaly different properties. I want a clean portable and fast solution and have come up with an idea that maby has a name I'm unaware of.
Here it goes:

items-entity holds base class fields + additional fields for subclass fields but with dummie-names, ItemID,ItemNo,ItemTypeID,int1,int2,dec1,dec2,dec3,str1,str2
referenced itemtype-record holds name of type and child enity (1:n):
itemtypefields [itemtypeid,name,type,realfield]
example in [53,MaxPressure,dec,dec3]

It's limitations:

hard to estimate field requirements in baseclass
harder to add domains/checkconstraints based on child type
need application layer to translate tagged sql to real query
Only possible to query one type at a time since shared attributes may be defined to different "real-fields".

3rd bullet explained:
select ItemNo,_MaxPressure_ from items where ItemTypeID=10 and _MaxPressure_>42
should translate to:
select ItemNo,dec3 as MaxPressure from items where ItemType=10 and dec3>42

(can't do that with sp's or udf's right - or whould it be possible?)
But benefits of:

Performance
Ease of CRUD-operations
Easier to sort/filter at application level.

Now - does it have a name?
Comment: I doubt that this method has any of the advantages that you claim, least of all performance.
Comment: @DavidAldridge, which would be the alternate method - xml-field?
Answer: This antipattern is called One True Lookup Table.
In a relational database, each column needs to be defined as one logical type.  I don't mean one SQL data type like INT or VARCHAR, I mean everything in that column from start to finish must be from the same set of values, and you should be able to tell one value apart from another value.
You can't put shoe size and average temperature and threads per inch into the same column of a given table, and still call it a relation.
Basically, your database would not be a database at all -- it would be a spreadsheet.
Read almost any book by C. J. Date, such as SQL and Relational Theory for a proper explanation of relations and types.

Re your comment:

Read the Q again before lecuturing about elementary books and mocking about semi structured data.

Okay, I have re-read your post.
The classic use of One True Lookup Table isn't exactly what you're doing, but what you're doing shares the same problems with OTLT.
Suppose you have "MaxPressure" stored in column dec3 for ItemType 10.  Suppose there are a fixed set of valid choices for the value of MaxPressure, and you want to put those in another lookup table, so that no one can enter an invalid MaxPressure value.
Now:  declare a foreign key constraint on dec3 referencing your MaxPressures lookup table. You can't -- the problem is that the foreign key constraint applies to the dec3 column in all rows, not just those rows where ItemType is 10.
The reason is that you're storing more than one set of values in a single column.  The same problem arises for any other kind of constraint -- unique constraints, check constraints, even NOT NULL.  And you can't declare a DEFAULT value for the column either, because you probably have a different correct default for each ItemType (and some ItemTypes have no default for that attribute).
The reason that I referred to the C. J. Date book is that he gives a crisp definition for a type:  it's a named finite set, over which the equality operation is defined.  That is, you can tell if the value "42" on one row is the same as the value "42" on another row.  In a relational column, that must be true because they must come from the same original set of values.  In your table, dec3 could have the value "42" when it's MaxPressure, but "42" for another ItemType when it's threads per inch.  Therefore they aren't the same value "42".  If you had a unique constraint, these two 42's would not be considered duplicates. If you had a foreign key, each of the different 42's would reference a different lookup table, etc.
What you're doing is not a valid relational database design.
Don't bristle at my referring you to a resource on relational database design unless you understand that.
Comment: No, that's Entity-Attribute-Value, it's something different.  You're doing OTLT, which is to store a bunch of lookups for unrelated sets in one table.
Comment: As I understand OTLT, it's a child table witch one row for each attribute. That's another deal. I'm storing attributes in base-class and using lookups only to solve the label of the attribute.
Comment: no i'm not. Read the Q again before lecuturing about elementary books and mocking about semi structured data.
Comment: thanks for sharing your thoughts, it appricated (but I do have some issues with all do's and dont's circulating). I fully understand all the shortcomings regardning contraints etc. But. What's the option here? Create and maintain >200 sub-entities would be an adminstration-nightmare.


Assigning the variables to the Temporary table columns

Question: I'm working on a Task where I should get the datas from all the table from the Database without knowing the table names. What I'm planning to do is to write a query to get all the table names and column names and store it in a temporary table.
Once I got the table name and column name I have to store the values to the variables like @Table_Name and @Column_Name. Then I have to call the table names within a Loop and have to write a query like this
"select * from '''+@Table_Name+''' where '''+@Column_Name+''' = 1"

Earlier I used cursor to get the values and store it in a variable and call it within the loop. But it seems that the cursor is consuming more time and memory. So I thought of changing it using temporary table.
My doubt is, is it possible to assign the Temporary table values to a variable to use it later. If possible how to do it?
Comment: How does this query make sense? Many tables' columns' values will not be convertible to `int`, and yet the `WHERE` clause will force such an attempt to be made.
Comment: I just mentioned col_val '1' for an example. THe actual column value is declared in nvarchar
Comment: The Column name will always be the same with nvarchar value like EngUID or EngID. The table name is one which changes. Sorry I wasnt clear about ur question when I replied.,
Answer: Your idea may not work, I feel, since you are trying to incorporate the concept of arrays in SQL Server. SQL Server does not have arrays, but it has tables. You can obtain the data you need by creating a temporary table. Inserting into it by firing a query like
select * from sys.tables.
Then trying to do your operation by loading each row from this table. After your work is done, by all means drop the table.


Set setCachePeriod for static resources in spring boot

Question: I am using spring boot, and the /static is served as static resources like js and css, so far so good, while I want to set the cache header of these files, so I tried this:
@Configuration
public class BaseMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/").setCachePeriod(24 * 3600 * 365);
    }
}

However after that, the application can not serve anything from the /static folder.
What's the problem?
Answer: In my opinion, it's better to use spring.resources.cache-period property to set the cache period of default Boot Resource Handler. So add the following to your application.properties:
spring.resources.cache-period = 31536000

And delete the BaseMvcConfig config file.
Comment: `spring.resources.cache-period` is deprecated in favour of `spring.resources.cache.period`
Comment: `spring.resources.cache-period` and `spring.resources.cache.period` is
deprecated. You should use: `spring.web.resources.cache.period`
Comment: With Spring default configurations, if you save your file in `classpath:/static/all.css`, you can access it through `http://localhost:8080/all.css`. If you're using that Java Config, you should send your request to `http://localhost:8080/static/all.css`.
Comment: spring.resources.cache.cachecontrol.max-age worked for me
Answer: Since spring.resources.cache-period is deprecated, you may want to use the newer spring.web.resources.cache.period instead, which takes either seconds (as before), or a Duration specification like this:
spring.web.resources.cache.period = P30D

See Duration#parse() JavaDoc for reference.
Comment: `spring.resources.cache.period` is
deprecated. Now you should use: `spring.web.resources.cache.period`
Comment: Funny how my _update post_ became outdated itself. However, I will just happily update my update post. :-)
Answer: If you want to use spring security for controllers and setup cache for static content then you might want to configure exceptions in your WebSecurityConfigurerAdapter and set cache period in application.properties:
@Override
public void configure(WebSecurity web) throws Exception {
   web.ignoring().antMatchers("/js/**", "/css/**");
}

#1 week cache
spring.resources.cache-period = 604800

Comment: In my particular setup (using Spring Boot 2.6.4) it doesn't seem to matter whether or not you add the `web.ignoring()` call.  The cache period (set using the newer `spring.web.resources.cache.period`) seems to control all of the static resources whether spring security thinks it is ignoring them or not.


Packets getting blocked by iptables on port 22

Question: I'm noticing some blocked packets in my iptables log when running a python library that calls paramiko. I noticed the blocked packets when trying to figure out why there is inconsistent network performance with this library when iptables is running. Basically, the server (10.0.12.206 in the log below) runs the library which uses paramiko to execute commands securely on the client (10.0.10.103 in the log below) over port 22. When the client is running permissive iptables, it works pretty well. When the client runs iptables with the rules below, there are typically indefinite hangs, and I suspect it might be due to some packets getting blocked by iptables running on the client, since these packets only appear in the log when the library is running.
These are my iptables rules-
-P INPUT DROP
-P FORWARD DROP
-P OUTPUT DROP

-A INPUT -i lo -j -ACCEPT
-A OUTPUT -o lo -j -ACCEPT

-A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT

-A OUTPUT -o eth0 -p udp --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT

-A INPUT -m state --state ESTABLISHED,RELATED -j -ACCEPT
-A OUTPUT -m state --state ESTABLISHED,RELATED -j -ACCEPT

-A INPUT -j LOG --log-prefix "IPtables DROP DEFAULT IN: "
-A OUTPUT -j LOG --log-prefix "IPtables DROP DEFAULT OUT: "

-P INPUT DROP
-P FORWARD DROP
-P OUTPUT DROP

These are the usual messages in the client log-
Oct  7 16:43:08 ip-10-0-10-103 kernel: IPtables DROP DEFAULT IN: IN=eth0 OUT= MAC=<withheld> SRC=10.0.12.206 DST=10.0.10.103 LEN=52 TOS=0x00 PREC=0x00 TTL=64 ID=18436 DF PROTO=TCP SPT=58634 DPT=22 WINDOW=523 RES=0x00 ACK FIN URGP=0

Oct  7 16:44:14 ip-10-0-10-103 kernel: IPtables DROP DEFAULT OUT: IN= OUT=eth0 SRC=10.0.10.103 DST=10.0.12.206 LEN=260 TOS=0x00 PREC=0x00 TTL=64 ID=57627 DF PROTO=TCP SPT=22 DPT=58634 WINDOW=240 RES=0x00 ACK PSH URGP=0

I'd like to see if these blocked packets are causing the trouble. How do I allow these blocked packets to pass? I tried a couple of rules but had no luck, e.g.-
-A OUTPUT -o eth0 -p tcp --tcp-flags ALL ACK,PSH,URG -j ACCEPT

Comment: Instead of using `iptables` rules directly, consider using a firewall management solution like `shorewall` or `ufw`. They take care of the pitfalls like this when setting up rules.
Answer: I think the problem is that you are allowing OUTPUT to port 22, but it should be coming from port 22:
-A OUTPUT -o eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT

This should fix the second log line you posted.  I'm not sure why the first packet you logged is getting caught though.  Can you check iptables -nvL and make sure these rules are actually getting applied?
Comment: Thanks very much for your help. That fixed it. (And yes, the rules were definitely getting applied as per `iptables nvL`).


Como numerar o alfabeto e somar suas letras obtendo um resultado a cada palavra escrita?

Question: Queria obter o resultado de palavras com suas letras somadas...
Exemplo:  a=1 b=2 c=3 se eu digitar a palavra "bac" o resultado seria "6".
Porque somou as 3 letras a+b+c=6.
Tentei esse código mas não funciona:
public static void main(String[] args){

Scanner on = new Scanner(System.in);
System.out.println("Digite a palavra: ");

String soma;

soma = on.nextLine();

char a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z;

a=1; b=2; c=3; d=4; e=5; f=6; g=7; h=8; i=9; j=10; k=11; l=12; m=13;
n=14; o=15; p=16; q=17; r=18; s=19; t=20; u=21; v=22; w=23; x=24; y=25; z=26;

System.out.println(soma);

  }
}

Answer: É bem simples usando a matemática:
import java.util.Scanner;

class Ideone {
    public static void main(String[] args) {
        Scanner on = new Scanner(System.in);
        System.out.println("Digite a palavra: ");
        String texto = on.nextLine();
        int soma = 0;
        for (char caractere : texto.toCharArray()) { //varre cada caractere
            //"A" vale 97, então tira 96 e assim por diante
            soma += caractere > 96 && caractere < 123 ? caractere - 96 : 0;
        }
        System.out.println(soma);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Outras coisas podem ser feitas diferentemente, mas a pergunta não dá requisitos claros.
O importante é que essa solução usa o princípio de KISS. Nunca complique o que pode ser simples. Há problemas que são inerentemente complexos e só podemos gerenciá-los bem. Soluções complicadas podem e devem ser evitadas.
Comment: Muito obrigado pela resposta!!! @bigown
Answer: O que o seu código está fazendo é simplesmente imprimir o que alguém digita. Você precisa adicionar a lógica de somatório e mapeamento do alfabeto. Para isso, você pode realizar as seguintes modificações:
1- Criar um método que contabiliza as somas:
private static int calcularSomaPalavra(String palavra, Map<Character, Integer> alfabeto) {
    int valorSoma = 0;
    for (char caractere : palavra.toCharArray()) {
        if (isCaractereEncontrado(alfabeto, caractere))
            valorSoma += getValorCaractere(alfabeto, caractere);
    }
    return valorSoma;
}

O que foi feito foi criar um método que dado uma palavra obtém a soma dos caracteres da palavra, simples assim. A grande sacada aqui é verificar se o caractere possui um valor numérico mapeado e somá-lo ao totalizador. Isso pode ser feito de várias formas, por simplicidade você pode utilizar um Map:
// Declaração do map de letras do alfabeto.
Map<Character, Integer> alfabeto = new HashMap<Character, Integer>();

//Mapeamento dos valores de cada letra do alfabeto
alfabeto.put('a', 1);
alfabeto.put('b', 2);
...
alfabeto.put('z', 26);

private static Integer getValorCaractere(Map<Character, Integer> alfabeto, char caractere) {
    return alfabeto.get(caractere);
}

private static boolean isCaractereEncontrado(Map<Character, Integer> alfabeto, char caractere) {
    return getValorCaractere(alfabeto, caractere) != null;
}

Com a utilização de um Map, a lógica de verificação do valor numérico do caracter trata-se apenas da chamada do método get.
2- Imprimir a soma da palavra:
int valorSoma = calcularSomaPalavra(soma, alfabeto);
System.out.println(valorSoma);

Agora você está imprimindo de fato a soma, e não apenas o que o usuário digita. Juntando tudo, teríamos:
public static void main(String[] args) {
    Map<Character, Integer> alfabeto = new HashMap<Character, Integer>();
    Scanner on = new Scanner(System.in);
    System.out.println("Digite a palavra: ");

    String soma;

    soma = on.nextLine();

    alfabeto.put('a', 1);
    alfabeto.put('b', 2);
    ...
    alfabeto.put('z', 26);

    int valorSoma = calcularSomaPalavra(soma, alfabeto);
    System.out.println(valorSoma);

}

private static int calcularSomaPalavra(String palavra, Map<Character, Integer> alfabeto) {
    int valorSoma = 0;
    for (char caractere : palavra.toCharArray()) {
        if (isCaractereEncontrado(alfabeto, caractere))
            valorSoma += getValorCaractere(alfabeto, caractere);
    }
    return valorSoma;
}

private static Integer getValorCaractere(Map<Character, Integer> alfabeto, char caractere) {
    return alfabeto.get(caractere);
}

private static boolean isCaractereEncontrado(Map<Character, Integer> alfabeto, char caractere) {
    return getValorCaractere(alfabeto, caractere) != null;
}

Uma dica é sempre pegar um problema e dividí-lo em etapas de resolução, assim você consegue resolver um problema maior resolvendo cada etapa dele, o que facilita a elaboração da solução global.
Comment: Olá @Giuliana Bezerra Muito Obrigado!!!! Muito boa sua explicação!!!! Realmente muito show!!! Você é Demais!!!!


Groups of order $n^2$ that have no subgroup of order $n$

Question: For which $n$ is there a group of order $n^2$ without a subgroup of order $n$.
Such groups can not be nilpotent.
This question is related to Sudokus as composition tables of finite groups.
Comment: No, there is an example with $n=5^3 \times 3$ that is similar to the one with $n=24$, but with $|N| = 5^6$.
Comment: Must $n$ be even?
Answer: I have a feeling that there is not much we can say in general, but here is an infinite family of examples.
Let $p$ be an odd prime such that $3$ divides $p+1$ (for example $p = 5$).
One example is $G = A_4 \times ((C_p)^2 \rtimes C_3)$, where the semidirect product is nontrivial. Then $G$ has order $(6p)^2$, but $G$ has no subgroup of order $6p$.
Proof: Let $H$ be a subgroup of order $6p$. Then $H$ has a subgroup of order $2$. Since any such subgroup is contained in the $A_4$ factor, it follows that $H \cap A_4$ has order divisible by $2$. Now $A_4$ has no subgroup of order $6$, so $H \cap A_4$ must have order $2$.
Now note that because $3$ does not divide $p-1$, any group of order $3p$ is cyclic. Thus $H$ contains an element of order $3p$. There is no such element in $(C_p)^2 \rtimes C_3$, so it must be of the form $xy$, where $x \in A_4$ has order $3$ and $y \in (C_p)^2 \rtimes C_3$ has order $p$. But then $x \in H \cap A_4$, a contradiction since $H \cap A_4$ has order $2$.

The above gives examples for $n = 30, 66, 102, 138, \ldots$
With GAP it is possible to check that $n = 28$ also gives examples, for example $\operatorname{SmallGroup}(784, 160)$ and $\operatorname{SmallGroup}(784, 162)$. I am not sure if there are any examples for smaller $n$.
Comment: Not so long with a bit of parallel processing, but it would have helped if I had started at the far end. SmallGroup(576,8661) has no subgroup of order $24$. That's the only example, and $24$ is the smallest $n$ with this property.
Comment: With GAP I went through groups of order $n^2$, where $n \leq 30$ and $n \neq 24$, and the examples in this answer are the only ones among them (one for $n = 30$ and two for $n = 28$). There are $8681$ groups of order $24^2 = 576$, so going through them manually might take a very long time
Comment: @DerekHolt: Thanks for saving me the trouble!
Comment: I checked n=31...44; all such groups have a subgroup of index n.
Answer: Just to expand my comment, the smallest $n$ for which this occurs is $n=24$, and the single example of a group of order $24^2$ with no subgroup of order $24$ is ${\mathtt{SmallGroup}}(576,8661)$, a semidirect product $N \rtimes C_9$, where $N$ is elementary abelian of order $64$, and the $C_9$ acts irreducibly on $N$.
It is a Frobenius group of degree $64$ and can also be accessed as $\mathtt{PrimitiveGroup}(64,1)$.


How to maintain session persistence and file sync in load balancing?

Question: I'm not very educated when it comes to distributed systems.
I have a website hosted currently on a windows server and I want to load balance to 2-3 servers.
But I have some problems in mind, and I want to know what I need to do about them.
1- Session persistence. I thought about using nginx open source but found out that the only way to do sticky sessions is ip_hash which causes uneven distribution among the servers. I don't want this, are there any free alternatives for windows that allow sticky sessions without IP Hashing?
2- Updating and downloading files. When I need to update/copy/create files, do I need to do it on all servers? Is there any easier way?
Answer:
When you have many users, IP hashing will statistically give you almost uniform distribution across servers. I would suggest to stay with sticky sessions with ip_hash. That is the simplest and most robust way.

Alternatively, you can store sessions in something like memcached or any other no-SQL database, this way you won't need to care about session sticking.

There are no easier ways, but there are more automated ways which will require less manual work. You can automate this using repository and doing remote execution of  commands like PSExec or WMI.

Files uploaded by users will have to be ether synchronized to all servers, or uploaded and served from network location accessible to all servers.
Comment: Thanks. Btw is ip_hash random?
Comment: @MarkusPauli it is pseudorandom. If you look at 10 clients it will not look very random. But at 10000 clients over time they will distribute quite randomly. That's the nature of the hash.


Help solving a probability problem

Question: I encountered the following problem. I am not very sure on how to solve it. Can someone help me solve the problem.
Problem:
A dart is thrown onto a circular plate with unit radius. X is the random variable representing the distance of the point where the dart lands from the origin of the plate.
Assume that the dart always lands on the plate and that the dart is equally likely to land
anywhere on the plate.
Find (i) P(X < a) and (ii) P(a < X < b), where a < b <=1.
A reply would be appreciated
Answer: You have a uniform distribution on the plate, so its density is $f_X(x)$ is $1/\pi$ on the plate and $0$ off the place.  So if $A$ is a subset of the plate,
$$P(A) = {|A|\over \pi},$$
where $|A|$ denotes the area of $A$.
Can you take it from here?
Comment: My understanding of the problem is, since X is the distance of the dart from the origin, X is equally likely to take a value in the range [0,1]. So X has a uniform distribution with parameters (0,1). So its density function is f(x)=1 in [0,1] and 0 otherwise.
So P(X<a) = a and P(a<X<b) =b-a.

I could not see why area of the circular plate is considered here. Can you say whether my understanding is correct.
Comment: OP: `Assume that the dart ... is equally likely to land anywhere on the plate`.
Comment: Yes, the dart is equally likely to land anywhere on the plate. But, the random variable X just measures the distance from the origin. I do not understand how area comes into this picture.
Answer: (i) $P(X<a)=\frac{Area\;  of\;  circular\; plate \; with\;  radius\;  a}{Area\; of\; whole\; circular\; plate}=\frac{a^2\pi}{1^2\pi}=a^2$.
(ii) $P(a<X<b)=P(X<b)-P(X<a)$ gives a result.
Comment: My understanding of the problem is, since X is the distance of the dart from the origin, X is equally likely to take a value in the range [0,1]. So X has a uniform distribution with parameters (0,1). So its density function is f(x)=1 in [0,1] and 0 otherwise.
So P(X<a) = a and P(a<X<b) =b-a.

I could not see why area of the circular plate is considered here. Can you say whether my understanding is correct.
Comment: OP: `Assume that the dart ... is equally likely to land anywhere on the plate`.

Help solving a probability problem


Fatal error while upgrading

Question: While upgrading to Drupal 7.39 from 6.37, after copying the new files over into the site's directory, when I tried to navigate to the website I see a blank page with the following error: Fatal error: Cannot redeclare template_preprocess_block() (previously declared in /home2/mccotter/public_html/test/includes/theme.inc:2042) in /home2/mccotter/public_html/test/modules/block/block.module on line 1038
I have not yet run update.php, and when I try to the page appears blank.  I was unable to sign in as the maintenance user, but I set $update_free_access = TRUE.
For reference, the site that I am attempting to upgrade is jailtraining.org/test
Comment: try `cache clear` or `registry rebuild` option. I hope you have backup of the site and disabled all the `contributed modules` that should be your first step :) first upgrade the core and after that upgrade other modules.
Comment: Yeah, everything's backed up and I've disabled all the contributed modules.  I'm pretty new to Drupal, though, so could you point me somewhere that explains how to use the cache clear or registry rebuild options?
Comment: clearing the cache didn't help, I still have yet to try the registry rebuild option, though
Answer: Pre-First back up your site.
First upgrade to the most recent version of Drupal 6. The follow instructions here to move to Drupal 7:
https://www.drupal.org/documentation/upgrade
Have trouble? Explain where you are in the process at that point so one might help.
Comment: Thank you for the suggestions!  I have been following the upgrade instructions outlined in Upgrade.txt included with the Drupal 7 download, and the latest version of Drupal 6 is 6.37.  I'm sorry if wasn't clear enough with where I am in the upgrade process, but I'm at the point where you would normally run update.php.

Fatal error while upgrading


Members Area php session login logout

Question: I have a Members area in the below model but I am not sure whether it is safe or not. Please tell me your suggestions and opinion on this.
I made a page called members.html and Members area page called members.php
Code inside members.php
<?
session_start();

if($_SESSION['user_level'] == 0)
{
include 'members.html';
}

echo "
Logout";

?>

In the logout.php
<?
session_start();
session_unset();
session_destroy();

header("location:home.html");
exit();
?>

Is this coding good enough to be called as a password protected page? what should I add to make it more safe?
Thanks!
Edit.......
The coding is not working. I logout out and went to the members page directly and the page is working fine. I am a little confused, please help me with the code.
In the checkuser.php page I have the below sessions,
            $_SESSION['first_name'] = $first_name;

    $_SESSION['last_name'] = $last_name;

    $_SESSION['email_address'] = $email_address;

    $_SESSION['user_level'] = $user_level;

and I have the username and password which users entered in variables $username and $password.
Edit..........
I found the below answer and is working for now. But I am not sure this is right or not.
if (isset($_SESSION['user_id']))
{
if($_SESSION['user_level'] == 0){
include 'members.html';
}
}
else
{
header("Location: home.html");
}

Comment: Yes, but I can't see where your sessions are being set.  You may also want to use SSL since sessions can be hijacked.
Answer: Your members area page looks completely unprotected. I don't see any session checking in the code below. What session variables do logged in users have?
<?
session_start();

include 'members.html';

echo "
Logout";
?>

Comment: Sorry I forget this line.
if($_SESSION['user_level'] == 0){
 include 'pay.html';
}

Members Area php session login logout


Protect SYSVOL folder without damaging the execution of the GPOs

Question: Ever since I begun working with Windows Server 2008 I have noticed that the SYSVOL folder C:\Windows\SYSVOL\sysvol is shared and the NTFS permissions for the Authenticated Users group are almost maxed.

Although I know that this folder has to be shared (and it is shared by default) I have to protect it somehow from the everyday users. Last week I turned off the shared permissions and it interrupted the execution of GPO.. ffs it took me whole day until i realized that after i removed the sharing the GPOs stoped processing on the client workstations  :S.
So how to give the minimum permission settings on this folder so that it is protected from everyday users but the execution of the GPOs is not interrupted?
Comment: So what are you "protecting" the sysvol folder from? What precise threat vector are you worried about here? From what I see so far, the biggest threat is people changing settings without understanding the implications. Don't Play With The Sysvol Folder Unless You Want Bad Things To Happen.
Comment: why? You shouldn't be storing anything confidential in there. If you have, for example, a login script that is delivered by GPO and includes a username and password then it may be possible to restrict viewing of that policy folder via special permissions, but I seriously wouldn't touch the sysvol folder itself.
Comment: I got it now... however I just don't want anyone except the Admins  in our company to see the SYSVOL folder..
Answer: It's obvious that you're out of your element here (no offense intended) so my suggestion is that you leave SYSVOL alone, unless you:
A. Modified NTFS permissions on the root folder prior to the creation of SYSVOL
B. Moved SYSVOL to another volume
c. Mucked with the NTFS permissions of SYSVOL
In which case, you should follow this article:
http://technet.microsoft.com/en-us/library/cc816750(v=ws.10).aspx
Answer: I don't see Everyone listed in your screenshot there... authenticated users is fine, they by default have to have the read and execute and list folder contents permissions to be able to apply GPO. As far as I know, there is no way to limit this, they have to be able to read it or they won't be able to apply GPO's.
Comment: Oh yes... it should be `Authenticated Users`... I will corect it now...
Comment: So i guess it is OK to be this way... Perhaps I can protect it further if I set the `Hidden` attribute to the SYSVOL folder?
Comment: yes setting it to hidden will prevent users from seeing it providing they don't have "show hidden files" enabled.