In Git pre-commit hook, temporarily remove all changes that are not about to be commited

Question: I would like my pre-commit hook to compile the program and run all the automatic tests before allowing to perform the commit.
The problem is that usually my working copy is not clean while I'm committing. They are not staged or even untracked files that I don't want to commit. Sometimes I even explicitly specify only a few files to commit which has nothing to do with what is currently staged.
Of course I want to compile and test only the changes that will be committed, ignoring the other ones.
There would be 3 steps to it:

Remove all changes that won't be committed.
Run the tests.
Restore the all the changes to exactly how they were before the 1st step.

The 1st step could be achieved by running git stash push --include-untracked --keep-index. The stash entry would also help with the 3rd step.
However, I don't know what to do when I'm committing explicit list of files that are not staged.
(The 2nd step is not really a part of the question.)
The 3rd step could be theoretically done with command git stash pop --index but this command seems to be prone to conflicts if some file was staged and then changed more without staging it again.
This script creates a repository with some files and changes that cover various corner cases:
#!/usr/bin/env sh

set -e -x

git init test-repo
cd test-repo
git config user.email "firstname.lastname@example.com"
git config user.name "Your Name"

echo foo >old-file-unchanged
echo foo >old-file-changed-staged
echo foo >old-file-changed-unstaged
echo foo >old-file-changed-both
git add .
git commit -m 'previous commit'

echo bar >old-file-changed-staged
echo bar >old-file-changed-both
echo bar >new-file-staged
echo bar >new-file-both
git add .
echo baz >old-file-changed-unstaged
echo baz >old-file-changed-both
echo baz >new-file-both
echo baz >untracked-file

Comment: I recommend not doing this at all: look into the `pre-commit` program instead, or consider doing a `git checkout-index` into a temporary directory. All solutions to this problem have their own problems, though, so you're kind of in a pick-your-flaws situation here.
Comment: @torek Do you mean the `pre-commit.sample`? Yes, it provides examples how to get the list of cached files but testing individual files is not sufficient for what I'm trying to do. I need to compile everything into a single program to do those tests. As for `git checkout-index`, I'm not entirely clear on what it does. Does it allow to make a clear copy of the to-be-committed state in another directory? If this is the case, I'll pass. There is a lot of ignored `*.o` files in the current directory. If I would need to recompile everything from scratch, it would take significantly too long.
Comment: No, not the included sample, the stuff at https://pre-commit.com/
Answer: You were actually quite close to a correct solution.
(In this answer, I'm going to use the word "cache" instead of "stage" because the latter one is too similar to "stash".)
In fact, the trick with using stash would work even if you were to commit files that are not cached. This is because Git changes the cache for the duration of running hooks, so it always contains the correct files. You can check it by adding the command git status to your pre-commit hook.
So you can use git stash push --include-untracked --keep-index.
The problem with conflicts when restoring the stash is also quite easily solvable. You already have all the changes backed up in the stash so there is no risk of loosing anything. Just remove all the current changes and apply the stash to a clean slate.
This can be done in two steps.
The command git reset --hard will remove all the tracked files.
The command git clean -d --force will remove all untracked files.
After that you can run git stash pop --index without any risk of conflicts.

A simple hook would look like that:
#!/bin/sh

set -e

git stash push --include-untracked --keep-index --quiet --message='Backed up state for the pre-commit hook (if you can see it, something went wrong)'

#TODO Tests go here

git reset --hard --quiet
git clean -d --force --quiet
git stash pop --index --quiet

exit $tests_result

Let's break it down.
set -e ensures that the script stops immediately in case of an error so it won't do any further damage.
The stash entry with backup of all changes is done at the beginning so in case of an error you can take manual control and restore everything.
git stash push --include-untracked --keep-index --quiet --message='...' fulfills two purposes. It creates a backup off all current changes and removes all non staged changes from the working directory.
The flag --include-untracked makes sure that untracked files are also backed up and removed.
The flag --keep-index cancels removal of the cached changes from the working directory (but they are still included in the stash).
#TODO Tests go here is where you tests go.
Make sure you don't exit the script here. You still need to restore the stashed changes before doing that.
Instead of exiting with an error code, set its value to the variable tests_result.
git reset --hard --quiet removes all the tracked changes from the working directory.
The flag --hard makes sure that nothing stays in the cache and all files are deleted.
git clean -d --force --quiet removes all the untracked files from the working directory.
The flag -d tells Git to remove directories recursively.
The flag --force tells Git you know what you're doing and it is really supposed to do delete all those files.
git stash pop --index --quiet restores all changes saved in the latest stash and removes it.
The flag --index tells it to make sure it didn't mixed up which files were cached and which were not.

Disadvantages of this method
This method is only semi-robust and it should be sufficient for simple use cases.
However, they are quite a few corner cases that may break something during real-life usage.
git stash push refuses to work with files that were only added with the flag --intent-to-add.
I'm not sure why that is and I haven't found a way to fix it.
You can bypass the problem by adding the file without the flag or by at least adding it as an empty file and left only the content not cached.
Git tracks only files, not directories. However, the command git clean can remove directories. As the result, the script will remove empty directories (unless they are ignored).
Files that were added to .gitignore since the last commit will be deleted. I consider this a feature but if you want to prevent it, you can by reversing the order of git reset and git clean.
Note that this works only if .gitignore is included to the current commit.
git stash push does not create a new stash if there is no changes but it still returns 0. To handle commits without changes such as changing the message using --amend you would need to add some code that checks if stash was really created and pop it only if it was.
Git stash seems to remove the information about current merge, so using this code on a merge commit will break it.
To prevent that, you need to backup files .git/MERGE_* and restore them after popping the stash.

A robust solution
I've managed to iron out most of the kinks of this method (making the code much longer in the process).
The only remaining problem is removing empty directories and ignored files (as described above). I don't think these are severe enough issues to take time trying to bypass them. (It is doable, though.)
#!/bin/sh

backup_dir='./pre-commit-hook-backup'
if [ -e "$backup_dir" ]
then
    printf '"%s" already exists!\n' "$backup_dir" 1>&2
    exit 1
fi

intent_to_add_list_file="$backup_dir/intent-to-add"
remove_intent_to_add() {
    git diff --name-only --diff-filter=A | tr '\n' '\0' >"$intent_to_add_list_file"
    xargs -0 -r -- git reset --quiet -- <"$intent_to_add_list_file"
}
readd_intent_to_add() {
    xargs -0 -r -- git add --intent-to-add --force -- <"$intent_to_add_list_file"
}

backup_merge_info() {
    echo 'If you can see this, tests in the `pre-commit` hook went wrong. You need to fix this manually.' >"$backup_dir/README"
    find ./.git -name 'MERGE_*' -exec cp {} "$backup_dir" \;
}
restore_merge_info() {
    find "$backup_dir" -name 'MERGE_*' -exec mv {} ./.git \;
}

create_stash() {
    git stash push --include-untracked --keep-index --quiet --message='Backed up state for the pre-commit hook (if you can see it, something went wrong)'
}
restore_stash() {
    git reset --hard --quiet
    git clean -d --force --quiet
    git stash pop --index --quiet
}

run_tests() (
    set +e
    printf 'TODO: Put your tests here.\n' 1>&2
    echo $?
)

set -e
mkdir "$backup_dir"
remove_intent_to_add
backup_merge_info
create_stash
tests_result=$(run_tests)
restore_stash
restore_merge_info
readd_intent_to_add
rm -r "$backup_dir"
exit "$tests_result"

Comment: Nice answer. re "not sure why that is", stash checks whether a stash pop will recreate the stashed index, and there is simply no way to write an intent-to-add entry in a committed tree. There is no representation for it; if there were, it'd be an added entry, not an entry-to-be-added later. The intent-to-add entry is there to show various tools that they should regard a work tree file as "tracked" so the various diffing and patching tools show the change and offer to really add it (before the next commit in the series you're building) as an option.
Comment: @jthill An entry of Git stash is comprised of 2 (or three) commits. One of them is for cached files and it is capable of storing a newly added file. Another one is for not cached files and I can't see a reason why it couldn't be able to store a newly added file which would mean it is intended to be added but not in the cache. Am I missing something here?
Comment: Yes, the intent-to-add entries *aren't added yet*. The entire point of that index entry is it *isn't* written to the object db.
Comment: @jthill The problem isn't really how they are represented when they are in the working directory. This already works. The problem is that they are not represented in the stash while they could be easily be just included in the non-cached commit as new files. `git apply` could convert that back to whatever representation the working directory uses. I'm fine with the explanation that it just isn't implemented yet because other things have higher priority or something. However, if you want to suggest there is some technical reason for that, I still don't see it.
Comment: I don't think there is a *technical* reason. Note that intent-to-add was completely broken for several years and nobody noticed; it's not heavily used. (But as jthill notes, you'll turn "intent to add" into "actually added" when you commit—there would need to be a way to store the intent flag and reinstate the weird state later. This is obviously do-able, but it needs some additional information: probably a fourth commit in the stash.)
Comment: No, you're not getting it. Stash writes ordinary commits of ordinary trees, which by definition do not contain any "intent to add" entries because writing a  tree adds it to the object db, not by any arbitrary definittion or authority but by the actual fact of it being written to the object db. The "intent-to-add" entry in the index cannot exist anywhere but the index, not because nobody's "implemented" it but because if it's in a written tree, you've gone beyond "intent to add" that entry to a written tree, you've *actually* added it to a written tree.
Comment: @torek No, you wouldn't ;) The fact, a file is present in the stash commit that represents non-cached changes and not in the stash commit that represents stashed changed, suffices for intend-to-add flag.
Comment: Ah, good point. This only applies to the stash commits themselves, but when taken as a pair, the absence in `i` plus presence in `w` could only be explained by the `N` flag, yes.
Comment: @jthill OK, let's say the db don't have any GC mechanism and we don't want to litter it with untracked files. When we use the flag `--include-untracked`, we commit the file anyway so maybe it could work at least with this flag?
Comment: If you want to implement it and try to sell it, have at. I think it's a waste of time, deep into foolish consistency territory: massive amounts of pain, no value to anyone. As it stands, intent-to-add entries are a special case for in-flight rebuilds, and you're trying to eliminate one special case by introducing an entire host of others.


Meteor : get the opposite statement from a variable into handlebars

Question: I'm discovering Meteor and was asking myself for a thing.
How in a template can we reverse the boolean into the handlebars from a template ?
There is an example of what I'm trying to do :
task.html

    ...

But I'm getting an error "Expected close "}}". Maybe it's not possible.
Thank you !
Answer: Here is your solution : How to IF NOT inside of {{ #each }} template
Use {{#unless}} :
Example of use :
{{#unless checked}}
    ....
{{/unless}}

Comment: Didn't find anything with my keywords, now I know why.. Thanks !
Comment: All you need to know about Blaze you will find in the guide. Look at: https://guide.meteor.com/blaze.html
Answer: There is no ! syntax handling in the template.
Neither {{#if !myVar}} nor {{#if not myVar}} worked.
You need to remove ! from !checked:

Or you can use unless:

Comment: Yeah, it's weird we can't find it easily in the documentation. Thank you for your response !


Combinations in tournament

Question: A tournament includes P total players. The game played in rounds with teams of size T. Possible number of teams is (P T).
Questions

How would you calculate the number of total possible combinations of matches?
How would you calculate the number of total possible matches per round?

Examples
<code>Example 1: 4 players in teams of 2
4 Players
1-2
1-3
1-4
2-3
2-4
3-4
=(4 2) = 6

1-2 - 3-4
1-3 - 2-4
1-4 - 2-3
= 3

Example2: 5 players in teams of 2
Teams
1-2
1-3
1-4
1-5
2-3
2-4
2-5
3-4
3-5
4-5
=(5 2) = 10

Matches
1-2 - 3-4
1-2 - 3-5
1-2 - 4-5
1-3 - 2-4
1-3 - 2-5
1-3 - 4-5
1-4 - 2-3
1-4 - 2-5
1-4 - 3-5
1-5 - 2-3
1-5 - 2-4
1-5 - 3-4
2-3 - 4-5
2-4 - 3-5
2-5 - 3-4
= 15
</code>
Answer: you have to chose the first and the second teams. for the first team you have $\binom{P}T$ and for the second team you have $\binom{P-T}T$ however you are counting each match twice in this case so the total number of possible matches is $$\frac{\binom{P}T\binom{P-T}T}{2}$$
The number of possible combinations of matches per round (assuming you get as many teams to play as possible in each round) is $$\prod_{n=0}^{n=2\lfloor{T/2P}\rfloor-1}\binom{P-(Tn)}T/(\lfloor{T/2P}\rfloor!(2^{\lfloor{T/2P}\rfloor})$$

Combinations in tournament


O número e a letra ficam juntos quando tento compilar uma variável

Question: Estou criando variáveis, e quando eu compilo, o número sai "grudado" com a letra. Não sei explicar bem, mas é mais ou menos isso.
Veja meu código abaixo:
int numero = 24;
System.out.println("Eu gosto muito de" + numero);

O resultado é:
Eu gosto muito de24

Note que o 24 está junto ao "de", e eu queria que eles ficassem separados, porém eu não sei como resolver isso.
Isso também acontece com números.
Answer: A concatenação não adiciona um espaço automaticamente entre os seus operandos. Isso significa que você deve colocar o espaço manualmente na string:
int numero = 24;
System.out.println("Eu gosto muito de " + numero);
//                                   ↑
//                          Note o espaço aqui

Veja a diferença em um snippet em JavaScript:

console.log('O número é' + 10);

console.log('O número é ' + 10);


Convergence of sum with binomial coefficient

Question: I found this exercise in a book and I don't know how to start:

With the help of probabilistic methods, prove that
$$
\lim_{n\rightarrow\infty} \frac{1}{4^n} \sum_{k=0}^n  \binom{2n}{k} = 1/2
$$

One cannot use the binomial theorem because the sum just goes to $n$ and not to $2n$ and besides that, am I supposed to use one of the limit theorems in stochastics? If so, which one and how can I approach this exercise.
Comment: Yes, you can use the binomial theorem! Hint: $\binom{2n}{k}=\binom{2n}{2n-k}$
Answer: Let $(\xi_j)_{j\geqslant 1}$ be an i.i.d. sequence of random variables such that $\mathbb P(\xi_1=1)=\mathbb P(\xi_1=0)=1/2$. Then $\sum_{j=1}^{2n}\xi_j$ has a binomial distribution with parameters $(2n,1/2)$ hence
$$
\frac{1}{4^n} \sum_{k=0}^n  \binom{2n}{k}=\mathbb P\left(\sum_{j=1}^{2n}\xi_j\leqslant n\right).
$$
The central limit theorem will give the answer.
Answer: We obtain
\begin{align*}
\color{blue}{\sum_{k=0}^n\binom{2n}{k}}&=\frac{1}{2}\sum_{k=0}^{n-1}\binom{2n}{k}+\binom{2n}{n}+\frac{1}{2}\sum_{k=n+1}^{2n}\binom{2n}{k}\tag{1}\\
&=\frac{1}{2}\sum_{k=0}^{2n}\binom{2n}{k}+\frac{1}{2}\binom{2n}{n}\\
&\,\,\color{blue}{=\frac{1}{2}2^{2n}+\frac{1}{2}\binom{2n}{n}}\tag{2}
\end{align*}
In (1) we use the symmetry $\binom{2n}{k}=\binom{2n}{2n-k}$. We use Stirling's approximation formula
\begin{align*}
n!\sim \left(\frac{n}{e}\right)^n\sqrt{2\pi n}
\end{align*}
and get
\begin{align*}
\color{blue}{\binom{2n}{n}}=\frac{(2n)!}{n!n!}
&\sim\left(\frac{2n}{e}\right)^{2n}\sqrt{4\pi n}\left(\frac{e}{n}\right)^{2n}\frac{1}{2\pi n}\\
&\,\,\color{blue}{\sim 4^n\frac{1}{\sqrt{\pi n}}}\tag{3}
\end{align*}

We conclude from (2) and (3)
\begin{align*}
\color{blue}{\frac{1}{4^n}}\color{blue}{\sum_{k=0}^n\binom{2n}{k}}
&=\frac{1}{4^n}\left(\frac{1}{2}2^{2n}+\frac{1}{2}\binom{2n}{n}\right)\\
&=\frac{1}{2}+\frac{1}{2}\,\frac{1}{4^n}\binom{2n}{n}\\
&\sim\frac{1}{2}+\frac{1}{2}\frac{1}{\sqrt{\pi n}}\color{blue}{\underset{n\to\infty }{\longrightarrow} \frac{1}{2}}
\end{align*}
and the claim follows.


Geometry problem - IOQM

Question: In $\triangle ABC$, $AC = BC$, $\angle C=20^{\circ}$, $M$ is on the side $AC$ and $N$ is on the side $BC$, such that $\angle BAN=50^{\circ}, \angle ABM = 60^{\circ}$. Find $\angle NMB$ in degrees.
It is INMO-IOQM level question and I am not able to solve anyhow, please help. I tried by angle chasing but up to no avail.
Answer: Take a point P on AC between A and M such that $\angle ABP=20$
Hence $BA=BP$
$\angle PMB= \angle PBM= 40$
Hence  $PB=PM$
$\angle BAN= \angle BNA= 50$
Hence  $BA=BN$
So $\triangle BPN$ is equilateral triangle
$PN=PM$ and $\angle MPN=40$
Finally
$\angle PMN= \angle PNM= 70$
$\angle NMB= 30$
Answer: Trigonometric Solution
Let $\angle NMB=\alpha$
$\dfrac{BN}{\sin\alpha}=\dfrac{MB}{\sin(160-\alpha)}$,$\triangle NMB$,and, $\dfrac{AB}{\sin40}=\dfrac{MB}{\sin 80}$,  $\triangle AMB$ (Sine Theorem)
Since $AB=BN$, then
$\dfrac{\sin\alpha}{\sin(160-\alpha)}=\dfrac{\sin40}{\sin 80}=\dfrac{1}{2\cos40}$
$\sin(160-\alpha)=2 \sin\alpha \cos40=\sin(\alpha+40)+ \sin(\alpha-40)$
$\sin(160-\alpha)- \sin(\alpha-40)=\sin(\alpha+40)$
$2\cos60 \sin(100-\alpha)=\sin(\alpha+40)$
$\sin(100-\alpha)=\sin(\alpha+40)$

Case

$100-\alpha=\alpha+40 \implies \alpha=30$

Case

$100-\alpha+\alpha+40=180 \implies 140\not=180$ , NA
Comment: Please,explain how yoU got angles in sine rule
Comment: Let $\angle NMB=\alpha$,$\angle MNB=180-(\alpha+20)=160-\alpha)$,$\triangle NMB$,$\angle AMB=180-(80+60)=40$,$\triangle AMB$

Geometry problem - IOQM


Average distance in distance matrix

Question: I have a set of many longitude and latitude points within a city. I constructed the nxn euclidean distance matrix. My goal is to know which is the average distance between any two points.
So my guess is that it should be as simple as calculating the mean of the matrix.
However, I'm not certain if this number would reflect what I'm looking for or maybe there's a better estimator. My ultimate goal is to use this estimator for comparison between cities.
Comment: The computation of the mean is straightforward as explained in the answer. But are you sure euclidean distance as the crow flies is the most relevant metric of distance within cities?
Comment: What do you mean by 'comparison between cities'?
Comment: so, the idea was to have a measure of a 'within' (what's the average distance between points in a city) to compare between cities. That's what was not making a lot of sense back then when I asked the question
Answer: The mean distance between points $i \not = j$ expressed with matrix operations:
Let the matrix with the Euclidean distances be $D$, an $n\times n$ matrix with $i,j$-element given by
$$
  D_{ij} = \lVert x_i - x_j \rVert
$$
There are $n(n-1)/2$ pairs, but to get a simpler matrix formula we include both (equal) terms $D_{i,j}$ and $D_{j,i}$ and can write the mean as
$$
    \frac{1}{n (n-1)} \sum_i \sum_{j\not= i} D_{i,j}
$$
The formula simplifies if we include the zeros on the diagonal:
$$ \DeclareMathOperator{\ones}{\mathbb{1}}
  \frac{1}{n(n-1)} \sum_i \sum_j D_{i,j}
$$
and writing the vector of $n$ ones as $\ones$ we finally get the mean as
$$
  \frac{1}{n(n-1)} \ones^T D \ones
$$

Average distance in distance matrix


How do I require an IP range instead of 1 IP?

Question: My IP changes do a different D class, so I want to set a range:
123.123.123.xxx where the last segment can be 0-255.
Right now, Apache says:
<RequireAny>
   Require ip 127.0.0.1
   Require ip ::1
</RequireAny>

Answer: Firstly, I'm going to assume you mean Apache 2.4 despite the "apache-2.2" tag since the syntax you've posted is from 2.4.
From the Apache documentation:

ip.address is an IP address, a partial IP address, a network/netmask pair, or a
  network/nnn CIDR specification.

I assume you mean you wish to allow a /24 since Class D is Multicast addresses, and classful networking died in the 90's. To allow a /24, you can use any of the following:
Require ip 123.123.123
Require ip 188.8.131.52/255.255.255.0
Require ip 220.127.116.11/24

Personally, I find the last to be less ambiguous than the first, and easier to read than the second.
You may find this section of the documentation useful: http://httpd.apache.org/docs/2.4/howto/access.html#host
Comment: So this won't work on Apache 2.2? phpMyAdmin works on both 2.2 and 2.4 and I just checked to see what this server was running and it's 2.2
Comment: Unless something has been backported to enable it, I've never seen that syntax in 2.2 config files.
Comment: @fukawi2 - Yes, you are of course correct. For user281497: While `Require` has limited support in Apache 2.2, Apache 2.2 does not support either `Require ip` or ``. As noted in the [Overview of new features in Apache HTTP Server 2.4](http://httpd.apache.org/docs/2.4/new_features_2_4.html#module), "Advanced authorization logic may now be specified using the `Require` directive and the related container directives, such as ``." The former are among those improvements added to Apache 2.4.
Answer: In Apache 2.2 and below, you could work with:
Order deny,allow
Deny from all
Allow from 24.18    # allow access from home
Allow from 162.12   # allow access from work

in your .htaccess, directly on base level (not within any <directive>).
As of Apache 2.4 and above, here you go:
<RequireAny>
    #IPv4 range at my work
    Require ip 207.100
    #IPv4 range I usually get through my mobile provider
    Require ip 29.11
    #IPv6 from home
    Require ip 2a02:4126:2aa4::/48
</RequireAny>

(all numbers fictional, no worries ;-).
I have been using this for many years now to shield my back end folders against 99% of potential users. (Working very well, unless you are an avid blogger while traveling. If you are a gmail user: "last account activity" Link at the very bottom is a comfy way to figure out your own "IP habits").
Comment: Is it because 2a02:4126:2aa4:: = 2a02:4126:2aa4:0000:0000:0000:0000:0000, whereas 2a02:4126:2aa4::/48 matches all addresses that begin with 2a02:4126:2aa4?
Comment: I just saw this: PLease use Require ip 29.11. (with a trailing dot). Otherwise an adress like 126.96.36.199 may gain access as well (the documentation is not clear here).
Comment: What's the difference between `Require ip 2a02:4126:2aa4::/48` and `Require ip 2a02:4126:2aa4::`? Both don't produce syntax errors for me, but only the former works.
Answer: Apache's Require directive is used during the authorization phase to ensure that a user is allowed or denied access to a resource. mod_authz_host extends the authorization types with ip, host, forward-dns and local. Other authorization types may also be used but may require that additional authorization modules be loaded.
These authorization providers affect which hosts can access an area of the server. Access can be controlled by hostname, IP Address, or IP Address range.
Since v2.4.8, expressions are supported within the host require directives.
Require ip
The ip provider allows access to the server to be controlled based on the IP address of the remote client. When Require ip ip-address is specified, then the request is allowed access if the IP address matches.
A full IP address:
Require ip 10.1.2.3
Require ip 192.168.1.104 192.168.1.205

An IP address of a host allowed access
A partial IP address:
Require ip 10.1
Require ip 10 172.20 192.168.2

The first 1 to 3 bytes of an IP address, for subnet restriction.
A network/netmask pair:
Require ip 10.1.0.0/255.255.0.0

A network a.b.c.d, and a netmask w.x.y.z. For more fine-grained subnet restriction.
A network/nnn CIDR specification:
Require ip 10.1.0.0/16

Similar to the previous case, except the netmask consists of nnn high-order 1 bits.
Note that the last three examples above match exactly the same set of hosts.
IPv6 addresses and IPv6 subnets can be specified as shown below:
Require ip 2001:db8::a00:20ff:fea7:ccea
Require ip 2001:db8:1:1::a
Require ip 2001:db8:2:1::/64
Require ip 2001:db8:3::/48

Note: As the IP addresses are parsed on startup, expressions are not evaluated at request time.
Source: https://httpd.apache.org/docs/trunk/mod/mod_authz_host.html
Comment: Please don't just copy&paste other peoples work. This is called plagiarism.
Answer: Noting that you have now confirmed using Apache 2.2, Apache 2.2 does not support either Require ip or <RequireAny>. As noted in the Overview of new features in Apache HTTP Server 2.4, "Advanced authorization logic may now be specified using the Require directive and the related container directives, such as <RequireAll>." The former are among those improvements added to Apache 2.4.
To deal with this in Apache 2.2, you will probably need to do something like:
Order allow,deny
Allow from 123.123.123

which will get the whole range specified.
Answer: Note: I am leaving this here as others might benefit from it; it is not a direct answer to the question.
For example:
Require ip 192.168.100.0/22
works, while
Require ip 192.168.100.0/22 #localnetwork
fails!
Restarting httpd outputs:
Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.
So, it seems that no comments are allowed on that line.
Comment: Comments are not allowed anywhere inside a configuration line, see https://httpd.apache.org/docs/2.4/configuring.html : "Lines that begin with the hash character "#" are considered comments, and are ignored. Comments may not be included on the same line as a configuration directive. "


how to sign my own kernel module in linux?

Question: I write a simple hello world kernel module in Linux and I tried to load it to the kernel. but it was not possible because I get this error while I want to load it.
module verification failed: signature and/or required key missing - tainting kernel
I tried to find a solution for that but all of that found was about VM and not a real system.
my secure boot is disabled and I don't want to change kernel config and rebuild it.
I also tried to create a key with openssl and MOK and enroll it but in the last step that tries to sign module, I stopped because of No such file or directory error.
I can't find /scripts/sign-file in /usr/lib/linux-headers-5.11.0-16-generic
I followed the answer to this question:
https://unix.stackexchange.com/questions/560895/sign-kernel-modules
I am completely confused!
can anyone help me??
my os is ubuntu and the kernel version is 5.11.0-16
UPDATE: now I understand my module seems to be signed via command modinfo hello.ko and this is the result:
$ modinfo hello.ko
filename:       /home/###/Documents/kernel/hello.ko
description:    This is the module description.
author:         ###
license:        Dual BSD/GPL
depends:
retpoline:      Y
name:           hello
vermagic:       5.11.0-16-generic SMP mod_unload modversions
sig_id:         PKCS#7
signer:         ###
sig_key:        58:26:4E:F2:6A:5F:2F:DB:F0:21:E0:8C:79:60:E9:C8:78:38:01:3F
sig_hashalgo:   sha256
signature:      67:F2:74:BF:6A:AB:D4:AD:6C:EA:BD:35:D6:7A:9A:94:0F:C7:0F:6B:
        AD:10:18:26:D1:D9:8A:07:DD:89:36:03:D0:C9:AA:10:A1:52:71:A0:
        CF:D0:7D:C6:2E:D7:E2:B1:AF:1D:45:A4:97:13:23:23:C8:B7:99:6D:
        4A:F9:60:B7:64:D0:E4:3C:EE:74:9F:68:D2:C5:EC:C0:C9:F3:09:76:
        EF:B5:C4:46:62:36:1B:95:EC:4A:D3:4D:B7:2F:87:71:E1:D2:D7:ED:
        EE:F3:04:58:3F:F9:EA:16:4C:39:BD:B5:50:60:FC:A7:96:AF:03:74:
        F0:03:76:98:95:91:A9:5A:1B:50:17:8A:71:A2:C0:D6:B4:DD:D3:50:
        FE:2A:05:29:03:D6:E6:A0:69:F4:18:44:2B:EC:F6:41:6D:A3:E7:EF:
        10:3D:98:A8:33:21:56:0E:D6:8E:67:88:18:7F:31:DB:2E:CA:70:F7:
        7E:03:42:04:F5:99:64:BD:EE:0F:04:DA:56:50:B5:2E:7A:B7:AE:D0:
        ED:07:6B:86:89:45:38:B4:7C:FE:B9:B3:F4:5D:17:1B:6F:04:33:52:
        BE:0E:1F:D3:CA:F1:9D:17:AD:EC:A4:DC:84:25:47:73:ED:02:9E:74:
        4C:AD:25:35:2B:E4:C0:BE:15:F2:FF:99:CE:89:82:E6

but still I get error while inserting module:
$ sudo insmod hello.ko
insmod: ERROR: could not insert module hello.ko: Invalid module format

Comment: You should ask on [Unix & Linux stack exchange](https://unix.stackexchange.com), as this is not about programming, but about general software, specifically Linux.
Comment: Unless you have the private keys used to build the kernel in the first place, you can't create a signed module.  That's the whole point.  You can generate your own keys and build your own kernel and modules, but it won't be signed by Ubuntu.
Comment: `/scripts/sign-file in /usr/lib/linux-headers-5.11.0-16-generic` It's in [sources](https://github.com/torvalds/linux/blob/master/scripts/sign-file.c), not in headers. There are docs https://www.kernel.org/doc/html/v4.14/admin-guide/module-signing.html , [archlinux wiki](https://wiki.archlinux.org/index.php/Signed_kernel_modules) looks nice.
Comment: @KamilCuk yes that's right but it was in mentioned link. I tried that (in src) and my module signed (as said in UPDATE) but still can't load to kernel because of that reason
Comment: Try dmesg command.. To see the kernel log after you insert module
Comment: @Varun I did. ```module verification failed: signature and/or required key missing - tainting kernel ```
Comment: @stark so what should I do?
Comment: Build kernel with CONFIG_MODULE_SIG not set and make sure trusted boot is not enabled.
Comment: add MODULE_AUTHOR(), MODULE_LICENSE() in your kernel module.
Answer: A workaround is to build the module with that line in Makefile:
#this line fix the problem. tomrtc
CONFIG_MODULE_SIG=n


Find the middle point on an arc

Question: For an arc in 3D space with the following known variables:

$A$: start point
$B$: end point
$C$: center point
$r$: radius
vector normal to the surface of the arc

How can we calculate the coordinates of the point $D$ lying in the middle of the arc using the swept angle $\fracθ2$?
How would this angle be calculated correctly?
I have tried the following:

Calculate the $X$ direction vector as $X = C - A$.
Calculate the Y direction vector as Y = normal x X.
Get the vectors from center to start and end, $CA$ and $CB$ respectively.
Calculate swept angle as $\theta = \arccos\left(\frac{CA\cdot{CB}}{{\lvert CA\rvert}{\lvert CB\rvert}}\right)$.
$D = C + X_{dir}\cdot{r}\cdot{\cos{\frac{\theta}{2}}}+ Y_{dir}\cdot{r}\cdot{\sin{\frac{\theta}{2}}}$

This way I am sometimes getting a diametrically opposite point. The problem seems to be that the sign of the angle $\theta$ I am calculating does not respect the direction of the normal axis.
Comment: The formula I mean in previous comment: $|u \times v|=|u|\cdot |v|\cdot \sin(\theta)$ where $\theta$ is the angle between vectors $u,v.$
Comment: Most of the time you are eligible for an answer when you show what you did. What coordinate system are you using?
Comment: I thought I wouldn't clutter the question with my calculations. I will add more information.
Comment: I don't think you need the normal vector. Calculate $(B-C) \times (A-C)$ [the cross-product] and use known formulas connecting cross product with the angle swept out.
Answer: First, I would advise you to not take the arccos of that dot product. It is numerically unstable, and could even yield an error if the vectors CA and CB are parallel or anti-parallel and the floating point error falls the wrong way.
The cross product is a more stable source of the angle. Simply calculating CA x CB will yield a vector which lies is along the normal vector, whose length is tan(θ)(CA · CB)
So, we can first use the normal vector to get the angle θ:
<code>// possibly confirm normal is parallel to CA x CB
θ = atan2(normal · (CA ⅹ CB), (CA · CB))
</code>
We now need to resolve the question's ambiguity. There are two possible arcs you've specified: The short way around and the long way around.
If it is guaranteed you want the short way around, we're already done. atan2 will yeild an angle in the range (-180º, 180º], so dividing it by 2 will give you either a clockwise or a counterclockwise angle in the range (-90º, 90º] with the shortest way around (tie goes to positive angle)
If it is instead guaranteed that the provided normal vector is consistently oriented to the arc (so that the end B is clockwise from A looking down the normal, or vice versa), then you can manipulate atan2 to lie in positive range (0º, 360º] with the substitution atan2(-y, -x) + 180º
<code>θ = atan2(-normal · (CA ⅹ CB), -(CA · CB)) + 180
// possibly flip θ depending on the convention
</code>
If neither is guaranteed, I believe the problem is underspecified.
Either way, you now have a stable signed angle θ from A to B, and you can get the arc midpoint by rotating around the normal vector by θ/2 (using your calculation above, or using the Rodriguez rotation formula).
Comment: Just a note for posterity, if you have this problem without a normal specified at all, you can use the length (norm(CA x CB)) in place of (normal · (CA x CB)), then use that cross product normalize(CA x CB) as the normal to rotate around in the last step. However, if A, B and C are collinear you have a bigger ambiguity to deal with, since without a normal specified there are an infinite number of 180º arcs to choose from for midpoints.
Comment: Thank you for the insightful answer. It turns out it is the case that my input normal vector always point to the right direction, so the angles are indeed always positive. I have substituted the calculations with atan2 as per your suggestion.

Find the middle point on an arc


Creating Sticker Pack programmatically, issue with casting UICollectionViewCell as MSStickerView

Question: So, I have opted to using no storyboards in my messages extension sticker pack. The iMessage app comes with a storyboard file and a MessagesViewController.swift. I created 2 files named CollectionViewController and StickerCell. The idea is to subclass CollectionViewCell and cast it as MSStickerView and dequeue that view into my CollectionView as a "cell".
Here is the code for setting up the "StickerCell" as MSSstickerView:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let item = data[indexPath.row]
    return deQStickerCell(for: item, at: indexPath)
}

private func deQStickerCell(for sticker: MSSticker, at indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! StickerCell
    cell.stickerView.sticker = sticker
    return cell
}

and the code in my StickerCell class:
class StickerCell: UICollectionViewCell {
    var stickerView: MSStickerView!
}

I'm guessing the issue is here as I have done this successfully with storyboard and the exact code in StickerClass, except the var was an IBOutlet. So clearly something is not connecting to the CollectionView or I missed a step. In Interface Builder, I would create the CollectionViewController, give it a CollectionView, give it a CollectionViewCell, then slap a UIView on top and change it's class to MSStickerView.
How do I recreate the Interface Builder workflow programmatically!?
Answer: It's hard to know exactly what your issue is, but from what I can tell you aren't getting back a StickerCell with a subview of stickerView. What stands out different from IB is that you aren't ever initializing your stickerView. You need to add an init that will create and add the view to your cell. Something like (pseudo code):
override init(frame: CGRect) {
    super.init(frame: frame)

    self.stickerView = StickerView()
    self.contentView.addSubview(self.stickerView)
    // Set up your constraints & layout
}

Comment: Ohhhhh totally. I take for granted what IB does for me. Which is why I'm forcing myself to do things programmatically. I'll give something like this a shot.


Bulk change the order status based on a date in Woocommerce

Question: The following sql query will change order status:
update wp_posts set post_status = 'wc-completed' where post_type = 'shop_order' and post_status ='wc-processing' ;
How can I change the order status only on orders that are before a certain date?
Answer: To bulk change the order status before a date (for example before the 05 OCT 2018) using this SQL query (making always a database backup before):
UPDATE `wp_posts`
SET `post_status` = 'wc-completed'
WHERE `post_type` = 'shop_order'
AND `post_status` ='wc-processing'
AND `post_date` < '2018-10-05 00:00:00';

Tested and works
Comment: Woohoo!  24739 rows affected. (Query took 0.6414 seconds.) Outstanding, thank you.


How do i prove that Mobius transformation is continuous at its pole?

Question: Let $a,b,c,d$ be complex numbers such that $c\neq 0$ and $ad-bc\neq 0$.
Define $T(z)=\dfrac{az+b}{cz+d}, \forall z\in\mathbb{C}\setminus\left\{-\dfrac{d}{c}\right\}$.
Define $T(-\frac{d}{c})=\infty$ and $T(\infty)=\frac{a}{b}$.
This function $T:\overline{\mathbb{C}}\rightarrow \overline{\mathbb{C}}$ is called a Mobius transformation.
I have proved that $T$ is continuous on $\mathbb{C}\setminus\{-\frac{d}{c}\}$.
How do i prove that $\lim_{z\to -\frac{d}{c}} T(z) = \infty$?
Comment: Did you also prove $T$ is continuous at $\infty$?  It would seem arhythmic to omit that from this exercise. ${}\qquad{}$
Answer: It won't work if $a/b=c/d$ for reasons you can figure out.
Suppose you prove $az+b$ approaches some number in $\mathbb C$ other than $0$ as $z\to-d/c$.
Then the problem is to prove that $1/(cz+d)\to\infty$ as $z\to-d/c$.
$$
\frac{1}{cz+d} = \frac 1 c \cdot \frac{1}{z+\frac d c}. \tag 1
$$
(Maybe you can also think about what happens if $c=0$, since $c$ is in two denominators here.)
Given $R>0$, you need find $\delta>0$ such that the second fraction on the right in $(1)$ is bigger than $R$ if $|z-\frac d c |<\delta$.  Maybe $\delta=1/R$ works.


Open inbound calls redirects to another Twilio client when hang up

Question: I have two available Twilio <client> to receive inbound calls on my website (after caller enters a code) using JS Quickstart and Twilio client PHP library, these calls are recorded and registered on my database.
I've noticed when one <client> hangs up an open inbound call , this call goes to the website of the other <client> I have have 2 registers on my database instead of one.
This is an example:
<?php

//...
//Validating connection status
//$estd is the connection status I get via AJAX

if($estd=="open"){
    $call = $twilio->calls($callsid)->update(array("status" => "completed"));
    $calla = $twilio->calls($callsid)->fetch();
    $parentCall = $calla->parentCallSid; //parent call
    $calld = $twilio->calls($parentCall)->update(array("status" => "completed"));
} else if($estd=="pending"){
    $call = $twilio->calls($callsid)->update(array("status" => "completed"));
    $calla = $twilio->calls($callsid)->fetch();
    $parentCall = $calla->parentCallSid; //parent call
    $calld = $twilio->calls($parentCall)->update(array("twiml" => '<Response><Dial timeout="20" record="record-from-answer" recordingStatusCallback="https://mywebsite.com/record.php" recordingStatusCallbackEvent="in-progress completed absent"><Client><Identity>the_other_client</Identity><Parameter name="numdoc" value="user_code"/></Client></Dial></Response>'));
}

?>

How can I fix it?
I'd like your help.
Answer: I believe this could be occurring because a single incoming voice call will trigger both of your $estd if statements.
According to Twilio documentation (https://www.twilio.com/docs/voice/client/javascript/connection#status), an incoming call will first have the status pending, and then the status open. If your statuscallbackURL is set for when the status changes, you may be calling your record-keeping code more than once. Depending on how you have your SQL you may be inserting new records each time.
The way to prevent the double record is to save the resource SID for the call in your database and insert on duplicate key or update to prevent creating new records.

Alternatively, if the code snippet you are displaying is from record.php, when you make your outbound call using Twiml, you use a callbackURL to call record.php -- at which time you may be creating a new record in your database (as this call will have it's own unique SID). If you want to attach it to the current record, then you will need to create a different callbackURL for those outbound dials made from this script.
(But it is difficult from the details you have provided to know what code is being called when).


Find all possible subgroups of a cyclic group of order $n$.

Question:
Let $G$ which is a cyclic group with $n$ elements. Find:
   a) all possible subgroups
   b) all elements which generate whole group.

I know that number of subgroups is the number of total divisors of $n$. Moreover if $l|(|G|=n)$ then exist exactly one subgroup $H$ such that $|H|=l$.
However I know how to do this task when I know $n$.
For example for $n=6$ we have divisors: $1,2,3,6$ so we have $4$ supgroups.
Meanwhile I have a problem when I don't know $n$:
Let $G= \left\{ e,g,g^{2},\dots ,g^{n-1} \right\}$ then we have:
$$\langle e\rangle=\left\{ e \right\}$$
$$\langle g\rangle =\left\{ e,g,g^{2},\dots ,g^{n-1} \right\}$$
But I already have a problem with $\langle g^2\rangle $ because firstly I have: $\langle g^2\rangle =\left\{ e,g^{2},g^{4},\dots ,g^{n-1}\right\}$ but I don't know if $n=2k+1$ and this is whole $\langle g^2\rangle $ or $n=2k$ and $g^2$ is not a generator of any subgroups.

How can I do this task for every $n$?
Comment: About b). If $g$ is a generator, than any $g^k$ is a generator iff $(k, n)=1$. As a corollary, if $n$ is prime, than any non-unit element of $G$ is a generator.
Answer: If $\langle g\rangle =G$, then $\mid g^k\mid=\frac n{\operatorname {gcd}(n,k)}$.
For $b)$, using this fact we get that whenever $\operatorname {gcd}(n,k)=1$, $\langle g^k\rangle =G$.


How to print key and value in an array of array with bash script

Question: I've this script: an array of array, and a loop. Inside the loop, how can I print the key (foo) and the value (bar)???
#!/bin/bash
declare -A combo=()
combo+=(['foo']='bar')
combo+=(['hello']='world')
for window in ${combo[@]};
do
    echo ???
    echo ???
done
exit

expected output:
key: foo   value: bar
key: hello value:world

I'll read this bash manual asap!!
Comment: @JID While you are correct that's only because they didn't declare the array with `declare -A`. If they did this would do what they expected. So a more constructive version of your comment here (and on the posted answer) would likely have been more useful.
Comment: This won't work how you think it will, `combo` will have one array element that is `barworld`
Comment: Exactly, ... can you help to define array, ed loop through it?
Comment: What exactly is it you are trying to do? Post expected output. Are you trying to make an array inside another ?
Comment: Yes, ... I need a key, and its value. Is this the correct way to define it?
Comment: @EtanReisner Yeah probably, i was going to suggest that after working out exactly what OP wanted as i wasn't 100% from the question. As for the answer it is wrong, they have literally just explained how to access a normal array.
Comment: It is "wrong" in as much as the OP is wrong (re: `-A`) and a single character fixes the other issue. Again a more constructive comment would have been useful (even just to explain why it was wrong).
Comment: It is OK for OP to be wrong though as they are asking a question. That wrong comment was more of a sign to others.They posted an answer as though it is correct when if they had tested it they would have seen it was intrinsically wrong. And adding a `declare -A` would not have fixed it as they also didn't use the indirection `!` on the array.
Comment: **note:** the when assigning to associated arrays there is never a need to quote `key` in e.g. `array+=( [key]='some value with spaces' )`. **key** cannot contain more than 1 word unless `IFS` is changed. (that would defeat the purpose of quoting `key` to begin with...)
Answer: Your script is almost correct. As is v.coder's answer.
You need to declare your array as an associative one before you append items to it with string keys.
declare -A combo

Then you need to iterate over the keys of the array (${!combo[@]}") instead of the values (${combo[@]}").
Then the rest of v.coder's answer works just fine.
#!/bin/bash
declare -A combo
combo+=(['foo']='bar')
combo+=(['hello']='world')
for window in "${!combo[@]}"
do
    echo "${window}" # foo
    echo "${combo[${window}]}" # bar
done

Comment: Associative arrays don't have an order.
Comment: There isn't a "beginning" or an "end" to an associative array. Not in the way you mean. Insertion order doesn't matter.
Comment: Could you also tell me why first element added is the last printed? I got "hello world" and then "foo bar". Is += the wrong way?
Comment: Nice =(. But, ... could you tell me how to iterate the for from the end to the beginning?


Calculate: $\lim_{x\to 0}{\frac{\tan x-\sin x}{x^3}}$

Question:
Calculate: $\lim{\frac{\tan x-\sin x}{x^3}}$ as $x\to 0$

I have solved it using a way that gives a wrong answer but I can't figure out why:
$$\lim{\frac{\tan x-\sin x}{x^3}}\\
=\lim{\frac{\tan x}{x^3}-\lim\frac{\sin x}{x^3}}\\
=\lim{\frac{1}{x^2}}\cdot\lim{\frac{\tan x}{x}-\frac{1}{x^2}}\cdot\lim{\frac{\sin x}{x}}\\
=\lim{\frac{1}{x^2}}-\lim{\frac{1}{x^2}}
=0$$
The answer using the standard method gives $\frac{1}{2}$.
It would be great if someone could explain to me why this method is wrong.
Comment: $\lim \frac{1}{x^2} - \lim \frac{1}{x^2}$ is not $0$, it's an undetermined form (you're calculating $+\infty - \infty$)
Comment: See http://math.stackexchange.com/questions/2116279/limit-lim-x-to-0-frac-tan-3-x-sin-3-xx5-without-lh%c3%b4pitals-rule
Answer: 1) With l'Hospital:
$$\lim_{x\to0}\frac{\tan x-\sin x}{x^3}\stackrel{\text{l'H}}=\lim_{x\to0}\frac{\frac1{\cos^2x}-\cos x}{3x^2}\stackrel{\text{l'H}}=\lim_{x\to0}\frac{\frac{2\sin x}{\cos^3x}+\sin x}{6x}=$$
$$=\lim_{x\to0}\frac16\frac{\sin x}x\left(\frac2{\cos^3x}+1\right)=\frac16\cdot1\cdot(2+1)=\frac12$$
2) Without l'Hospital:
$$\lim_{x\to0}\frac{\tan x-\sin x}{x^3}=\lim_{x\to0}\frac{\sin x}x\frac{1-\cos x}{x^2}\frac1{\cos x}=1\cdot\frac12\cdot1=\frac12$$
Where we used
$$\frac{1-\cos x}{x^2}=\frac{\sin^2x}{(1+\cos x)x^2}=\frac1{1+\cos x}\left(\frac {\sin x}x\right)^2\xrightarrow[x\to0]{}\frac12\cdot1^2=\frac12$$
Answer: $\frac{\tan{x}-\sin{x}}{x^3}=\frac{2\sin{x}\sin^2\frac{x}{2}}{x^3\cos{x}}\rightarrow2\cdot\left(\frac{1}{2}\right)^2=\frac{1}{2}$


Graphing the translated trig function $y = 2\cos(3(x - 1)) + 4$

Question: So for the trig function
$$
y=2\cos(3(x-1))+4
$$
I'm not sure how to draw the graph with a shift of $1$ to the right, would it be preferable to sketch it in radians? Also am I supposed to expand the $3(x-1)$ portion of the function?
Comment: This might help illustrate whats going on http://www.regentsprep.org/regents/math/algtrig/att7/phaseshift.htm
Answer: The function $f(x) = 2\cos[3(x - 1)] + 4$ has the form
$$f(x) = A\cos[B(x - C)] + D$$
where $|A|$ is the amplitude, $|B|$ is the frequency, $C$ is the horizontal shift, $D$ is the vertical shift and $2\pi/|B|$ is the period.  In our example, $A = 2$, $B = 3$, $C = 1$, and $D = 4$.  Hence, our final graph will have amplitude $2$, frequency $3$, period $2\pi/3$, and will be shifted one unit to the right and four units upwards.
The graph of $f(x) = \cos x$ is shown below.

The function $f(x) = \cos x$ has amplitude $1$ and period $2\pi$.
The transformation $f(x) \to 2f(x)$ that sends $\cos x \to 2\cos x$ doubles the amplitude of the function, as shown below. The graph of $y = 2\cos x$ has amplitude $2$ and period $2\pi$.

The transformation $2f(x) \to 2f(3x)$ that sends $2\cos x \to 2\cos(3x)$ triples the frequency of the preceding graph, meaning that three cycles of the graph are completed in each period of the preceding graph, as shown below.
Notice that the graph of $y = 2\cos(3x)$ has amplitude $2$ and period $2\pi/3$.

The transformation $2f(3x) \to 2f(3(x - 1))$ that sends $2\cos(3x) \to 2\cos[3(x - 1)]$ shifts the graph of $y = 2\cos(3x)$ one unit to the right, as shown below. Notice that the graph of $y = 2\cos[3(x - 1)]$ has amplitude $2$, period $2\pi/3$, and a horizontal shift of $1$.

Finally, the transformation $2f(3(x - 1)) \to 2f(3(x - 1)) + 4$ that sends $2\cos[3(x - 1)]  \to 2\cos[3(x - 1)] + 4$ shifts the graph of $y = 2\cos[3(x - 1)]$ up by four units, as shown in the graph below.  Notice that the graph of $y = 2\cos[3(x - 1)] + 4$ has amplitude $2$, period $2\pi/3$, a horizontal shift of $1$, and a vertical shift of $4$.
Answer: Think of it in multiple phases. The way I would do this is to consider the simplified expression
$$
y = 2 \cos(3x - 3) + 4
$$
Analysing this helps if you know how to analyse the general form of
$$
z(t) = A \cos(\omega t + \phi)
$$
Here, notice that the maximum amplitude for $z$ is $A$, and minimum is $-A$.
When $t = 0$, $z(t = 0)  = A \cos(\phi)$. Here, $\phi$ is called as the phase of the function, and it tells you by how much the function is shifted from the actual value of $\cos$ at $0$.
The $\omega$ is called as the angular velocity, and it tells you "how fast" the function $z(t)$ repeats.
We know that $\cos$ has a period of $2 \pi$. That is $$\cos (2 \pi + t) = \cos (t )$$
Similarly, the general period for out function $z(t)$ is $T$ such that
$$
z(t + T) = z(t) \\
A \cos (\omega(t + T) + \phi) = A \cos (\omega t + \phi) \\
\cos (\omega(t + T) + \phi) - \cos (\omega t + \phi) = 0
$$
Since the period of $\cos$ is $2 \pi$,
$$
\omega(t + T) + \phi - (\omega t + \phi) = 2\pi \\
\omega t + \omega T + \phi - \omega t - \phi = 2 \pi \\
\omega T = 2 \pi \\
T = \frac{2 \pi}{\omega}
$$
Usually, $T$ is called as the time period of $z(t)$ since it tells you after how long the function repeats.

Analysing the function

The given function is
$$
y = 2 \cos(3x - 3) + 4
$$
By comparing with
$$
z = A \cos(\omega t + \phi)
$$
we know that $A = 2$, $\omega = 3$, $\phi = -3$.
So, the function has a maximum amplitude $2$, It repeats itself after every $\frac{2 \pi}{\omega} = \frac{2 \pi}{3}$, and is shifted to the left by $3$.
The function $y(x)$ also has an extra factor $+4$ which makes the entire function shift by $4$ units upward in the $y$-axis.
Comment: Notice that $\omega t + \phi = 0$ when $t = -\frac{\phi}{\omega}$.  In the case of the function $y = 2\cos[3(x - 1)] + 4$, the argument vanishes when $x = 1$, so the horizontal shift is one unit to the right.


html form using javaScript to call out some function

Question: I'm a beginner and I'm try to set up a form. I have written the html/css code. What I wanted to do is to click on a level of study such as Bachelors, I want all the courses under bachelors to display in the second box (choose course) while hiding the rest of the courses in the box.

label {
  font-family: sans-serif;
  font-size: 1rem;
  padding-right: 10px;
}

select {
  font-size: .9rem;
  padding: 2px 5px;
}

This is a form

Online Application:

                <form id="form1" action="#">
                    Choose levels of study:

                    <select id="level-select">
                        <option value="">--Please choose an option--</option>
                        <option value="bachelor">Bachelors</option>
                        <option value="postgraduates">Postgraduates</option>
                        <option value="phd">PhD</option>

                    </select>

                </form>

                <form id="form2" action="#">
                    Choose course:

                    <select id="cour">
                        <optgroup label="Bachelors">
                            <option>Microbiology</option>
                            <option>chemistry</option>
                            <option>physics</option>
                        </optgroup>
                        <optgroup label="Postgraduates">
                            <option>computer</option>
                            <option>biology</option>
                            <option>accounting</option>
                        </optgroup>

                        <optgroup label="PhD">
                            <option>business</option>
                            <option>fisheries</option>
                            <option>agric</option>
                        </optgroup>
                    </select>

                </form>
Answer: Just add onClick event in <option> tag?
<option onClick="myFunction()">Microbiology</option>

```

Answer: Add a onchange event to the select field, and push the value to a function like;
<select id="level-select" onchange="setLevel(this.value)">

Hide all option groups in css;
#cour optgroup {
    display:none;
}

Give all option groups a unique ID containing the value of the first select, like;
<optgroup label="Bachelors" id="course_bachelor">

And now the function for the onchange event could be something like this;
    function setLevel (val) {
        var elements = document.getElementsByTagName('optgroup');

        // Loop through all elements and check if they are hidden or shown
        for(var i=0; i < elements.length; i++) {
            if (elements[i].id === 'course_' + val) {
                elements[i].style.display = 'block';
            } else {
                elements[i].style.display = 'none';
            }
        }
    }

Answer:

label {
  font-family: sans-serif;
  font-size: 1rem;
  padding-right: 10px;
}

select {
  font-size: .9rem;
  padding: 2px 5px;
}

This is a form

Online Application:

                <form id="form1" action="#">
                    Choose levels of study:

                    <select id="level-select">
                        <option value="">--Please choose an option--</option>
                        <option value="bachelor">Bachelors</option>
                        <option value="postgraduates">Postgraduates</option>
                        <option value="phd">PhD</option>

                    </select>

                    Choose course:

                    <select id="cour">

                    </select>

                </form>

var select = document.getElementById("level-select");
select.onchange(() => {
if(select.value == 'bachelor') {
document.getElementById("cour").value == "<optgroup label="Bachelors">
                        <option>Microbiology</option>
                        <option>chemistry</option>
                        <option>physics</option>
                    </optgroup>"
}

})

Do this for all the conditions.
Comment: I think it's bad practice to inject html with javascript, because it makes the code unreadable most of the time. Also you can introduce xss vulnerabilities.
Comment: Then you should use some simple styling like collapse in bootstrap. That will also help.
Comment: Indeed! I think it's better to use a framework than vanilla stuff anyways, because the code is more structured that way and most of the boring code is already done. ;)
Answer: Here, I've come up with a simple solution to this. I've changed your html a little bit. I've set the same values as their optgroup's label so that we can choose the specific optgroup for being shown. So the solution is simple:

Hide all the options of the second box.
Show the one by courses.querySelector('[label="' + value + '"]'); this, where value is your first box's selected value.

Have a look at the code snippet below:

function getLevels() {
    var value = document.getElementById("level-select").value;

    if (value) {
        var courses = document.querySelector("#cour");
        var all_options = courses.querySelectorAll('optgroup');
        var show_courses = courses.querySelector('[label="' + value + '"]');

        all_options.forEach(function (element) {
            element.style.display = "none";
        });

        show_courses.style.display = "block";
    }

}

This is a form

Online Application:

<form id="form1" action="#">
    Choose levels of study:

    <select id="level-select" onchange="getLevels()">
        <option value="">--Please choose an option--</option>
        <option value="Bachelors">Bachelors</option>
        <option value="Postgraduates">Postgraduates</option>
        <option value="PhD">PhD</option>
    </select>

</form>

<form id="form2" action="#">
    Choose course:

    <select id="cour">
        <option selected>--Choose Course--</option>
        <optgroup label="Bachelors">
            <option>Microbiology</option>
            <option>chemistry</option>
            <option>physics</option>
        </optgroup>
        <optgroup label="Postgraduates">
            <option>computer</option>
            <option>biology</option>
            <option>accounting</option>
        </optgroup>

        <optgroup label="PhD">
            <option>business</option>
            <option>fisheries</option>
            <option>agric</option>
        </optgroup>
    </select>

</form>
Comment: Thumb Up...exactly what I needed
Comment: @Ayplux, My pleasure :)
Answer: You'll need to use some Javascript to do this. Here's one solution that could work for you.
I've updated some of your html names (first dropdown values to exactly match the 'optgroup' labels in your second dropdown). Also added some CSS to have the options for the courses dropdown to not show until you've selected a valid option, which prevents the user from, say, going back to change the first dropdown value while the second dropdown value stays the same. Always 'idiot-proof' your UI:

//grab both dropdowns and store in variable
var levelSelectDropdown = document.querySelector('#level-select');
var coursesDropdown = document.querySelector('#cour');

//create an on 'change' event for first dropdown
levelSelectDropdown.addEventListener('change', levelDropdownChange);

function levelDropdownChange(e){
  var selectedLevelOfStudy = e.target.value;
  var coursesGroups = coursesDropdown.querySelectorAll('optgroup');

  //this basically hides the 'default' empty option that's auto-selected
  //by default
  coursesDropdown.querySelector('option[value="default"]').style.display = 'none';

  //loop through all 'optgroup' items in second dropdown (coursesGroups)
  coursesGroups.forEach(function(element){
    //default course dropdown to first element (this essentially resets
    //the course dropdown each time level of study dropdown is changed
    coursesDropdown.selectedIndex = 0;
    //make sure all optgroups are hidden
    element.style.display = 'none';
    //only display optgroup whose label matches the value selected
    //from first dropdown
    if(element.getAttribute('label') == selectedLevelOfStudy){
      element.style.display = 'block';
    }
  })
}
label {
  font-family: sans-serif;
  font-size: 1rem;
  padding-right: 10px;
}

select {
  font-size: .9rem;
  padding: 2px 5px;
}

#cour optgroup {
  display:none;
}

This is a form

Online Application:

  <form id="form1" action="#">
    Choose levels of study:
    <select id="level-select">
      <option value="">--Please choose an option--</option>
      <option value="bachelors">Bachelors</option>
      <option value="postgraduates">Postgraduates</option>
      <option value="phd">PhD</option>
    </select>
  </form>

  <form id="form2" action="#">
    Choose course:
    <select id="cour">
      <option value="default"></option>
      <optgroup label="bachelors">
        <option>Microbiology</option>
        <option>chemistry</option>
        <option>physics</option>
      </optgroup>
      <optgroup label="postgraduates">
        <option>computer</option>
        <option>biology</option>
        <option>accounting</option>
      </optgroup>
      <optgroup label="phd">
        <option>business</option>
        <option>fisheries</option>
        <option>agric</option>
      </optgroup>
    </select>
  </form>
Answer:

label {
  font-family: sans-serif;
  font-size: 1rem;
  padding-right: 10px;
}

select {
  font-size: .9rem;
  padding: 2px 5px;
}

This is a form

Online Application:

                <form id="form1" action="#">

                    Choose levels of study:

                    <select id="level-select" onchange="onLevelofStudyChange()">
                        <option value="">--Please choose an option--</option>
                        <option value="bachelor">Bachelors</option>
                        <option value="postgraduates">Postgraduates</option>
                        <option value="phd">PhD</option>

                    </select>

                </form>

                <form id="form2" action="#">
                    Choose course:

                    <select id="cour">
                        <option>--Please Choose course--</option>
                        <optgroup label="bachelor" style="display:none">
                            <option>Microbiology</option>
                            <option>chemistry</option>
                            <option>physics</option>
                        </optgroup>
                        <optgroup label="postgraduates" style="display:none">
                            <option>computer</option>
                            <option>biology</option>
                            <option>accounting</option>
                        </optgroup>

                        <optgroup label="phd" style="display:none">
                            <option>business</option>
                            <option>fisheries</option>
                            <option>agric</option>
                        </optgroup>
                    </select>

                </form>

Try this, it should work also note I have changed Optgroup label inorder to match the value of first dropdown


Showing that $C^1([0,1])$ space with the norm $||f||^2=\int_{0}^{1}|f|^2+\int_0^{1}|f'|^2$ is not a Banach Space

Question: I am given the $C^1([0,1])$ space containing $f$-s such that $f,f'\in C[0,1]$, with the norm $||f||^2=\int_{0}^{1}|f|^2+\int_0^{1}|f'|^2$ and asked to show that it is not a Banach Space.
What I am not so sure about is how; do I need to find $f_n$ such that $\int_0^{1}|f_n'|^2$ is infinite, or should I rather find $f'_n$ such that $\lim_{n\to \infty}f'n\notin C[0,1]$, or is any of the two will be sufficient? I am having trouble to find ANY Cauchy sequence of functions, especially the conditioned ones. Should I start looking for derivatives sequence and integrate them?
Comment: Can you find continuous $g_n$ which converges in $L^2$ to some diccontinuous function? If yes, you can just integrate $f_n = \int_0^x g_n$
Comment: The idea should be to try to find a Cauchy sequence in this norm that is not convergent. In the case where you have the space of continuous functions with the norm of $L^2$ just consider a sequence that is equal to $1$ from $0$ to $1/2$, linear between $1/2$ and $1/2+1/n$ and $1$ from $1/2+1/n$ to $1$ so it's continuous, maybe it's similar in this case.
Comment: Thank you! I'll get right to it and attempt it
Answer: If you have a linear space $X$ and two norms  $||\cdot ||_1 ,||\cdot ||_2 $ on $X$ such that are comparable i.e. there exist $C_1>0 $ such that $$\forall_{x\in X} ||x||_1 \leq C_1 ||x||_2 $$
or
there exist $C_2>0 $ such that $$\forall_{x\in X} ||x||_2 \leq C_2 ||x||_1 $$
but not equivalent then only on of these two norms can be complete.
To see this assume conversly that $(X, ||\cdot ||_1 ) $ and $(X, ||\cdot||_2 )$ are Banach spaces. Then the one of the itentity maps $$I_1 : (X, ||\cdot ||_1 )\to (X, ||\cdot||_2 )$$ or $$I_2 : (X, ||\cdot ||_2 )\to (X, ||\cdot||_1 )$$
is continous and hence by Banach inverse operator theorem it is a linear homeomorphism and therefore the norms are equivalent which gives contradiction.
It is well known that the norm $||\cdot ||^1_{\infty}: C^1[a,b]\to\mathbb{R},$ $$||f||^1_{\infty}=\sup_{x\in [a,b]} |f(x)| +\sup_{x\in [a,b]} |f'(x)| $$ is complete. So it is enough to show that $||\cdot ||$ is not eqivalent to $||\cdot ||_{\infty }^1 .$
To prove this take $f_n (x) = \frac{x^n}{n} ,$ then $f_n ' (x) =x^{n-1} $ for $x\in [0,1].$ Therefore $$||f_n ||^2=\frac{1}{2n^3 } +\frac{1}{2n} \to 0$$
but $$||f_n ||^1_{\infty } =1+\frac{1}{n} \geq 1$$
so these norms cannot be equivelent , but always $$||f||\leq \sqrt{2} ||f||^1_{\infty} $$ so the norm $||\cdot ||$ coannot be complete.


Preventing dupliate form submission.

Question: I have a form in my jsp file of the eclipse.
the form gets values and inserts them into my database.
I entered the values and pressed the submit button, so the values were inserted into my database.
the problem is: if I refresh the page, the previous values are inserted into my database again, although the inputs are empty.
<code>String name = request.getParameter("name");
</code>
so after the refreshing, the name gets the last value that was inserted.
how can I fix it?
Comment: Use the post-redirect-get pattern?
Comment: @DaveNewton,  thank you!
I found this: http://balusc.blogspot.co.il/2007/03/post-redirect-get-pattern.html
there is a code. where should I save it? in my servlet.java file?

"Activate this phaselistener by adding the following lines to the faces-config.xml", but I don't have this file in my project :/
Comment: Are you using JSF? If not, you shouldn't have one. All PRG means is that after you post you redirect to another page; it's not complicated.
Comment: so I have to make two pages that have the same code (the same form), and when the user presses the submit button from first page, submit it and move the user to the second page..
in the second page, if he presses the submit button, submit it and move him to the first page. right? @DaveNewton
Comment: I don't really know; why would you post to a servlet and show the same form again? When you submit, if it's successful, redirect to a new page. If it's the same form, then redirect to the servlet (or the JSP if you're hitting them directly, but ew) that shows the form.
Comment: possible duplicate of [Submit a form only once; don't submit when page is refreshed](http://stackoverflow.com/questions/9269119/submit-a-form-only-once-dont-submit-when-page-is-refreshed)
Answer: You should use the POST method for HTTP requests that perform an action, and GET for those that only retrieve data. Respond to the POST request by redirecting to a resource that would be requested with GET. That way, the form won't get resubmitted.

Preventing dupliate form submission.


Cannot find a symbol error in java when compiling from command prompt

Question: Hi I have created two Java file under a directory called Utility with as follow:

FileName.java

public class FileName {
  private String name;
  public FileName (String name) {
      //some code
  }
  String getName() {
      return name;
  }
}

FileNameReader.java

public class FileNameReader {

  public static void main(String[] args) throws IOException {
      FileName obj = new FileName("testfile.txt");
  }

}

Now, when i am comipling throw command prompt, compiler giving me error saying cannot file symbol at FileName obj = new FileName(); this line
Comment: Don't fix your code afterwards because it completely changes the context of the question. Right now, there shouldn't be any compiler error anymore, except for the missing import statement.
Comment: @QBrute, I've deleted my answer because it does not make sense anymore
Answer: Here:
public SearchFile(String name) {

That would be the constructor of a class called SearchFile.
But your class is named FileName; so you have have to rename everything (class and file name) to SearchFile; or you change the ctor to say public FileName(String name) instead.
Beyond that: that class only has a constructor taking a string argument. But your other class goes for new FileName() without providing an argument. That will not work either.
But the real answer here: such "subtle" details matter. You have to pay close attention to each and any line of code that you write down. And: you run the compiler immediately after you have "finished" something of which you think it should compile. You don't create 2, 3 files with 10, 20, 50 lines of code to then find out that you have a bunch of problems in each file!
Comment: Probably you have many different errors. Go file by file, start with those that don't depend on others.
Answer: You have to problems in your FileNameReader class:

You need to import the IOException by adding
import java.io.IOException;

You have created an explicit constructor for FileName with a String argument, so the implicit default constructor is no longer visible. You need to provide that String when creating a new instance:
FileName obj = new FileName("someString");

This FileNameReader.java compiles:
import java.io.IOException;

public class FileNameReader {

  public static void main(String[] args) throws IOException {
      FileName obj = new FileName("someString");
  }

}


Avaliar código de jogo-da-velha

Question: Eu estou programando há um tempo e gostaria que avaliassem o meu código em C.
É um jogo-da-velha usando uma estrutura de dados circular.
Meu código está aqui:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/*
 *      rows
 *
 * 7   = 000 000 111
 * 56  = 000 111 000
 * 448 = 111 000 000
 *
 *     columns
 *
 * 73  = 001 001 001
 * 146 = 010 010 010
 * 292 = 100 100 100
 *
 *    diagonals
 *
 * 84  = 001 010 100
 * 273 = 100 010 001
 *
 */
int win_code[8] = {7,56,448, 73,146,292, 84,273};

struct _Player{
    int    cod;
    char   symbol;
    struct _Player *next;
};

typedef struct _Player* Player;
Player player;

char board[9]="         ";

//after add on board: player->cod+=pow(2,index);
int add_board(int index);

// check_win()==false: player=player->next;
int check_win();

void print_board();

int main(){
    //Create player 1
    player                  = (Player) malloc(sizeof(Player));

    //player 1 variables
    player->symbol          = 'X';
    player->cod             = 0;

    //Create player 2
    //after player 1 is player 2
    player->next            = (Player) malloc(sizeof(Player));

    //player 2 variables
    player->next->symbol    = 'O';
    player->next->cod       = 0;

    //after player 2 is player 1
    player->next->next      = player;

    /*  one struct control two players.
         _________________|struct _Player*|_________________
        |                                                   |
        |                player=player->next;               |
        |            ___________________________            |
        |           |                           |           |
        |    _______|_______             ______\ /______    |
        |   |               |           |               |   |
        |   |       X       |           |       O       |   |
        |   |_______________|           |_______________|   |
        |          / \                          |           |
        |           |___________________________|           |
        |                                                   |
        |                 player=player->next;              |
        |___________________________________________________|
    */

    int index, turn=1;

    do{
        print_board();
        do{
            printf("Enter a number from 1 to 9 (Valid).\n");
            scanf("%d",&index);
            fflush(stdin);
        //correct range? try add on board.
        }while((index>=1||index<=9)&&!add_board(index));
    }while(!check_win()&&turn++<9);
    return 0;
}

int add_board(int index){
    index--;
    //board is empty.
    if(board[index]==' '){
        //add on board.
        board[index]=player->symbol;
        /*
               |   |
            2^0|2^1|2^2
            ---|---|---
            2^3|2^4|2^5
            ---|---|---
            2^6|2^7|2^8
               |   |
        */
        player->cod+=pow(2,index);
        return 1;
    }
    return 0;
}

int check_win(){
    int x;
    for(x=0;x<9;x++){
        /*
            Example check:
                X| |O
                O|X|   player X cod = 337 = 101010001
                X|O|X
            player->cod:    101010001
                                     &
            win_code[8]:    100010001
                            ---------
                            100010001 == win_code[8]
        */
        if((player->cod&win_code[x])==win_code[x]){
            print_board();
            printf("\n\t   Player: %c Win!\n\n",player->symbol);
            return 1;
        }
    }
    //player did not win, next player.
    player=player->next;
    return 0;
}

void print_board(){
    system("cls");
    printf("\n\n\t   Tic Tac Toe\n\n");
    printf("\t     |     |     \n");
    printf("\t  %c  |  %c  |  %c  \n",board[0],board[1],board[2]);
    printf("\t_____|_____|_____\n");
    printf("\t     |     |     \n");
    printf("\t  %c  |  %c  |  %c  \n",board[3],board[4],board[5]);
    printf("\t_____|_____|_____\n");
    printf("\t     |     |     \n");
    printf("\t  %c  |  %c  |  %c  \n",board[6],board[7],board[8]);
    printf("\t     |     |     \n");
    printf("\n");
}

Comment: Você acumulou 4 votos negativos e 4 votos de fechamento na pergunta (com 5 ela é fechada) pelo seguinte motivo: Não estava em português e não continha o código na pergunta. Resolvi esses dois problemas para você.
Answer:
(index>=1||index<=9)&&!add_board(index) deveria ser index < 1 || index > 9 || !add_board(index).
player->cod+=pow(2,index); pode ser reescrito como player->cod |= 1 << index;. Isso também elimina a necessidade de usar-se math.h.
Antes do return 0; do main, coloque um free(player->next); free(player);. Não é bom você alocar memória e não desalocar.
Ao invés de int x; for(x=0;x<9;x++){, use for (int x = 0; x < 8; x++) {. Note que as posições do seu array vão de 0 a 7, então o <9 está errado.
Eu colocaria um print_board() dentro do do-while externo do main, logo após o final do do-while interno. Com isso, o print_board() dentro de check_win() pode ser retirado.

Avaliar código de jogo-da-velha


Redirect To Another Page and Hide/Show DIV using a Button

Question: I have two HTML files one is called index.html and the other one is called main.html. I have a button on index.html that when clicked it should redirect to main.html and show a hidden div there, using jquery. how do I achieve that?
Answer: The button should be a  hyperlink that points to another html page.
Then, use JS to show the hidden div "document.getElemenyById("myDiv").style.visibility="visible";" when the page loads.
How to create a hyperlink:
https://www.w3schools.com/html/html_links.asp
How to create an "onload" function:
https://www.w3schools.com/jsref/event_onload.asp
Answer: Yes, it's possible, granted that the two pages are on the same domain.
On index.html, add an event listener for click on the button. On click, set a value (say, 'show') to a key (say 'show-div') in localStorage.
On main.html, read the value from localStorage via localStorage.getItem('show-div'). If the key exists and the value is show-div, you can select the div and show it.
Here's an example on CodeSandbox:
Answer: You could add a query parameter to the link to main.html, such as:
Go to main

Then on main.html you add a onload check to show that div if the query parameter is set:
$(function() {
  if (location.search.includes('showdiv=true') {
    $('#divName').show();
  }
});


Sql query for sum(field) with order by anotherfield and limit

Question: I am having the below table name 'banking'
+------------------------------+
|    id | amount | created     |
+------------------------------+
| 1 | 10 | 2018-01-18 00:10:00 |
| 2 | 20 | 2018-01-18 00:50:00 |
| 3 | 30 | 2018-01-18 00:20:00 |
| 4 | 40 | 2018-01-18 00:30:00 |
+------------------------------+

and I need an output as 60
I have tried this query
SELECT sum(amount)
  FROM banking
 WHERE created >= '2018-01-18 00:00:00'
   AND created < '2018-01-18 18:01:35'
 GROUP
    BY created
 ORDER
    BY created DESC LIMIT 2;

but I get an out put as
+---------+
|   | sum |
+---------+
| 1 | 20  |
| 2 | 40  |
+---------+

how do I get singlescalar output as 60 (the sum of 40+20)
Comment: Tag properly!!!!!  MySQL <> SQL Server <> PosgresSQL.  Which one are you using?????
Comment: How will you get 60? I see that all your records qualify as per your where clause - `created >= '2018-01-18 00:00:00' AND created < '2018-01-18 18:01:35'`
Comment: yes all my records qualified but I need to limit the sum by 2 so that i expect the result as 60
Comment: Got it. Check the answer below.
Comment: I don't understand what you're trying to do. The LIMIT seems very arbitrary.
Comment: I am trying to get only 2 result by order desc a created filed in four results
Comment: How is accepted answer is different from what I answered below? Why all the remaining answers have been downvoted? This is SO, not FB. Not accepting the answers due to lack of clarity is fine but who gives the privilege to downvote the correct answers?
Comment: @YusufHassan The accepted answer differs from the other answers provided. The other answers are incorrect.
Comment: @Strawberry I can't figure out how my solution is wrong. The answer is still un-edited and with a SDL Fiddle link attached for verification.
Comment: @YusufHassan OK, maybe not wrong. Just redundant. And if there was more than one entry created at the same time, then it would be wrong. http://sqlfiddle.com/#!9/8ea4f4/1
Answer: This should suffice:
select sum(amount) from
(SELECT sum(amount) amount FROM banking
WHERE created >= '2018-01-18 00:00:00' AND created < '2018-01-18 18:01:35'
GROUP BY created ORDER BY created DESC LIMIT 2)sum_amount;

Check the SQL Fiddle


Context in Drupal 7

Question: When I install the context module in Drupal 7, it works but does not display all the options for reactions. So I created my context, but was not able to built it like I wanted because the "Block" reaction was unavailable. I had read that clearing the cache will bring this option up, so I cleared the cache, but now my contexts stopped being interactive.
Behavior happening:

Select a condition/reaction from contexts and no options appear. I cannot input any information or select any options.

Expected behavior:

Select a condition/reaction from contexts and options appear (if I select views, I should see various views appear. If I select path, I should be able to input a path).

What can I do to fix this? It does not appear to be on the Context bug list.
Comment: What options is it showing? What options are you expecting and not seeing? Also even context has add ons which apply additional reactions (for example http://drupal.org/project/context_addassets)
Comment: What I expect: Select an action (say Views) and a series of options appear (List of views available to the context module). What actually happens: I select an action and nothing appears. The same thing is true with reactions: I select Blocks and no list of blocks appear. Does this help to clarify?
Comment: Which version [of context / context_ui] are you using?
Comment: I am currently using the most up-to-date recommended build. -> 7.x-3.0-beta4
Comment: I recall this happening a long time ago, and think it was due to a javascript conflict. Sorry I can't offer more information (it's long since solved), but it's a place to start looking. Disable any modules that add JS, one by one, and see if it solves the issue.
Comment: Thanks! I will look into it. If it is a js problem, then I think I know what might be causing it... I will post the solution if I get it to work.
Answer: Got the same problem just a few days ago. And it was not contained only to context. The usual drag and drop behaviour for rearranging fields for example also was not working. I only got weights. Everything using javascript was broken. It would seem something is messing up the jquery. Perhaps drupal loads a javascript that needs jquery before loading jquery?
The problem showed up after installing BeautyTips and CalendarTips that use jquery to create pop-up tips. Even after unistalling them didn't change the situation.
Then I enabled the js aggregation from the admin>config>development>performance menu and everything works. Perhaps you could try the following:

Enable/Disable the js aggregation
Forcibly delete the contents of sites>default>files>js so drupal will have to regenerate them
Clear your caches
Keep firebug open to the script tab and watch if you get any errors.

Good luck
Comment: This helped me resolve the problem. Thank you so much!

Context in Drupal 7


Templating. Check if entity is comment or node?

Question: I'm modifying a template file for an Advanced Forum sub theme. AF uses a single template to theme both nodes AND comments with the same markup. I need to add a php check inside the node template to see if the current entity is a node or a comment, then print some flags based on the result.
I don't think there is a straight forward $entity_type variable to check, so how would I go about writing this?
Answer: Assuming this is for Drupal 7, there isn't an official way to do this, unfortunately. See core issue: https://www.drupal.org/node/1042822
One possible workaround is to check if the entity has some known fields that you are aware of. This obviously wouldn't be a generalized solution - but might work for you.
Comment: This was successful, thanks! Used `if  (isset($body)):` for the node and `if (isset($comment_body)):` for the comment.


Making sense of the concept of coordinates of a vector with respect to some basis

Question: Relevant definition:

If $B = \{v_1, v_2,\ldots, v_n\}$ is a basis for $\mathbb R^n$, and $v = a_1v_1, a_2v_2,\ldots, a_nv_n$, then the uniquely defined scalars $a_i$ are called the coordinates of the vector $v$ relative to the
  basis $B$.

I reworded the example in my book in my own words however awkward, inelegant and ugly they might be. Does what you see below make sense to you?
Let $(x, y, z)$ be a vector in $\mathbb R^3$. Since $xe_1 + ye_2 + ze_3 = (x, y, z)$, we have that $(x, y, z)$ is the coordinate vector of $(x, y, z)$ with respect to the standard basis.
Let $(x, y, z)$ be a vector in $\mathbb R^3$. If $a(2, 1, 1) + b(1, 7, 7) + c(4, -1, 0) = (x, y, z)$, then $(a, b, c) = (z + \frac {7}{13}(x - 6z + 4y, -\frac{1}{13}(x - 6z + 4y), z - y)$ is the coordinate vector of $(x, y, z)$ with respect to the basis $B = \{(2, 1, 1), (1, 7, 7), (4, -1, 0)\}$.
Let $(x, y, z) = (13, 0, 0) \in \mathbb R^3$. Then $(13, 0, 0)$ is a vector. Also, $(13, 0, 0)$ is the coordinate vector of the vector $(13, 0, 0)$ with respect to the standard basis.
Taken as a regular vector, $(13, 0, 0)$ has another coordinate vector $(7, -1, 0)$ with respect to the basis $B$ since $(z + \frac {7}{13}(x - 6z + 4y, -\frac{1}{13}(x - 6z + 4y), z - y) = (7, -1, 0)$.
Comment: I haven't checked the arithmetic but what you've written makes perfect sense, yes.
Comment: @ BrianO. Thank you very much. This concept is super counter-intuitive to me right now.
Comment: Coulda fooled me ;) But I believe you. I think you're approaching it correctly: work through some examples in detail, and you'll build up your intuition. Try an even simpler example, e.g. $\Bbb R^2$, $B=\{(1,1), (-1,1)\}$.
Answer: Imagine you have to pay 17 dollars in cash, and money is available in 10 dollar and 1 dollar notes (bills). Then we can give it out using 1 ten-dollar and  seven 1-dollar bils. (1,7) are the co-ordinates. Instead if you are using five-dollar and two-dollar units (differnet 'basis') then you can pay that as 3 five-dollar bills plus 2 one dollar bills, So (3,2) is the co-ordinates for the same amount of 17 dollars.
My analogy is not perfect as basis means only one way  that amount should be possible (e.g. one can use 1  five-dollar bills and 12  one-dollar bills).
But this should cure you from the counter-intuitive feeling you are getting.


Neural Network: What if there are multiple right answers for a given set of inputs?

Question: For a given input into the input nodes, there are multiple correct values for the output nodes. In the training set, there are times when the inputs result in a certain output, and other times when the inputs result in a completely different (but equally valid) output.
Will a neural network still be able to "figure out" a pattern? From what I know about backpropagation, it seems like the different right answers would prevent it from functioning properly. If that's so, are there any solutions?
I don't need the neural network to predict all possible correct solutions, but I do need it to output a correct solution.
Comment: I believe that most typical algorithms can be adapted to this setting. The problem is that it is not usually done/well known, since the problem is not that relevant. Anyway you are right, generally it is not possible (e.g. I would not know how to do it in the case of an SVM).
Answer: A neural network can in principle deal with this. Actually, I believe they are among the best models for this task. The question is whether it is modeled correctly.
Say you are looking at a regression problem and minimize the sum of squares, i.e.
$$L(\theta) = \sum_i (\hat{y}_i - y_i)^2.$$
Here, $L$ is the loss function we minimize with respect to the parameters $\theta$ of our neural net $f$, which we use to find an approximation $\hat{y}_i = f(x_i; \theta)$ of $y_i$.
What will this loss function result in for ambiguous data like $(x_1, y_1), (x_1, y_2)$ with $y_1 \neq y_2$? It will make the function predict $f$ predict the mean of both.
This is a property which not only holds for neural nets, but also for linear regression, random forests, gradient boosting machines etc--basically every model that is trained with a squared error.
It makes now sense to investigate where the squared error comes from, so that we can adapt it. I have explained elsewhere that the squared error stems from the log-likelihood of a Gaussian assumption: $p(y|x) = \mathcal{N}(f(x; \theta), \sqrt{1 \over 2})$. Gaussians are uni modal, which means that this assumption is the core error in the model. If you have ambiguous outputs, you need an output model with many modes.
The most commonly used one is mixture density networks, which assume that the output $p(y|x)$ is actually a mixture of Gaussians, e.g.
$$p(y|x) = \sum_j \pi_j(x) \mathcal{N}(y|\mu_j(x), \Sigma_j(x)).$$
Here, $\mu_j(x), \Sigma_j(x)$ and $\pi_j(x)$ are all distinct output units of the neural nets. Training is done via differentiating the log-likelihood and back-propagation.
There are many other ways, though:

This idea is applicable also to GBMs and RFs.
A completely different strategy would be to estimate a complicated joint likelihood $p(x, y)$ which allows conditioning on $x$, yielding a complex $p(y|x)$. Efficient inference/estimation will be an issue here.
A quite different example is certain Bayesian approaches which give rise to multimodal output distributions as well. Efficient inference/estimation is a problem here as well.
Comment: It depends. If that is not what you want, you should a different likelihood function for your model, e.g. a mixture density network.
Comment: Forgive me if I missed something but isn't predicting the "mean of both" exactly the opposite of what we need? We need it to predict either one or the other, and exclude things like "mean" as wrong answers.
Comment: Yeah you're right; I misread your answer at first
Comment: @bayerj . I am skeptical your answer is correct.  Imagine a regression trained on millions of data points including say (0,0)  and that the  model has intercept zero.  Now add the point (0,100) to the training set.  The mean of the new data set will be approximately zero and the model will still approximately predict that 0 -> 0 .  Am I missing something ?
Comment: @bayerj  I think the same argument will work for any model that produces outputs that are continuous functions of their inputs- including neural nets.  It is certainly true that abstractly the loss function will be minimized by having the model output the mean of the $y_i$'s, but it may be impossible to get that value from a continuous f(x) .  So maybe your answer is correct for things like random forests and boosting.
Comment: You are right that your $f$ will also have to reflect the rest of the data set, sure. My point was merely that if you have a data set $\{(0, 1), (0, 0)\}$, $f(0) = 0.5$ if you minimise sum of squares. But that might not be what you want.
Answer: Perhaps an RNN can solve this "order doesn't matter" problem.
Consider the task of image captioning which has been successfully implemented by Stanford and Google. Now consider that an image might have multiple equally correct solutions, "dog playing with cat" or "cat playing with dog". I believe using an RNN (recurrent neural network) to spit out the text is the key to getting around this, because the RNN knows that if it already said "dog playing with" the next word should be "cat", and vice versa for "cat playing with" -> dog. http://cs.stanford.edu/people/karpathy/cvpr2015.pdf
Answer: Firstly there is no reason for back propagation to 'fail' in the case of ambiguous data.  Here is why.
Neural nets work by producing a truly highly non-linear function by composing linear functions with a non-linear activation function.  The model class of neural nets are functions of this class.  Roughly speaking a neural net produces a function as follows: At each stage a decision is made as to how many variables (features) to create.  Each new variable is created by composing the non-linear activation function with an arbitrary linear combination of the previous variables.  That means that there are (n+1)*(m) constants that are  created . Each new variable is some unknown linear combination of the n variables of the previous stage plus a constant.
One wishes to minimize the difference between actual observations and predictions according to some loss function $L(\Theta ,x_i)$ where $\Theta$ is all the parameters created by the model, that is the unknown sets of coefficients of all the linear functions. Thus the loss function is a function of the parameter set ${\Theta}$ and one wishes to minimize L with respect to the "theta's"
In the case discussed by bayerj, that loss function is $L_{\Theta} = \sum_i (y_i - F_{\Theta}  (x_i) )^2 $ . Where i runs over all the observations. The model is (in theory only !!!!) fitted by finding the parameters $\Theta$ which minimize this highly non-linear and non-convex function.
In general that is impossible to do. What one can do is find local minima of the function $L_{\Theta}$ as a function of ${\Theta} = (\theta_1, \ldots, \theta_M) $. Local minima can be calculated by various methods including gradient descent, which in the context of neural nets is called 'back propagation'. So there is nothing ambiguous about the y's being multivalued.  That is because one is interested in solving the system of equations $ \frac{\partial L}{\partial w_i}=0 $ for $ i = 1 \ldots (n+1)m $ .  There is no inconsistency because it treats each variable set and it's outcome as constants.
I will end with a little though experiment and a bigger thought experiment.  An ordinary least squares model is a trivial case of a neural net in which the activation is linear and there is only one layer and one output.  Imagine a data set consisting of $x_i = i, y_i = 3x_i + 'noise'$ and  i running from 0 to 10,000.  If I add a new observation $(x,y) = (0, 10) $ we have the ambiguous data points (0,noise) and (0,10) .  However the other 9,999 observations favor the data point (0,noise) and the model will reflect a value much closer to zero than to 5 = (0+10)/2 .
Bigger thought experiment. Imagine one is trying to discover probability of loan default using a neural net with income data and loan to income ratio (LTI).  Suppose one trains on 1000 people who don't default and 150 who do.  Now add example 1151 a person with characteristics of the top 1% of the no-default crowd, but assign him to the default outcome.  For example Mr. #1151 could have just discovered that his true love in life is gambling and not going to work every day.  The model will still have no choice but to characterize him as default = 0.  In essence, if one looks at the loss function for the first 150 people $L(x_i) = \mbox{nnet.train}(x_i)  '=' 0 $ will be almost identical.  To add $L(x_{151}$ to the mix will still have a loss function majorized by the behaviour on the first 150 examples.  It cannot average.
Answer: If you have more than one output $o_1, o_2,..,o_n$ for the $n$ possible correct answers. I have found the following error function works for about up to 4 expected answers:
$$E(o) = \tanh|e-o_1| \tanh|e-o_2|...\tanh|e-o_n|$$
Where $e$ is the expected result which is a random one of the correct answers.
Notice that the error is $E(o_n)=0$ for all $n$ and that nowhere $E''(x)=0$


Creating breadcrumbs based on content type relationships

Question: Currently I have 3 different content types: Program, Chapter, Item. A program contains multiple chapters and a chapter contains multiple items. These are related to one another using node reference field types.
On the item page I would like to have a breadcrumb listing: Program --> Chapter that is related to that specific item node.
I've looked into Custom Breadcrumbs and Page Breadcrumbs, but can't seem to figure out how to pull in the chapter and program that it is related to.
Comment: In which direction does the entityreference field go? Child pointing to parent, or parent pointing to child?
Comment: And, could you rename the question to breadcrumbs based on entity reference field? (note: there is no "node reference" in D7, there is only "entity reference"). There is also a "relation" module, but this is not what you are using.
Answer: For the time being I was able to figure it out by adding node reference fields to each of the content types. Then referencing my items to the chapters. I then found the Corresponding Entity Reference Module and used that to link them up. Using Custom Breadcrumbs I could use the reference tokens to create my breadcrumb.
Only downside is that I had to go into each item node. Took some time!
Answer: Try achieving it by Hansel Breadcrumb module. I don't have experience with situation of your kind but it works well for rule based breadcrumb. Module page describe :

Rules can be organized in a hierarchical structure.
Possible to leave breadcrumbs as is for specific sections.
Other modules can add switch types and breadcrumb actions by implementing the hansel_switch_types and hansel_action_types hooks.
An import / export module is included.
Export configuration in DOT format for visualisation (new).
Test functionality is available where you can see which steps are    executed to get the actual breadcrumbs for a given path.
Integration with forum module (new).
Integration with token module.
Integration with domain module.
Integration with og module (new).
Integration with realname module.
Settings for trimming of titles and whole breadcrumb items.
Comment: Yeah I tried that module. Unfortunately there is no documentation, not much support, and it is very complicated so I was not able to figure out how to use it. If it's even possible. :(