Angular 4 TalwindCSS setup

Question: Is there a way to configure TailwindCSS with Angular (4+)?
I'm happy to eject the Angular project, to make webpack configuration available. But I'm not sure what to put in the webpack.config.js so that TailwindCSS works nicely with the internals of Angular.
It would be great to have a setup such that I can still use a single command for dev (something like npm start), and continue to file changes watched (including CSS). Same for building the project.
Comment: I made the tutorial here if you guys want to take a look. It is proven working with AOT and latest Angular 9, also compatible with the previous version as well. You will need `@fullhuman/postcss-purgecss` plugin to remove unused CSS class from Tailwind. If you don't include that plugin, it will result in a massive bundle size of CSS.

https://github.com/trungk18/angular-tailwind-css-configuration
Answer: Method 1: (using ng-eject)
You can find full steps in this great video by Tom Gobich which I'd resume as follow:

Bring Sass into your project. If starting from scratch just run:
$ ng new project --style=scss

Go inside project, install tailwindcss then generate the config file:
$ cd project
$ npm install tailwindcss --save-dev
$ ./node_modules/.bin/tailwind init tailwind.config.js

Eject your app to output the webpack configuration file and solve new dependencies:
$ ng eject
$ npm install

add the tailwindcss plugin to webpack.config.js file:
const tailwindcss = require('tailwindcss'); // <-- create this constant
...

const postcssPlugins = function () {
   ...
   return [
      postcssUrl({
        ...
      }),
      tailwindcss('./tailwind.config.js'), //<-- then add it here
      autoprefixer(),
      ...
 };

add the @tailwind directives to src/styles.scss:
@tailwind preflight;

// your custom components goes here.

@tailwind utilities;

// your custom utilities goes here.

Start creating your tailwind components or grab some sample code online and put it into src/app/app.component.html for quick tests then run:
$ npm start

Method 2: (without ng-eject)
As mentioned in this nice article by @hackafro (Richard Umoffia) you can also use Tailwind's CLI to process your stylesheet. To do so, after creating your app and generating tailwind's config file:
$ ng new project
$ cd project
$ npm install tailwindcss --save-dev
$ ./node_modules/.bin/tailwind init tailwind.config.js

Create a new file at the same level of styles.css, call it tailwind-build.css for example, and add the following content to it:
@tailwind preflight;

// your custom components goes here.

@tailwind utilities;

// your custom utilities goes here.

Then, inside your package.json file add those 2 scripts under the script attribute:
{
  ...
  "scripts": {
    ...
    "tailwind": "./node_modules/.bin/tailwind build ./src/tailwind-build.css -c ./tailwind.config.js -o ./src/styles.css",
    "prestart": "npm run tailwind" // or "yarn run tailwind" depending on which you are using
  }
},

Now every time you start your server, or every time you manually type in terminal:
npm run tailwind // or "yarn run tailwind"

Tailwind's CLI will be used to fill ./src/styles.css content for you, which should work fine as angular CLI is already applying postCSS plugins on top of it including autoprefixer, more about it here: This is how angular-cli/webpack delivers your CSS styles to the client
Comment: As noted by ThanapongP., I get an "atRule.before..." error.
Comment: I made this the chosen answer, as using the latest angular version (from angular cli 1.6.0)  produces the desired result.
Answer: I put together some JavaScript using chokidar to watch my tailwind files and build them out when changes occur in my tailwind files, since Angular (as of 6.0.3, to the best of my knowledge) does not allow access to the postcss plugins in a CLI project (which is totally the way to go, in my humble opinion).
chokidar.js (top-level file, right next to package.json):
const chokidar = require('chokidar')
const child = require('child_process')

const tailwind = chokidar.watch(['tailwind.js', './src/tailwind.css'])

tailwind.on('change', (event, path) => {
  child.exec('npm run build-tailwind')
  console.log('Reprocessing Tailwind Files')
})

package.json scripts:
"scripts": {
  "ng": "ng",
  "build-tailwind": "./node_modules/.bin/tailwind build ./src/tailwind.css -c ./tailwind.js -o ./src/styles.css",
  "prestart": "npm run build-tailwind",
  "start": "ng serve & node chokidar.js",
  "build": "npm run prestart && ng build"
}

As you can see from the build-tailwind script, I just put tailwind.css in the src/ folder with the global styles.css, and all of my custom css goes there like any other tailwind project.
tailwind.css:
@tailwind preflight;

/* custom components */

@tailwind utilities;

/* custom utilities */

I hope that helps somebody while we wait for Angular to give us access to post-css directly.
UPDATE:
I built a cli tool for npm, to make this super easy on anyone else trying to take advantage of what tailwind offers in their angular projects.
https://www.npmjs.com/package/ng-tailwindcss
Answer: There is a better way without having to eject the CLI and not having a specific npm script for tailwind but simply by hooking into your CLI's webpack loaders.
You need to install npm install -D @angular-builders/custom-webpack postcss-scss tailwindcss
Then create a webpack.config.js config file:
module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        loader: 'postcss-loader',
        options: {
          ident: 'postcss',
          syntax: 'postcss-scss',
          plugins: () => [
            require('postcss-import'),
            require('tailwindcss')('./tailwind.config.js'),
          ]
        }
      }
    ]
  }
};

Then change your angular.json file to use this new configuration:
...
"build": {
  "builder": "@angular-builders/custom-webpack:browser",
  "options": {
    "customWebpackConfig": {
      "path": "webpack.config.js"
    },
    ...
  }
},
...

Import the tailwind utilities in your styles.scss
@tailwind base;
@tailwind components;
@tailwind utilities;

And now just run npm start and you are ready to use tailwind classes in your HTML or the @apply in your SCSS files!
Hope this helps.
I created a post to explain how in detail - https://email@example.com/angular-cli-tailwindcss-purgecss-2853ef422c02
Answer: If someone follow Salem's answer above and have the "atRule.before is not a function" error, just update all PostCSS dependencies to the latest version and everything should be working again.
Comment: @HackAfro What I did was delete the node_modules folder and then delete all the postcss stuff in package.json. After that I use `npm install postcss --save-dev`, `npm install postcss-loader --save-dev` and `npm install postcss-url --save-dev` to install the latest version of those dependencies.
Comment: I installed the latest postcss, and the error goes away. Running npm start (effectively 'webpack-dev-server --port=4200'), serves the application. However the tailwind styles do not seem to be coming through to the components.
Comment: I tried again, with the latest angular version (angular cli 1.6.0) and it produces the desired result

Angular 4 TalwindCSS setup


How to improve scipy based script for interpolation. Obtaining unknown x values

Question: Is there a way besides the graphical calltip function to obtain unknown x values from y? How would I go about coding an input() to obtain an unknown x value?
import numpy as np
from scipy import interpolate

x = np.linspace(0, 20, 5)
x = np.array([0. , 5. , 10., 15., 20.])

y = np.linspace(0.422,0.948, 5, endpoint =False)

y = np.array([0.422, 0.5513, 0.66433, 0.83433, 0.948])

f = interpolate.interp1d(x,y)
ynew = np.arange(0,1, 0.1)
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x,y,'o', ynew,f(ynew), '-')

Comment: Does the documentation for the `input` function that is built-in to Python help? https://docs.python.org/3/library/functions.html#input If not, you can search around for how to use it, this is probably a duplicate if that's your question. Otherwise, please clarify what you want to do.
Comment: I want to type in an unknown value and return the corresponding value from my standard curve (i.e. my x = and y = np.arrays)
Comment: Then do the `input` docs help you?
Comment: After some reading I'm thinking I need to use scikit instead. Might be possible with input(), but not sure? Thanks for the suggestion.
Answer: Here is the link to a video by APmonitor which had the solution. See script below:
from numpy import *
x = array([0,5,10,15,20])
y = array ([0.422,0.551333,0.66433,0.834333,0.948])

from scipy.interpolate import *
p1 = polyfit(x,y,1)

from matplotlib.pyplot import *

print(p1)

plot(x,y,'o')

plot(x,polyval(p1,x),'r-')

from scipy import *
slope, intercept, r_value, p_value,std_err = linregress(x,y)
print(pow(r_value,2))

print(p_value)


Contantes no codeigniter com dados do DB

Question: Boa tarde preciso pegar algumas configurações para o meu site que vem de uma tabela no banco de dados, atualmente utilizo variável mais dai toda hora tem que ficar indo lá no banco pra pegar, acho que isso pode deixar minha aplicação lenta não pode?
Caso verdadeiro qual seria a forma mais adequada?
Em busca no pai google vi que as constantes podem guardar dados pelo tempo que a aplicação ficar em execução, seria um boa pratica eu usar as constantes para deixar guardados os dados.
Os dados que preciso deixar gravado são, tenho um preço dos meus produtos, neles tenho que atribuir um desconto para pagamento a vista, mais quero deixar a opção para o meu cliente mudar essa taxa de desconto no admin dele, pra ele não ficar me pedindo depois de um tempo para ficar mudando ou vai saber tem clientes quer mudar toda mês.
Em uma busca na pasta config tem um arquivo constants.php, que se eu criar lá ele já fica para o site todo mais lá eu não consegui fazer load de um model acho que não deve ser possível fazer isso. Mais também não sei se será o correto utilizar constantes, preciso da ajuda de vcs. desde de já muito obrigado.
Answer: Não use constantes para valores dinâmicos.
Estas regras de descontos deverão ser definidos dentro de uma tabela do banco de dados, assim como você está fazendo agora. Eventualmente até uma tela para o usuário definir os valores de desconto.
A informação é pequena e não irá prejudicar a performance de sua aplicação.
Comment: obrigado lucas.


Saxophone for beginner -- which one (small hands)?

Question: I would like to learn to play saxophone. Can I play it from sitting down (wheelchair)?  Which is the best beginner size of saxophone? I have small hands and can reach an octave on piano.
Answer: The size of your hands shouldn't matter at all.  The keys are all right next to each other and don't require a stretch, except for maybe the left pinky--the good brands should have those keys designed ergonomically but sometimes the cheaper brands don't put as much care into them.  So check out brands in person and make sure they work.
Alto and lower saxes are typically played resting against the outside of the right leg, though alto and tenor can be played between the legs.  I imagine this position would hit the seat of a wheelchair, but knowing nothing further I'll leave it for you to investigate.
If you're having issues due to the wheelchair, then soprano might be the right choice.  It's shaped and held like a clarinet.  Beginners usually start on alto because the instruments are the cheapest and most people find it easiest to play, but there's no reason you can't start on any size.
Comment: I would always recommend playing the alto between the legs for better airflow. The tenor is just very uncomfortable in that position, so most use it on the side, which I recommend too. Else, +1
Answer: Because of the wheelchair, soprano or alto would be your best bet. The alto is typically played with the instrument sitting between your legs, whereas tenor and Bari are positioned to the right.
However... there ARE straight tenor saxophones that help solve this issue! They are a bit of a specialty item, but you should be able to find some. The tenor saxophone is not out of reach for anyone!
https://www.prowinds.com/product/6363/Phaeton-Dakota-Factory-Rebates-2017?utm_source=google&utm_medium=surfaces&utm_campaign=Surfaces%20Shopping&utm_content=google%20surfaces%20shopping&gclid=EAIaIQobChMIqIaJ7sb1-wIVTwutBh3vSgstEAQYAiABEgIqGvD_BwE
Comment: In some wheelchairs you can unmount the armrests. Depending on the size of the player, even an alt sax is played to the right if it will otherwise be stopped by the seat. Like me. I have to play to the right or sit at the front of the chair. One reason I don't play alt any more.


Prove Partial Order

Question: Prove that the following relation is an order on the Cartesian product {${1,2,3}$} × {${1,2,3}$} and draw its diagram.
$((x_1,x_2),(y_1,y_2))$ER if and only if $x_1 < x_2$ or $x_1=x_2$ and $y_1  ≤ y_2$
I can prove that this is reflexive, but I don't know how to prove it for anti-symmetricity and transivity.
Comment: For future reference, this is known as the *lexicographical order*.
Comment: It is about 9 elements. Write them down all, preferaribly according to the given order, you can also skip the parenthesis and the comma, so that the elements of the cartesian product may now be written like: 11, 32, 13, 22, ... maybe that helps.
Answer: Presumably there's a typo in the question, otherwise the relation is neither antisymmetric nor transitive.  Counterexamples:

E.g. $\big((1,2),(2,3)\big) \in R$ since $1<2$, and $\big((2,3),(1,2)\big) \in R$ since $2<3$, and thus $R$ is not antisymmetric.
E.g. $\big((1,1),(1,2)\big) \in R$ since $1=1$ and $1 \leq 2$, and $\big((1,2),(3,2)\big) \in R$ since $1<2$, but $\big((1,1),(3,2)\big) \not\in R$ since $1 \not< 1$ and $3 \not\leq 2$, and thus $R$ is not transitive.

This might explain why you are finding the question difficult.

Fixing the probable typo, the relation becomes:

$\big((x_1,x_2),(y_1,y_2)\big) \in R$ if and only if $x_1<y_1$ or $x_1=y_1$ and $x_2 \leq y_2$.

To show it's an order relation, we check:

Reflexive: Since $x_1=x_1$ and $x_2 \leq x_2$, we know $\big((x_1,x_2),(x_1,x_2)\big) \in R$.  Hence $R$ is reflexive.
Antisymmetric:  Suppose $\big((x_1,x_2),(y_1,y_2)\big), \big((y_1,y_2),(x_1,x_2)\big) \in R$.  Then there are four possibilities:
$$
\begin{array}{c|c|c|}
        & x_1<y_1 & x_1=y_1 \text{ and } x_2 \leq y_2 \\
\hline
y_1<x_1 & \text{impossible} & \text{impossible} \\
\hline
y_1=x_1 \text{ and } y_2 \leq x_2 & \text{impossible} &  \\
\hline
\end{array}
$$
So, we must have $x_1=y_1$ and $x_2 \leq y_2$ and $y_2 \leq x_2$.  Since $\leq$ is an antisymmetric (order) relation, we must have that $x_2=y_2$.  Hence $(x_1,x_2)=(y_1,y_2)$, and we can conclude that $R$ is antisymmetric.
Transitive: Suppose $\big((x_1,x_2),(y_1,y_2)\big), \big((y_1,y_2),(z_1,z_2)\big) \in R$.  Then there are four possibilities:
$$
\begin{array}{c|c|c|}
        & x_1<y_1 & x_1=y_1 \text{ and } x_2 \leq y_2 \\
\hline
y_1<z_1 & \text{implies } x_1<z_1 & \text{implies } x_1<z_1 \\
\hline
y_1=z_1 \text{ and } y_2 \leq z_2 & \text{implies } x_1<z_1 & \text{implies } x_1=z_1 \text{ and } x_2 \leq z_2 \\
\hline
\end{array}
$$
(The above deductions use the transitivity of the relations $=$, $<$ and $\leq$, along with the properties "$x_1=y_1<z_1$ implies $x_1<z_1$" and "$x_1<y_1=z_1$ implies $x_1<z_1$".)  In all four cases, $\big((x_1,x_2),(z_1,z_2)\big)$ satisfies the conditions of $R$.  Hence $\big((x_1,x_2),(z_1,z_2)\big) \in R$, and we can conclude that $R$ is transitive.

Prove Partial Order


Initialisation of a variable inside a loop

Question: class Spaces {
public static void main(String args[])
throws java.io.IOException{

    char ch;
    int space = 0;

    do {

        ch = (char) System.in.read();
        if (ch == ' ') space++;

    } while (ch != '.'); //Stop if fullstop is provided

System.out.println("No. of spaces: " + space);
}

The following code above is completely correct and is doing exactly what it is intended to do.(To read characters until fullstop is pressed, then tell the user how many spaces have been entered). Although if I initialise the variable outside the do-while loop like in the following code:
class Spaces {
public static void main(String args[])
throws java.io.IOException{

    char ch = (char) System.in.read();
    int space = 0;

    do {

        if (ch == ' ') space++;

    } while (ch != '.'); //Stop if fullstop is provided

System.out.println("No. of spaces: " + space);
}

The program is refusing to stop. When I enter the full stop, the program is not stopping. I do know that declaring a variable inside the loop would mean that it is unavailable elsewhere outside that loop. But variable declared outside the loop (like in second set of code) should work in the loop and elsewhere. So I am not getting why the second set of code is not valid (the program runs, there is no compiling error, but when full stop is entered it keeps going).
I also understand this is a very basic question compared to the ones that get asked here. But I honestly couldn't find an answer. Thank you in advance.
Comment: The second example does not work because `System.in.read();` is only being called once, at the beginning. If you want to stop, you need to get the input inside the do while loop.
Answer: The second program does not work because you are taking the input only once, and since the value of ch != '.' is always true, the loop never stops. You should instead place the System.in.read() inside the loop, so that in every iteration, the program will stop for the user input, compare it with the condition and then decide if next iteration should be performed or not.
Answer: you cant take ch = (char) System.in.read(); out of the loop. because you always have to ask the system to get you the new character.
Try to print your character, you will find that you are always printing the first character and you are in infinite loop.
Answer: Whatever value was in ch when this loop started will remain there forever because there's nothing writing to it:
    do {

        if (ch == ' ') space++;

    } while (ch != '.'); //Stop if fullstop is provided

Answer: You have to call System.in.read() from inside the loop. Like this:
class Spaces {
public static void main(String args[])
throws java.io.IOException{

    char ch = 0;
    int space = 0;

    do {
        ch = (char) System.in.read();
        if (ch == ' ') space++;

    } while (ch != '.'); //Stop if fullstop is provided

    System.out.println("No. of spaces: " + space);
}

The way you did it only one charakter is read in.
And afaik i know you dont have to write a throws statement for the main method.
Answer: You are calling System.in.read() outside of the do...while loop, so it's value never updates. Entering a full stop will not make difference in the second code because the value of ch is never updated. It is always equal to the value you initialized it to (in the case of the second example, System.in.read().
With regards to your confusion, a variable declared outside the loop can work in the loop, but it needs to be updated if you want to persist changes. for example:
int count=0;
for(int i=0; i<10; i++) {
    count++;
}
//count will be 10 now

As you saw in your question, this is why the first set of code works, because in
    char ch;
    int space = 0;

    do {

        ch = (char) System.in.read(); //ch is updated
        if (ch == ' ') space++;

    } while (ch != '.');

ch is updated. you could also have
char ch = (char)System.in.read();
int space = 0;

do {

    ch = (char) System.in.read();
    if (ch == ' ') space++;

} while (ch != '.');

where you actually instantiate the variable outside of the loop, but again, the value must be updated within the loop.
Answer: Variable declaration is not the same as variable initialisation which is also not the same as setting or assigning a variable.
In both versions of your program the variable declaration is outside of the do-while loop. A variable declaration includes the variable type and the variable name, so both char ch; and char ch = (char) System.in.read(); declare the variable ch as type char.
Variable initialisation is assigning a value to the variable when it is declared. For example, try running this program.
int i; // declaration and initialisation to default value
System.out.println("The integer is: " + i);

Java has a default for the initial value of any variable. If you do not want to use this default, you can instead use your own value. In this example we declare the variable i as type int and initialise it to the value 5.
int i = 5; // declaration and initialisation
System.out.println("The integer is: " + i);

Finally, after a variable is declared and initialised you may assign a new value to the variable. Note that when you assign a variable you do not state the type of the variable -- this is only done in declarations.
int i = 5; // declaration and initialisation
i = 6;     // assignment
System.out.println("The integer is: " + i);

Assigning a variable stores a value, and using a variable reads the stored value. Moving the variable outside of the loop as you have done would usually be okay. However, System.in.read() is not a usual expression because it is impure. This means that when you call System.in.read with the same arguments it does not always produce the same value. To demonstrate this, try running both versions of the example program.
Version A
int a = (int) System.in.read();
int b = (int) System.in.read();
System.out.println("a is: " + a);
System.out.println("b is: " + b);

Version B
int a = (int) System.in.read();
int b = a;
System.out.println("a is: " + a);
System.out.println("b is: " + b);

If you write program A you may be inclined to simplify the program by using the transitivity of equality. That is, if b = (int) System.in.read() and a = (int) System.in.read() then by transitivity, b = a. However, this only holds if System.in.read() produces the same value every time it is used, and because it is impure this is not the case.
Also notice that in program B you are not prompted twice for an input. This is because System.in.read is only called once to initialise the variable a. It is not called when a is used (i.e. read) to assign b or to print to the console with System.out.println. Also try running this program for clarity.
int a = (int) System.in.read();
System.out.println("a is: " + a);
a = (int) System.in.read();
System.out.println("a is: " + a);

Finally coming to your loop, the reason it may not terminate is because the value of ch is invariant. This means the value of ch does not change during execution of the loop.
// ch is declared and initialised
char ch = (char) System.in.read();
int space = 0;

// There are no assignments to ch in the loop, so it remains invariant
// during the loop's execution. This means if `ch != '.'` tests true
// once it will continue testing true.
do {
    if (ch == ' ') space++;
} while (ch != '.');

// ch is declared and initialised
char ch;
int space = 0;

// ch is assigned during the loop to an impure expression and has the
// potential to vary for each iteration of the loop. This means even
// if `ch != '.'` tests true once it may not test true next iteration.
do {
    ch = (char) System.in.read();
    if (ch == ' ') space++;
} while (ch != '.');

Comment: Very clear. Cleared up a lot of concepts and vocabulary. Thank you.


Smallest normal subgroup making quotient abelian, nilpotent, solvable

Question:
Given a finite group $G$ that is not abelian, nilpotent, or solvable, what is the smallest normal subgroup $H$ in each case such that $G/H$ is abelian, nilpotent, or solvable (respectively)?

In the abelian case it seems clear that the correct subgroup is the commutator subgroup. But what of the other two? Perhaps I'm just shaky with the concepts (of nilpotency and solvability) but I'm having trouble finding the right way to tackle this problem.
Edit: Well I've tried the most obvious thing and it worked out.
For the nilpotent case I took the intersection of all the subgroups in the lower central series, and for the solvable case I took the intersection of all subgroups in the derived/commutator series.
Comment: Your answers are correct when $G$ is finite. When $G$ is infinite, it could happen that the lower central series and/or the derived series are non-terminating (this happens in noncyclic free groups, for example), in which case there is no smallest normal subgroup with the required property. For fixed $k>0$, there is always a smallest normal subgroup such that the quotient is nilpotent of class at most $k$ or solvable with derived length at most $k$.
Comment: In many cases the answer's trivial: if $\;G\;$ is simple non-abelian then the minimal normal such sbgp. is $\;G\;$ , of course. Pretty boring.
Comment: In many cases it isn't, though. One gets some very different smallest normal subgroups of $D_{2n}$ making the quotient nilpotent, depending on the order of $n$.
Answer: The things you are asking about are quite well studied:
Suppose $G$ is a group and $\mathfrak{U}$ is a variety of groups (a class of groups, that is closed under taking subgroups, quotients and direct products; examples of varieties include abelian groups, nilpotent groups of class less than $c$ for any constant $c$ and soluble groups of class less than $c$ for any constant $c$). Then the smallest normal subgroup $H$ of $G$, such that $\frac{G}{H} \in \mathfrak{U}$ is called verbal. Basic properties of verbal subgroups can be seen under this link
What's about the classes of all nilpotent (soluble) groups, then this does not work (because they are not varieties). However, we can look at the intersection of all verbal subgroups corresponding to the varieties of nilpotent (soluble) groups of class less than $c$ for all possible constants $c$. This subgroup will be normal and there are two cases possible:
1) Quotient by it is nilpotent (soluble). Then it is the subgroup you are looking for.
2) Quotient by it is non-nilpotent (non-soluble). Then the subgroup you were looking for does not exist.
Comment: However, "all nilpotent groups" and "all solvable groups" are not varieties, so this does not solve the question "quotient is nilpotent" or "quotient is solvable".
Comment: @ArturoMagidin, I edited my answer to cover this too.


Simple little questions about available (ex)tensions

Question: In the key of Em, does the F#m7-5 chord have the b13 (D natural) or the 13 as an available (ex)tension?
Same question in Bb Major regarding the Gm7 chord, is the 13 (E natural) an available (ex)tension?
If so, why??
Comment: @everyone Tension is term used at Berklee to describe extensions to the chord.  "The word "tensions" is really short for "extensions" because they are an extension of the basic seventh chord."   - https://www.thejazzresource.com/chord_tensions.html
Comment: @ToddWilcox Sorry for my poor english..english isn't my first language.What I mean is the tension note for the chords like 9th 11th 13th. Notes you could add on the chords.
Comment: @Tim Actually doing a search for "tension note" helped me a lot. Now I understand the question.
Comment: @tim - how about changing it to _color tone_ ?
Comment: @rlo - funny, because 'ex' in English at least usually means 'used to be'. Funny...
Comment: @Tim Totally unrelated, but "extra", "exit", "extreme", "exceptional", "excellent", "extraordinary", "external". I could go on. In English, "ex" **rarely** means "used to be".
Comment: Can you explain what a "tension 13" is? Am I reading that right?
Comment: @ToddWilcox what do you mean??
Comment: If I google "tension 13" I get no hits that are related to music theory. I don't know what "tension 13" is. Your first sentence includes the phrase "if there is a tension 13" and I don't understand that phrase.
Comment: Tension note isn't too helpful. Added note might work. You can add what the heck you like to a basic chord, sometimes it adds nicely, sometimes it adds tension, if that's what you mean. But context is important too.
Comment: @ToddWilcox - a bit of touche there. I like it, and will respond after a well earned sleep...
Comment: @ToddWilcox - 'tra', 'it', 'ceptional', 'cellent', not words generally in their own right (**ex**cept 'it'...) but 'tension' *is* its own word ! My fault for not being as fastidious as usual with my language. Please forgive me!
Comment: @Tim- We americans can butcher almost anything , including the Queen"s English, and I've not been to Berklee so I was also puzzled by the terminology used in the question, but reading these comments was entertaining and informative at the same time.
Answer: For half-diminished 7th chords, the b13 is an available tension and the natural 13 and the #13 are not available (technically the #13 is just an octave above the 7th so it's not a tension in this case). So for the F#m7-5 chord, D natural is available and D# is not. The reason why the b13 is available in this case is because the 5 is diminished, which means the b13 is two steps away from both the 5th and the 7th.
For minor 7th chords, the natural 13 is an available tension, the #13 is enharmonic to the 7th (an octave up) and the b13 is unavailable. So you could use E natural for the Gm7 chord. The reason why the b13 is unavailable in this case is because it is only one step from the 5th. The 13 is two steps from the 5th and only one step from the 7th, but it works better to be closer to the 7th than the 5th in this case.
See: http://www.thejazzpianosite.com/jazz-piano-lessons/jazz-chords/available-tensions/
Comment: Not up to speed yet ! F#m7-5 with a D note makes D dominant 9, without a lot of 'tension'. Missing something - unsure what...
Comment: @Tim If the F# is the lowest sounding note and the D is above, it could be heard as an F#m7-5addb13. "Tension" in this case is meant in a different sense from the typical sense of a feeling in the listener. This is a branch of jazz chord theory that seems to be sort of "grass roots", you might say, where **a tension** is a note you can add to a 7th chord to add flavor. But some *tensions* "work" better than others. *Available tensions* are 9ths, 11ths, or 13ths that "work" and *unavailable tensions* are the same intervals that "don't work". Maybe a bit simplified but it's a way to view it.
Comment: @Tim I suggest following the link, which explains it better than I can.
Comment: I see that the page you linked to points out that these _available tensions_ are the ones which are used in practice, but does not rule out that other tensions might be used too. Just to add some information, [here is a question about adding a ♭9 to a major 7th chord](https://music.stackexchange.com/questions/22600/am-i-allowed-to-add-a-b9-to-a-maj7-chord-in-jazz). I flipped through my copy of Ted Greene's compendious _Chord Chemistry_, and found a few examples of Maj7(♯9) chords listed, but none for Maj7(♭9) chords, and none for Maj7 with sharp or flat 13ths.
Comment: @DavidBowling Good point. My answer is intended to address what seems to be the nature and context of the question, not a general guideline of what intervals can or should be added to chords in jazz. And sounds like both the asker and I could benefit from reading Ted Greene's book.
Comment: If the song is in Bb, then I would advise some caution when using an E on the Gmin7 chord. The risk is that a soloist is playing G Aeolian, which has an Eb rather than an E natural, so the Gmin13 voicing would clash with the soloist. Of course, this doesn't mean that Eb would sound *good* in the Gmin7 chord. It just means that the E and the Eb are both bad choices. (Though I could see using an Eb on the Gmin7 chord if it fairly quickly resolves down to a D.)


Easier way to filter data

Question: I'm trying to figure out a faster way to filter the tags below instead of using map three times.
I've looked a bit at loadash and their filter function. But doesn't seem to help speed wise.
export function tagFilter(reviews, userTags) {

    const arr = [];

    map(reviews, (review) => {

        let count = 0;

        map(review.tags, (tag) => {
            map(userTags, (userTag) => {
                if (userTag.tag_data.id === tag.id) count += 1;
            });
        });

        arr.push({ review, count });

    });

    arr.sort((a, b) => b.count - a.count);

    const reviewArray = [];

    arr.forEach((reviewObject) => {
        reviewArray.push(reviewObject.review);
    });

    return reviewArray;
}

Any suggestions is highly appreciated?
Comment: An example of what contains the variable `reviews` would help us a lot
Answer: map, loop, for loop and lodash map from this looping option the fastest is lodash map so i am sure about this you have to use lodash for map no other looping library is faster then lodash
Here are a comparation of the native map against the lodash map
https://jsperf.com/native-map-vs-lodash-map
Aparently lodash is faster

Easier way to filter data


If A is some invertible $n \times n$ matrix then show $\det(A^n) = (\det(A))^n$ for all $n\in \mathbb{Z}$

Question: So there exists $A^{-1}$. I am assuming $\det(AB)=\det(A)\cdot\det(B)$ and $(A^d)^f=(A^{df})$
I know the proof for $\det(A^{-1})=(\det(A))^{-1}$ is:
$\det(I_n)=1$
$\det(A\cdot A^{-1})=1$
$\det(A)\cdot \det(A^{-1})=1$
$\det(A^{-1})=\frac1{\det(A)}=(\det(A))^{-1}$
But I'm not sure how to prove it when it's $n\in\mathbb{Z}$, and that if A is not invertible then for all $n\in \mathbb{N}$
Comment: if you know $\det(AB)=\det(A)\cdot\det(B)$, then it's immediate. Use induction if you need to.
Answer:
I am assuming $\det(AB)=\det(A)\cdot\det(B)$ and $(A^d)^f=(A^{df})$

By your assumption,
$$
\det(A^1)^n = \det(A^{1 \cdot n})
$$


calcular duração entre 2 valores dentro do input

Question: Olá, eu tenho um código em javascript que me ajuda a calcular a duração entre uma hora e outra, preciso saber como fazer para deixar esses valores mais dinâmicos, quero colocar a hora de entrada em um input, a hora de saida em outro input e o resultado (qtd de horas) em um 3º input.
Alguem pode me ajudar?
Segue o código que eu tenho

Answer: Bom a parte mais difícil você já fez(não conferi o cálculo), então fica assim:

 <input id="start" type="time" name="s_time"> : Start

 <input id="end" type="time" name="e_time"> : End

 <input type="button" value="Run" onclick="calcTime()" />

 <input id="result" type="text" value=""/> : Resultado


OpenVPN: Assign a single URL to an IP

Question: I have a remote server that I am connecting to via OpenVPN. The OpenVPN-Server is configured not to forward ipv4 packages, so the "internet-traffic" does not go through the server.
Now I would like to assign a single URL to an IP address within the network. So for example: Whenever I am connected to the VPN and I enter random.org in my browser it redirects me to 10.8.42.12 within my VPN-Subnet.
I don't know, if this is possible or advisable? I have searched for a solution, but have not found one. Maybe because I am not using the correct terminology?
Any help or comments appreciated. Thanks! :)
Answer: You need to set a DNS A record somewhere, either on your VPN network or another network to which the clients can reach.
If you have a DNS server on the VPN network (or a network routable from the vpn connection) then you can configure openVPN to push DNS server addresses down to the clients so that when they connect, DNS's requests will go to the server you have specified that contains the A record you need. This set up means that the URL will only resolve to that IP when clients are connected to the VPN.
See this:
https://openvpn.net/index.php/open-source/documentation/howto.html#dhcp
EDIT:
I forgot to mention that consideration must be taken when changing out client DNS settings. The clients cache may still contain the lookup in which case you must look at setting the TTL on the A record so that it expires quickly.
Answer: use hosts file as in
10.8.42.12 example.org

or add entry to DNS server. create file with (e.g.) contents modifying the ns1.exampledns.com to point to a valid address
; Zone file for example.org
$TTL    3600
$ORIGIN example.org
@       IN      SOA     ns1.exampledns.com.    root.example.org. (
                                                     2012033101         ; Serial
                                                     3600         ; Refresh
                                                     1800         ; Retry
                                                     604800         ; Expire
                                                    43200 )       ; Negative Cache TTL

                IN      NS      ns1.exampledns.com.
                IN      NS      ns2.exampledns.com.

@       IN      A       10.8.42.12
www     IN      A       10.8.42.12

then add zone to /etc/bind/named.conf.local
zone "example.com" {
                type master;
                file "/etc/bind/db.example.org.conf";
};

Answer: Sure, the DNS solution as per tomstephens89 answer is one possible answer, but it works only if you type any domain name, and also that won't work if the client alter the DNS servers pushed by the server.
What do you really want is a solution, which is sometimes called Captive Portal. I am not strictly inside that topic, but SQUID which is a powerful HTTP proxy (which can be configured to be a transparent one - i.e. no configurations on client side needed) can help redirect the user to your page.
Comment: What you are referring to is a HTTP Proxy and yes these can be used for directing HTTP requests. However for this task, a simple DNS configuration would suffice rather than putting a proxy in place. You are correct in saying that the client is able change the pushed DNS settings.
Comment: Thanks for noting my mistake - of course SQUID is an HTTP Proxy. I fixed that error. The solution with setting up a kind of a Captive Portal with the help of a HTTP proxy server can also reroute requests to IPs, not only to DNS, and is a more robust solution. But it is indeed not an easy setup. But this won't mess with the user DNS cache - if the user reconnects to a normal internet connection and doesn't clear it's DNS cache it can have problems because of DNS rerouting cached previously.
Comment: that is a fair point regarding the client DNS cache and I will edit my answer to indicate that if DNS is the chosen solution then consideration must be taken with the TTL on the record.

OpenVPN: Assign a single URL to an IP


Acts_as_indexed .with_query() não retorna os resultados esperados na query

Question: Boa tarde,
tenho um método para buscar produtos no banco que usa o método with_query da gem acts_as_indexed:
Produto.with_query(query_texto)
Isso esta gerando uma query SQL  assim:
SELECT  produtos.* FROM produtos WHERE (produtos.id IN (NULL)) LIMIT 11
Já testei substituindo o .with_query(query_texto) por .all e os resultados são retornados. Já verifiquei no meu model produtos.rb tenho configurado os campos para  gem funcionar (acts_as_indexed :fields => [ :status, :nome ]).
Alguém tem alguma idéia de porque a gem esta retornando  WHERE (produtos.id IN (NULL)) na query?
Obrigado.
obs o mesmo ocorre pelo console
Produto.with_query('Pump')
Produto Load (0.6ms)  SELECT  produtos.* FROM produtos WHERE (produtos.id IN (NULL)) LIMIT 11
Answer: O problema foi solucionado dando um update em todos os produtos. Pelo visto essa gem cria algum tipo de index quando o item é atualizado.
Fiz isso no rails console:

Produto.all.each do |produto|
    nome = produto.nome
    Produto.update(produto.id, :nome => 'teste')
    Produto.update(produto.id, :nome => nome )
end


Weblogic server listening on additional port 5001

Question: Weblogic managed server is listening on 5001 in adddition to the listen port. Not sure why ? Please advise
Comment: Appservers open up a whole bunch of ports for various purposes. Is this just idle curiosity?
Answer: WebLogic Server will typically listen on two ports by default - the configured non-SSL and SSL  ports. You can see log mesages associated with these in WebLogic Server's bootup. (an example is provided a the end of the comment from a WLS 11g domain that only has a HTTP port configured)
Are you running any Fusion Middleware products like OSB or SOA Suite on top of WebLogic Server? These will often have application-specific ports that are used for different purposes.
Also, I'd recommend searching your config.xml for any reference to 5001 - it's possible that there's a network channel configured as part of the domain, or an admin port.
<code>####<01/03/2011 6:07:30 PM EST> <Notice> <Server> <danger-room> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <11d1def534ea1be0:36936e7f:12e703dca5f:-8000-000000000000000a> <1298963250040> <BEA-002613> <Channel "Default[3]" is now listening on 0:0:0:0:0:0:0:1:7001 for protocols iiop, t3, ldap, snmp, http.>
####<01/03/2011 6:07:30 PM EST> <Notice> <Server> <danger-room> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <11d1def534ea1be0:36936e7f:12e703dca5f:-8000-000000000000000a> <1298963250040> <BEA-002613> <Channel "Default[2]" is now listening on 127.0.0.1:7001 for protocols iiop, t3, ldap, snmp, http.>
####<01/03/2011 6:07:30 PM EST> <Notice> <Server> <danger-room> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <11d1def534ea1be0:36936e7f:12e703dca5f:-8000-000000000000000a> <1298963250040> <BEA-002613> <Channel "Default" is now listening on 10.0.2.15:7001 for protocols iiop, t3, ldap, snmp, http.>
####<01/03/2011 6:07:30 PM EST> <Notice> <Server> <danger-room> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <11d1def534ea1be0:36936e7f:12e703dca5f:-8000-000000000000000a> <1298963250040> <BEA-002613> <Channel "Default[1]" is now listening on fe80:0:0:0:a00:27ff:fe8d:6a0f:7001 for protocols iiop, t3, ldap, snmp, http.>
</code>
Answer: With good probability you have installed and activated Hudson CI service in Weblogic. And this service listen to port 5001. For more information you can see this page.


Combinatorics question - seats

Question: In how many options can we arrange random number of men (identical men) in line of 15 chairs but:
1. 2 men can't sit next to each other.
2. next to each empty chair - there is at least one men.
i can't find the easiest way to solve this problem.
i tried to make a tree with all options, and i got to 113 different options (maybe i missed some). but I'm sure this is not the way me teacher want's me to do it.
Comment: Are these conditions separate questions, or do both conditions have to be satisfied simultaneously?
Answer: Case 1: At least one empty seat, between every seated man.
Take $15-n$ empty seats.  Select from among the $16-n$ spaces before, between, and after each of these one $n$ into which to place a sitting man.
This will fill $15$ seats with $n$ men with at least one empty seat between each seated man.
The number of seated men can be between $0$ and $8$.
$$\sum_{n=0}^8 {16-n\choose n}$$

Case 2: At least one man next to each empty seat.
This means no more than two seats can be adjacent to each other.
Take $15-n-2m$ men sitting on chairs.  From among of the $14-n-2m$ spaces between the sitting men (not before or after), select $m$ to place a pair of empty chairs.  Into the $16-n-3m$ unused spaces before, between, and after the men, select $n$ to place the remaining single empty chairs.
There will then be $15$ seats with no more than $2$ empty chairs between each one (and at most one empty chair on either end).
The number of pairs of empty seats can be no more than 4.  The remaining single empty seats can number no more than $\lceil \frac{14-3m}2 \rceil$.
$$\sum_{m=0}^4\sum_{n=0}^{\lceil \frac{14-3m}2 \rceil} {14-n-2m\choose m}{16-n-3m\choose n}$$
Answer: Suppose the following interpretation of your problem:
Given 15 chairs in a line, how many ways can you seat people so that the following two conditions are met:
(1) No two people are in adjacent seating, and
(2) each empty chair is adjacent to at least one seated person.
Let us diagram this by denoting "P" as a seated person and "_" as an empty seat. For example,
P_P_P_P_P_P_P_P
is a possible configuration with 8 seated person with 7 empty chairs in between: No two seated person are adjacent, and each empty chair is next to at least a seated person.
We will examine cases with different number of seated person. First note that we can have at most 8 people, and at least 5 people (check this!) that satisfy both condition above.
Case 8 people:
There is only one possible configuration: the one given above.
Case 7 people:
Since no two people are seated adjacently, that means there is at least a chair between two people. So preliminarily we have the following configuration of 7 people and 6 empty chairs in between:
P_P_P_P_P_P_P
But we still have two more empty chair to place. Note that these two empty chairs could be at the very beginning, the very end, or in between two seated person, and you cannot place these two extra chairs next to each other (otherwise you will have a chair that is not next to a seated person). So we have 8 possible places to put 2 extra empty chairs, which gives us $8\choose 2$ ways.
Case 6 people:
First we have preliminary configuration of 6 people with 5 empty chairs between:
P_P_P_P_P_P
Now we have 4 extra chairs to be in 7 possible positions (same argument as before), which gives $7 \choose 4 $ configurations.
Case 5 people:
Same analysis should lead you to $6 \choose 6$ ways.
Thus, in total, we have $1+ {8\choose 2}+ {7\choose 4 }+{ 6\choose 6}=65$ ways to have some number of people in 15 chairs satisfying both conditions above.
Comment: Much easier when both conditions are satisfied at once.

Combinatorics question - seats


Query varrendo todos registros

Question: Bom dia pessoal, alguém poderia me ajudar nesse retorno?
Bom, tenho esse select:
public function Empenho($id)
{
    $table = DB::table('empenho as emp')
            ->join('gestora', 'emp.unidGestId', '=', 'gestora.id')
            ->join('gestora_tipo', 'gestora.tipoId', '=', 'gestora_tipo.id')
            ->join('despesa', 'emp.fichaOrcId', '=', 'despesa.id')
            ->join('pessoa', 'emp.fornecedorId', '=', 'pessoa.id')
            ->join('sub_elemento', 'emp.subElementoId', '=', 'sub_elemento.id')
            ->join('fonte', 'emp.fonteId', '=', 'fonte.id')
            ->join('cbo', 'emp.cboId', '=', 'cbo.id')
            ->select('gestora_tipo.nome as a', 'emp.nrEmpenho as b', 'emp.date as c', 'emp.hora_insc as d',
                     'emp.valor as e', 'pessoa.nome as f', 'sub_elemento.codSubElem as g', 'despesa.valor as h',
                     'fonte.descricao as i', 'emp.historico as j', 'emp.tipo as k',
                     'cbo.descricao as l', 'emp.folha as m')->get();

    $header = ['Gestora', 'Número', 'Data', 'Hora', 'Valor', 'Credor', 'SubElemento',
        'Despesa', 'Fonte', 'Historico', 'Tipo', 'CBO', 'Folha'];

    return ['Tipo' => 'Empenho', 'header' => $header, 'table' => $table, 'id' => $id];
}

O método get pega todas as informações, no entanto estou passando um parâmetro "id" que  recebe a identificação de cada registro do banco, então faço o mapeamento e o retorno do select:
function retornaEmpenho(json){
var result= $('
');

for(var i = 0; i < json.header.length; i++)
{
    for(var j = 0; j < json.table.length; j++)
    {
    var arr = $.map(json.table[j], function(value){
        return [value];
    });
}
    var divInner = $('
');
    divInner.addClass(json.header[i]);
    divInner.append(json.header[i]+': ');
    divInner.append(arr[i]);
    result.append(divInner);
}
    return result;
}

Tudo está funcionando normalmente, no entanto só consegui fazer o mapeamento de todo o registro, então minha variável "arr" sempre vai receber o ultimo registro, pois foi o último valor atribuído, o que eu queria saber é, como faço pra minha variável "arr" fazer o mapeamento somente do "$id" e me retornar somente os campos do "$id", alguém sabe como eu o faço? Estou usando laravel.
Grato desde já !
Answer: Após a linha:
$table = DB::table('empenho as emp')

insira seu 'where' assim:
->where('nome_da_coluna_de_id', $id)

Tente com esse 'where' aí e substituindo 'join(' por 'leftJoin('.
Comment: Agradeço a resposta amigo, no entanto não resolveu, tentei dessa mesma forma que você me falou, também tentei assim:  ->where('empenho', 'empenho.id', '=', $id), no entanto ambos não resolveram.  Obrigado assim mesmo, continuo tentando.
Comment: O que retornou a query com esse `where` ? pode explicar melhor @LincolnBinda? Qual foi o retorno?
Comment: Tente com esse 'where' aí e substituindo 'join(' por 'leftJoin(' em todas as ocorrências.
Comment: Obrigado pelas respostas, tenho que esperar minha reputação chegar ao 15 para poder reputar, falta bem pouco, sou totalmente novato no fórum e ainda não consigo sinalizar como útil, no entanto agradeço em especial ao amigo Jhonnyjks por ter me ajudado a solucionar o problema. Grato !
Comment: Tranquilo! Cheguei ontem nessa versão PT do stack overflow, vamos contribuir e fortalecer!

Query varrendo todos registros


Caching Large Dataframes in Spark Effectively

Question: I am currently working on 11,000 files. Each file will generate a data frame which will be Union with the previous one. Below is the code:
var df1 = sc.parallelize(Array(("temp",100 ))).toDF("key","value").withColumn("Filename", lit("Temp") )
files.foreach( filename => {
             val a = filename.getPath.toString()
             val m = a.split("/")
             val name = m(6)
             println("FILENAME: " + name)
             if (name == "_SUCCESS") {
               println("Cannot Process '_SUCCSS' Filename")
             } else {
               val freqs=doSomething(a).toDF("key","value").withColumn("Filename", lit(name) )
               df1=df1.unionAll(freqs)
             }

})

First, i got an error of java.lang.StackOverFlowError on 11,000 files. Then, i add a following line after df1=df1.unionAll(freqs):
 df1=df1.cache()

It resolves the problem but after each iteration, it is getting slower. Can somebody please suggest me what should be done to avoid StackOverflowError with no decrease in time.
Thanks!
Comment: The lineage becomes very deep and thus inefficient. You could try to `checkpoint` to truncate the lineage (in Spark 2). Alternatively, you could write all individual dataframes to disk (e.g. in a table which is partitioned by filename)...
Answer: The issue is that spark manages a dataframe as a set of transformations. It begins with the "toDF" of the first dataframe, then perform the transformations on it (e.g. withColumn), then unionAll with the previous dataframe etc.
The unionAll is just another such transformation and the tree becomes very long (with 11K unionAll you have an execution tree of depth 11K). The unionAll when building the information can get to a stack overflow situation.
The caching doesn't solve this, however, I imagine you are adding some action along the way (otherwise nothing would run besides building the transformations). When you perform caching, spark might skip some of the steps and therefor the stack overflow would simply arrive later.
You can go back to RDD for iterative process (your example actually is not iterative but purely parallel, you can simply save each separate dataframe along the way and then convert to RDD and use RDD union).
Since your case seems to be join unioning a bunch of dataframes without true iterations, you can also do the union in a tree manner (i.e. union pairs, then union pairs of pairs etc.) this would change the depth from O(N) to O(log N) where N is the number of unions.
Lastly, you can read and write the dataframe to/from disk. The idea is that after every X (e.g. 20) unions, you would do df1.write.parquet(filex) and then df1 = spark.read.parquet(filex). When you read the lineage of a single dataframe would be the file reading itself. The cost of course would be the writing and reading of the file.
Comment: I am new to spark and still very confused. can you please provide a code of Union in tree manner and how parquet will work with this parallel iteration? Thanks @AssafMendelson
Comment: Don't have code available off hand, but the idea is that you loop through the vector of dataframes doing a union: df(i).union(df(i+1)). This would result in a vector with half the number of elements. Then repeat this process until you get one dataframe.


How to get the single user profile from UPS using powershell?

Question: I am new to Powershell world. I want to fetch the single user data from the UPS using Powershell instead of looping through each and every user in the UPS.
I followed  this also. Here they are comparing Email with UPS Email and then they are fetching the profile of matched Email in UPS.
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$emailAddress = "EMAIL ADDRESS YOU WISH TO QUERY"
$site = Get-SpSite $mySitesURL;
$context = Get-SPServiceContext $site;
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$allProfiles = $profileManager.GetEnumerator()
foreach ($profile in $allProfiles) {
    if ($profile.GetProfileValueCollection("WorkEmail") -eq $emailAddress) {
        $profile
    }
}

Answer: I think this is what you are looking for. Try this:
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$emailAddress = "EMAIL ADDRESS YOU WISH TO QUERY"
$site = Get-SpSite $mySitesURL;
$context = Get-SPServiceContext $site;
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$userProfile  = $profileManager.GetEnumerator()| Where-Object {$_["WorkEmail"].value -like $emailAddress}

It will fetch only single user data based on the $emailAddress. You don't need to loop through each and every user profile in UPS.
Comment: No problem @SMD :)


Does Bertrand's Postulate give us the tightest proven upper bound for prime gaps?

Question: Bertrand's Postulate asserts that there is a prime between $n$ and $2n$.
Is this the best such upper bound on prime gaps known today, or have  stronger estimates been proved? I mean results of the kind:

there will always be a prime between $n$ and $2n-2$, or
there will always be a prime between $n$ and $cn$ with $1<c<2$?

Was any such improvement proved rigorously, or is Bertrand's Postulate still the best we have?
Comment: You can read [Wikipedia](https://en.wikipedia.org/wiki/Bertrand%27s_postulate). There is no reason to ask such a question here.
Comment: There is a nice proof of this from the book "Proofs from the book", which is elementary and you might like.
Answer: Yes. See theorem 3 of:
O. Ramar´e, Y. Saouter, Short effective intervals containing primes, J. Number Theory 98 (2003),
no. 1.
A related statement states for all $\epsilon > 0$, for sufficiently large $n$, there is a prime between $n, (1+ \epsilon)n$ which is a trivial corollary of the PNT.
For your first question, both of those statements have been proven.
Comment: "sufficiently large" makes this a non-generalisation of Bertrands postulate.
Comment: @JeffreyYoung: Far from it. The next prime is at most 1.000000000000000025k (Dusart 2010), and probably a lot closer than that. Apparently the result of Baker-Harman-Pintz could be made effective and that would give a much better gap, more like $(1+10^{-9148214})k$, but we don't have that yet. And far better is conjectured, more like $(1+3.11\cdot10^{-17425155})k$.
Comment: What about my second question? All known primes gaps have been observed to be smaller than n or n-2, with maybe the exception of the largest known prime.
Comment: Have you looked at the reference? And what do you mean by "with maybe the exception of the largest known prime"?
Comment: @MayankPandey From the largest known prime to the next prime, what is the distance? Let k be the largest known prime. Let u be the next consecutive prime, which is currently unknown. Will u be only slightly less than 2k?
Comment: I should have said that all known prime gaps are significantly smaller than that which is allowed by Bertrand's postulate. However, we do not know concerning any prime gaps following the largest known prime as to whether they will be as large as Bertrand's postulate will allow or if Legendre's conjecture will hold true.


How should the GridView/ListView with images be handled to avoit memory leaks, if any?

Question: Scenario:

A Fragment
A gridview which displays images from external-storage/downloads from the web
An Adapter for the gridview which uses an xml layout containing an ImageView and a TextView inside a FrameLayout
Inside getView the adapter downloads the image and sets it as resource for the bitmap

After the user is done with the fragment, the fragment is removed.
My concern:
We all know that android is prone to OoM errors, especially when working with bitmaps, even if when they are scaled down.
When the fragment is removed, like onPause should I parse all the items of the GridView and:

remove callbacks for image drawable
recyle the bitmpa drawable ?

Is this needed to prevent memory leaks ?
Comment: I would take a look at lazy-loading the images with something like this: http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_Example/index.php?view=article_discription&aid=112&aaid=134  It should handle all of the stuff you're worried about
Answer: If you don't need a full size image, I recommend you to use sampled images.
  options.inSampleSize = calculateInSampleSize();
  options.inJustDecodeBounds = false;

And I use the following tricky code in my own project on decoding files to bitmaps.
  public static Bitmap decodeFile(String pathName, BitmapFactory.Options opts) {
    for (int i = 0; i < 5; ++i) {
      try {
        return BitmapFactory.decodeFile(pathName, opts);
      }
      catch (OutOfMemoryError e) {
        System.gc();// Retry with running gc.
      }
    }
    return BitmapFactory.decodeFile(pathName, opts);
  }

Comment: System.gc(); doesn't force the system to garbage collect immediately, and the JVM can even ignore it, so immediately trying to decode it again outside of the try/catch after it's failed will almost definitely result in the same OutOfMemoryError being thrown again. He's way better off calculating the inSampleSize before decoding it so that he doesn't (or, more accurately, is far less likely to) run into the issue in the first place.
Comment: Thanks for your answer, but this is not about how I load the images, but how to manage them when the list gets destroyed.
Answer: As I said, my main concern was related to usage of already scaled down bitmaps, but in the same time handling a lot of memory caching of other images. This could be a problem for instance on big screen devices, where an image can be scaled to 1080px and its footprint in memory is not small. I also had to stack some fragments containing images for future use.
This forced the app to run into out of memory after a while. The fix I applied for now is to allow large memory use by android:largeHeap="true"
Comment: From https://developer.android.com/training/articles/memory.html#CheckHowMuchMemory : Using the extra memory will increasingly be to the detriment of the overall user experience because garbage collection will take longer and system performance may be slower when task switching or performing other common operations.


Is Transformer multi-headed attention a form of ensemble?

Question: In Transformer, is it correct to say that multi-headed attention is an ensemble learning and each head is learning a different capability by below?

independent random weight initialization for each head and
attending only to 512/8 dimension per head (where 8 is number of heads)

If incorrect, please help correct what is incorrect?
References
Attention Is All You Need

3.2.2 Multi-Head Attention
Instead of performing a single attention function with dmodel-dimensional keys, values and queries,
we found it beneficial to linearly project the queries, keys and values h times with different, learned
linear projections to dk, dk and dv dimensions, respectively. On each of these projected versions of
queries, keys and values we then perform the attention function in parallel, yielding dv-dimensional
output values. These are concatenated and once again projected, resulting in the final values, as
depicted in Figure 2.

Transformers Explained Visually (Part 3): Multi-head Attention, deep dive

What is different in each head of a multi-head attention mechanism?
Comment: ensemble usually is associated with "taking N high variance predictors, and increasing the bias taking as prediction some combination of the N predictors output", for example the majority or the mean.... here there is no notion of "reducing the variance", actually it's probably the other way around... increasing the heads is used to increase the variance, in order to capture multiple connections (IMO)
Answer: I would not say so. The idea behind ensembles is that the errors ML models make are in part systematic and in part random. When we train different classifiers for ensembling, we assume that the random part of the error will zero out and will get a better result. All the models in the ensemble do the same thing, but with a different random error.
The intuition behind multi-headed attention is quite the opposite. It is there to allow each head to focus on a different type of information in the attention input representation. In NLP, there is a lot of literature on what the attention heads do: they can look at syntactically related words, some heads can look at surrounding words, and some heads can emulate coreference chains (see e.g., Chapter 5 of this book). When trained correctly, each head should do a different thing.


Changing org-mode link color

Question: When I add a link within an org-mode heading, is it possible have the link color match the rest of the text in the heading?
Comment: See also [this](https://stackoverflow.com/questions/19057881/customize-color-of-internal-links-orgmode) question on how to customize the color of org-mode links.
Answer: You can make the color of org links always match the text in which they are found, but you can't do that conditionally based on whether they are within headings. If that's good enough for your needs, try:
M-x customize-face RET org-link RET
then remove the 'foreground' specification for the face.
Comment: I also had to remove the inherit specification as well before I saw any effect, although the links still do not have the same color as the surrounding text. I've added this to my .emacs: `(custom-set-faces  '(org-link ((t (:underline t)))))`

Changing org-mode link color


Is it bad practice to use informal arguments when evaluating limits?

Question: I often see slightly informal ways of evaluating limits. For example:
$$\lim_{x\to\infty} \frac{1+\frac{\sin(x)}{x}+\frac{x}{e^x}}{3+\frac{1}{x}} = \frac{1+0+0}{3+0} =\frac{1}{3}$$
I think this is not a proof, rather a bit of an sketchy argument.
Is it bad practice to evaluate limits like this? Or is it okay?
Comment: In this case you're applying known theorems
Comment: I'd say this depends on the audience. If you are going to start the first lesson of an undergraduate course like that, then yes, it would be bad practise. If you, on the other hand, would start to give detailed explanations on why this particular example is evaluated like this in a mathematical paper in some distinguished math journal, that would be bad practise, too...
Comment: An intermediate step would be to put $lim$ in front of each term in the num and denom. How formal does it have to be? I don't think it is a bad practice since all limits of individual terms exist, which is of course a necessary condition, but I am sure you already knew that :) Want to have a proof, perhaps then epsilon delta?
Answer: No, you just explain the properties used to calculate this limit: arithmetic laws, etc.


Make Gojs FlowCart working on AngularJS

Question: For my current project, I'm using this amazing library "GoJS", that offers many awesome diagrams.
The problem is that the library is based on Javascript, and does not have any AngularJS wrapper.
The only angular code I found, is the based diagram http://gojs.net/latest/samples/angular.html
For my project, I need to use FlowChart http://gojs.net/latest/samples/flowchart.html.
I've tried to wrap it into a directive, but without any luck.
So, that's way I'm asking your help today, to provide me with a solution to easily integrate the diagram into my angulaJS app, or provide me with any wrapper that can work without any issue.
Thanks
Comment: juz a marker, even I am looking towards, the same for a sample to learn.. Is it possible.. I am starting..
Comment: Did you find a way to implement it? If yes, please post your solution!
Answer: You should be using the GoJS Angular Component. The gojs-angular-basic project is an example using it.

Make Gojs FlowCart working on AngularJS


Given a signal in the time domain, is there a way to determine a function that produces that signal?

Question: Disclaimer: I'm by no means an expert in any of this, and I'm just wondering whether a solution to this problem already exists.
Using a raw audio waveform as an example, let's say you have a 1:00m long audio buffer, sampled at 44100 Hz, that is just a simple sine wave with a constant frequency of 500 Hz and a constant amplitude of 1.  Just by looking at this data, you can assume that the value of any sample can be found using the equation $v(t) = sin(500 * t)$, where $v(t)$ is the value of the sample and $t$ is the time, in seconds, since the start of the waveform (determined using the ratio of the sample position to the sample rate).  Lacking this assumption, however, you could in theory compute the spectrum via a Fourier Transform and find a point on that spectrum where the slope is 0 and the slope in either direction is positive and negative, respectively, in order to determine the frequency of the single partial (this is of course ignoring any partials generated by the existence of a noise floor).  You could then use this data to determine the previously mentioned assumption is true, and model the signal using that function rather than keeping track of the signal using a data table.  Not only that, you could continue this signal beyond the scope of the table indefinitely assuming that its nature is constant.
Can the same thing be done for more complex signals whose partials are much more numerous and change in amplitude and frequency over time?  Based on what I know about Fourier, any function can be modeled using sine waves of various frequencies with constant amplitudes, so while the function generated from this analysis might not say anything useful about the nature of the signal, it can at least be generated at all, right?
Comment: http://en.m.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem  is relevant
Comment: *Can the same thing be done for more complex signals whose partials are much more numerous and change in amplitude and frequency over time?* Sure, I used to own a Kawai K5000 synthesizer which worked based on this principle. It was a notoriously difficult to program! http://en.wikipedia.org/wiki/Additive_synthesis
Answer: I found a paper which seems to answer this question pretty thoroughly.  It's mainly related to the Nyquist-Shannon sampling theorem linked by Evan, the difference here being that the main focus of the article is on function reconstruction rather than sampling theory.


the question is to solve the ordinary differential equation $x=py-p^2$ where p=$\left(\frac{dy}{dx}\right)$

Question: I have tried the 3 methods of :

solving for $x$,
solving for $y$, and
solving for $p$, where $p$ is $\left(\frac{dy}{dx}\right)$.

In each of the above form, i could not get the solvable equation.
I am also not able to find the suitable substitution to modify it to the Clairaut's Form
I need a direction to proceed.
Comment: Are you familiar with d'Alembert's equation?
Comment: @Αδριανός, I got it. Thank you.
Comment: @K.K.McDonald, I got it. Thank You.
Comment: thanks to @Αδριανός. method of solving is in here https://en.wikibooks.org/wiki/Ordinary_Differential_Equations/d'Alembert
Answer: Differentiate the given equation w.r.t $x$,
     $$\dfrac{dx}{dy} = p + y\dfrac{dp}{dy} - 2p\dfrac{dp}{dy}$$
     i.e. $$\dfrac{1}{p} = p + y\dfrac{dp}{dy} - 2p\dfrac{dp}{dy}$$
     From this we get a linear differential equation of the following form:
     $$\dfrac{dy}{dp} + \dfrac{p}{p^2 - 1}y = \dfrac{2p^2}{p^2 - 1},$$
     This is a linear ordinary differential equation of first order and first degree and can be solved easily.
Comment: Welcome to MSE. Please use MathJax to format expressions.
Answer: $x=y\dfrac{dy}{dx}-\left(\dfrac{dy}{dx}\right)^2$
$\left(\dfrac{dy}{dx}\right)^2-y\dfrac{dy}{dx}+x=0$
Apply the method in http://www.ae.illinois.edu/lndvl/Publications/2002_IJND.pdf#page=2:
Let $F(x,y,t)=t^2-yt+x~,$
Then $\dfrac{dy}{dt}=-\dfrac{t\dfrac{\partial F}{\partial t}}{\dfrac{\partial F}{\partial x}+t\dfrac{\partial F}{\partial y}}=-\dfrac{t(2t-y)}{1+t(-t)}=\dfrac{2t^2}{t^2-1}-\dfrac{ty}{t^2-1}$
$\dfrac{dy}{dt}+\dfrac{ty}{t^2-1}=\dfrac{2t^2}{t^2-1}$
$y=t+\dfrac{\ln(t+\sqrt{t^2-1})+C_1}{\sqrt{t^2-1}}$
$\therefore\dfrac{dx}{dt}=-\dfrac{\dfrac{\partial F}{\partial t}}{\dfrac{\partial F}{\partial x}+t\dfrac{\partial F}{\partial y}}=-\dfrac{2t-y}{1+t(-t)}=\dfrac{2t}{t^2-1}-\dfrac{y}{t^2-1}=\dfrac{t}{t^2-1}-\dfrac{\ln(t+\sqrt{t^2-1})+C_1}{(t^2-1)^\frac{3}{2}}$
$x=\int\biggl(\dfrac{t}{t^2-1}-\dfrac{\ln(t+\sqrt{t^2-1})+C_1}{(t^2-1)^\frac{3}{2}}\biggr)dt=\dfrac{t(\ln(t+\sqrt{t^2-1})+C_1)}{\sqrt{t^2-1}}+C_2$
Hence $\begin{cases}x=\dfrac{t(\ln(t+\sqrt{t^2-1})+C_1)}{\sqrt{t^2-1}}+C_2\\y=t+\dfrac{\ln(t+\sqrt{t^2-1})+C_1}{\sqrt{t^2-1}}\end{cases}$
Answer: First differentiate w.r.t $x$ ,we get
$$\frac{dx}{dy}=p+y\frac{dp}{dy} -2p \frac{dp}{dy}$$
Now solve for $\frac{dy}{dp}$ using linear differential equation
Comment: Welcome to MSE! Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to make your answer easier to read.
Answer: The equation $F(x,y,p)=py-p^2-x$ can be solved for $p$ outside the singular set $0=F_p=y-2p$, that is, $(x,y)=(p^2,2p)$. This results in the differential equations
$$
y^2-4x=(2p-y)^2\implies y'=p=\frac12\left(y\pm\sqrt{y^2-4x}\right)
$$
which can be used to obtain numerical solutions. No integration tricks are immediately obvious.

One other approach is to use $p$ as parameter of the solutions wherever $p=y'$ is not constant.
For the lines $y'=p=c=const.$ the given equation results in $x=cy-c^2$. By differentiation this gives the condition $1=cy'=c^2$ so that only $c=\pm 1$ give solutions.
Outside these lines one can take $p$ as parameter, denote $\dot x=\frac{dx}{dp}$, $\dot y=\frac{dy}{dp}$. By the chain rule, $\dot y=p\dot x$. Taking the derivative by $p$ of the original equation and multiplying with $p$ gives
$$
\dot y=p\dot x=p(y+p\dot y-2p)\implies \dot y=\frac{py-2p^2}{1-p^2}
$$

For $|p|<1$ parametrize $p=\sin u$ so that
$$
\frac{d}{du}(\cos u\, y(\sin u))=\cos^2u\,\dot y(\sin u)-\sin u\, y(\sin u)=-2\sin^2u=\cos(2u)-1
$$
which integrates to
$$
\cos u y(\sin u)=C+\sin u\cos u-u.
$$
This gives, inserting this last equation in the original ODE, a parametrization
$$
\pmatrix{x\\y}=\pmatrix{(C-u)\tan u\\\sin u+\frac{C-u}{\cos u}}, ~~~ u\in(-\frac\pi2,\frac\pi2)
$$

For $p>1$ (and similarly for $p<-1$) parametrize $p=\cosh u$ so that $1-p^2=-\sinh^2u$ and
$$
\frac{d}{du}(\sinh u\,y(\cosh u))=\sinh^2u\,\dot y(\cosh u) + \cosh u y(\cosh u)
=2\cosh^2u=\cosh(2u)+1
$$
which integrates to
$$
\sinh u\,y(\cosh u)=C+u+\sinh u\,\cosh u.
$$
This gives, inserting this last equation in the original ODE, a parametrization
$$
\pmatrix{x\\y}=\pmatrix{(C+u)\coth u\\\cosh u+\frac{C+u}{\sinh u}}, ~~~ u\in(0,\infty)
$$

Comparing the parametrizations with numerical solutions confirms their correctness

Plotted in dark and light gray are the first and second parametrizations, red and blue are numerical solutions for both signs of the square root. Note that while the parametrizations pass resp. "are reflected at" the singular set (in yellow), the numerical solutions end there, there is no differentiable extension available.


Comparison / Selection of covariance structures - linear mixed model in SPSS

Question: Hi together,
I am currently trying to build a linear mixed model with repeated measurements in SPSS. I would expect that the correlation between my measurements is highest at adjacent time points, so my guess was that AR1 (autoregressive structure) is the right covariance structure in my case.
My syntax for this first model (model1) is:
MIXED measurement BY female meadiansplit time WITH age
  /CRITERIA=DFMETHOD(SATTERTHWAITE) CIN(95) MXITER(100) MXSTEP(10) SCORING(1)
    SINGULAR(0.000000000001) HCONVERGE(0, ABSOLUTE) LCONVERGE(0, ABSOLUTE) PCONVERGE(0.000001, ABSOLUTE)
  /FIXED=female mediansplit time age mediansplit*time | SSTYPE(3)
  /METHOD=ML
  /REPEATED=time | SUBJECT(study_id) COVTYPE(AR1)
As a comparison to this I also calculated a second model (model2) which is exactly the same like model1 but with an unstructured (UN instead of AR1) covariance structure.
(dependent = measurement;
factors = female, mediansplit (median split of a scale, coded as 1 for the upper half and 0 for the lower half), time (7 time points);
covariate=age in years (used as covariate as it is a continuous variable))
Model1: -2LL = -563, AIC= -527, parameters 18
Model2: -2LL = -701, AIC= -613, parameters 44
Difference -2LL: 138, difference parameters: 26
--> Model2 seems to fit better (p=0,01), although it includes way more parameters and has not the expected covariance structure. Unfortunately, there are also differences in the significance of my fixed effects. While the interaction of median split and time (which is of great importance to me) is significant in model1, it is not in model2.
Which model is the better one in this case? Model1 with less parameters and the expected covariance structure or model2 with more parameters but a better model fit?
Thanks!
Answer: It is not possible to give a definitive answer without accesss to the data itself, and even with access to the data it still might not be possible. However, we can say a few things about this situation.

Given that you expect high autocorrelation, I would suggest sticking with the first model.

The 2nd model, which has many more parameters, may very well be over-fitting the data, which results in an, apparent, better fit.

You could explore the previous point by using the same model to make predictions on a new dataset, or by splitting the dataset if you don't have access to new data.
Comment: Does this answer your question ? If so, please consider marking it as the accepted answer, or if not please let us know why so that it can be improved.


How do I make a script that cleans up objects from one document if they don't exist in another?

Question: I have the following two collections, Player and Team. These two collections each contains lots of documents. Here is an example with some dummy data:
Player
_id: ObjectId('6098c5ab615d9e23543d0f6e'),
name: 'Frank',
age: 27,
position: 'striker'

_id: ObjectId('61409537c4f113354782eea3'),
name: 'Jan',
age: 19,
position: 'midfielder'

Team
_id: ObjectId('61961ce8981cfc332fd71711'),
name: 'Team A',
players: [
    {
        refId: ObjectId('6098c5ab615d9e23543d0f6e'),
        goals: 13
    },
    {
        refId: ObjectId('61409537c4f113354782eea3'),
        goals: 6
    },
    {
        refId: ObjectId('61fcfb7d0fcb4d4c284bdefa'),
        goals: 2
    }
]

_id: ObjectId('61fd27c152d4a56752b8f05c'),
name: 'Team B',
players: [
    {
        refId: ObjectId('6218a8af0486c46703414aba'),
        goals: 2
    },
    {
        refId: ObjectId('61409537c4f113354782eea3'),
        goals: 1
    }
]

_id: ObjectId('56fd77c152d4a56752b8y89h'),
name: 'Team C',
players: [
    {
        refId: ObjectId('6413780af746f734b8720e5e'),
        goals: 9
    },
    {
        refId: ObjectId('6413781fab3a6458779aaa3f'),
        goals: 0
    }
]

I'm trying to make a clean up script that goes through all docs in my Team collection and pulls out the object if players.refId no longer exists in the Player collection. how can I do this?
So after the cleanup the teams would look like this:
_id: ObjectId('61961ce8981cfc332fd71711'),
name: 'Team A',
players: [
    {
        refId: ObjectId('6098c5ab615d9e23543d0f6e'),
        goals: 13
    },
    {
        refId: ObjectId('61409537c4f113354782eea3'),
        goals: 6
    }
]

_id: ObjectId('61fd27c152d4a56752b8f05c'),
name: 'Team B',
players: [
    {
        refId: ObjectId('61409537c4f113354782eea3'),
        goals: 1
    }
]

_id: ObjectId('56fd77c152d4a56752b8y89h'),
name: 'Team C',
players: [
]

So far I have this:
db.Team.aggregate([
    { $unwind: "$players" },
    {
        $lookup: {
            from: "Player",
            localField: "players.refId",
            foreignField: "_id",
            as: "player"
        }
    },
    { $match: { player: { $size: 1 } } },
    {
        $group: {
            _id: "$_id",
            players: { $push: "$players" }
        }
    },
    { $project: { _id: 1, players: 1 } },
    { $merge: { into: "Team", on: "_id", whenMatched: "merge" } }
])

This solution works as long as there are at least one player in each team that exists in the players collection. When a team only has players that does not exist in the players collection, they are not cleaned up because { $match: { player: { $size: 1 } } } filters them away. How do I solve this?
Comment: please make an attempt (and share [mcve]) before asking for help
Answer: db.Team.aggregate([
  // Unwind the players array
  { $unwind: "$players" },

  // Lookup the player in the Player collection
  {
    $lookup: {
      from: "Player",
      localField: "players.refId",
      foreignField: "_id",
      as: "player"
    }
  },

  // Filter out players that don't exist in the Player collection
  { $match: { player: { $size: 1 } } },

  // Group the players back into an array and replace the original players array
  {
    $group: {
      _id: "$_id",
      name: { $first: "$name" },
      players: { $push: "$players" }
    }
  },

  // Project only the necessary fields
  {
    $project: {
      _id: 1,
      name: 1,
      players: {
        refId: 1,
        goals: 1
      }
    }
  }
])

Comment: Unfortunately your solution does not work. In the scenario of `Team C` where none of the players exist in the `Players` collection, it does not clean up the document. The `$match` stage is where it goes wrong.
Answer: There is more than one way to do this:
First, there is a unwind/lookup/filter/group as in answer 1 (I think the match needs a small fix though (see my comment above).
I've stumbled onto a slightly better solution.
     // first get the player id's into one array
    [{$addFields: {
        player_id: {$map: {
           input: '$players',
            in: '$$this.refId'
           }}
    }},
{
    '$lookup': {
      'from': '$Players',
      'let': {
        'lst': '$player_id'
      },
      'pipeline': [
        {
          '$match': {
            '$expr': {
              // using indexOfArray, so a missing player is -1
              // and an existing player has an index gt -1
              '$gt': [
                {
                  '$indexOfArray': [
                    '$$lst', '$_id'
                  ]
                }, -1
              ]
            }
          }
        },
        {
          '$sort': {
            'name': 1
          }
        }
      ],
      'as': 'x'
    }
  }]

I did this on my own data and changed the variable names since you didn't provide enough data for the test try mongoplayground
Comment: I'm not trusted enough to comment, but the test for match should be
{$match: {player: {$ne: null}}


Typescript, require either of two function signatures

Question: I'm working with a library that gives me a a callback, which expects either an error as it's first argument, or null as an error and a value as it's second argument.
I'm trying to encode this with a type, so typescript will validate that I'm for example not passing in both a error and a value, or neither of them.

type Callback = {
  (error: undefined, value: string): void;
  (error: Error): void;
}

function doThings(c: Callback) {
    // Valid, no error, and a useful value.
    c(undefined, '1');
    // Valid, something went wrong, so we pass in an error, but no value.
    c(new Error());

    // Invalid. Since there's no value, there must be an error.
    c(undefined);
    // Invalid, there's both an error and a value.
    c(new Error(), '1');
}

function c1(error: undefined, value: string) { }

function c2(error: Error) { }

doThings(c1)
doThings(c2)
Comment: I'm confused by this question. The above code ends up calling both `c1(new Error())` and `c2(undefined, `1`)`.  Is that intentional?  Do you want the above to throw an error at runtime?  Or an error at compile time?  Or work?
Comment: I have updated the code with samples of what I want to work, and what I want to yield errors, hopefully this clears things up.
Comment: Your definition of `Callback` and `doThings()` is exactly as you want it to be, but I still don't understand why you would want to call `doThings()` on `c1` or `c2`.  Have you considered what the effect of calling `doThings(c1)` would be?  `c1` is a function that expects its first argument to be `undefined`, and its second argument to be a `string`.  But inside `doThings()`, a valid use of `c` is `c(new Error())`. This ends up calling `c1(new Error())`, *which will break*.  So `doThings(c1)` and `doThings(c2)` are *correctly* flagged as errors by the compiler.
Answer: As far as I can tell, your definition of Callback is exactly as you want it to be.  Callback is a function that can be called with arguments (error: undefined, value: string).  It is also a function that can be called with arguments (error: Error). A valid Callback must support being called in both of those ways.
To reiterate, this is just fine:
type Callback = {
  (error: undefined, value: string): void;
  (error: Error): void;
}

function doThings(c: Callback) {
    c(undefined, '1');  // okay
    c(new Error()); // okay
}

And the TypeScript compiler doesn't report any errors there, which is good.

The part that seems to be a problem is that you then go ahead and define two functions, neither of which conforms to the Callback specification.  Let's look at them.  First:
function c1(error: undefined, value: string) {
   // some impl which expects value to be a string, e.g.,
   value.charAt(0);
};
doThings(c1); // error, as expected

This function requires two arguments.  You cannot call it with arguments (error: Error).  So the call doThings(c1) is an error by the compiler, which is exactly what you want.  The compiler error tells you that c1 is not a Callback.  If you force the compiler to allow it with type assertions or other trickery, everything will be fine at compiler time, and then at runtime doThings(c1) will end up calling c1(new Error()), which, assuming that c1 does string-like stuff with its value argument (as I showed above), ends up throwing an error like Error: undefined has no properties.
Similarly:
function c2(error: Error) {
  // some impl which expects error to be an Error, e.g.,
    console.log(error.message);
 };
 doThings(c2); // error, as expected

This function requires that the first argument be an Error.  You cannot call it with arguments (error: undefined, value: string).  So the call doThings(c2) is an error by the compiler, which is exactly what you want.  The compiler error tells you that c2 is not a Callback.  If you force the compiler to allow it with type assertions or other trickery, everything will be fine at compiler time, and then at runtime doThings(c2) will end up calling c2(undefined, '1'), which, assuming that c2 does Error-like stuff with its error argument (as I showed above), ends up throwing an error like Error: undefined has no properties.

So neither c1 nor c2 are valid Callback objects.  If you want to make a valid Callback, you can do it.  One way is to make a more specific function type, like so:
function cSubtype(error: undefined | Error, value?: string) {
  if ((typeof error === 'undefined') && (typeof value === 'string')) {
    c1(error, value);
  } else if ((typeof error !== 'undefined') && (typeof value === 'undefined')) {
    c2(error);
  } else console.log('I got some other arguments');
}
doThings(cSubtype); // okay

The cSubtype function is more specific than a Callback, in that it accepts more general parameters. (Function parameters vary contravariantly, meaning that the more general/wider you make function parameters, the more specific/narrower you make the function type.)  It accepts arguments like (error: undefined, value: string) as well as (error: Error).  It also accepts (error: Error, value: string) and (error: undefined).  But you can still pass cWider to doThings, because cWider is a subtype of Callback, just like a {a: string, b: boolean} can be passed to something expecting a {a: string}.
Another way you can do this is just to define an overloaded function which behaves exactly as you want a Callback to behave.  It still needs an implementation signature which is more general, but it cannot be called with the implementation signature (read the link about overloads for more info).  Here's an example:
function cOverload(error: undefined, value: string): void; // signature1
function cOverload(error: Error): void; // signature2
function cOverload(error: undefined | Error, value?: string) { //impl
  if (typeof value !== 'undefined') {
    c1(undefined, value);
  } else {
    c2(error!);
  }
}
doThings(cOverload);  // works

Does that make sense?  Hope it helps.  Good luck.
Answer: You can use a combination of sum and intersection types to achieve this:
type ValueCallback = (error: undefined, value: string) => void;
type ErrorCallback = (error: Error) => void;
type Callback = (ValueCallback | ErrorCallback) & ((error: Error | undefined, value?: string) => void);

function doThings(c: Callback) {
  c(undefined, "1");
  c(new Error());
}

function c1(error: undefined, value: string) {}
function c2(error: Error) {}

doThings(c1);
doThings(c2);

The intersection part is needed so you can actually call the function inside doThings, without that it doesn't find a compatible call signature.
Comment: Could also use several signatures on `doThings` so as to keep the `((error: Error | undefined, value?: string) => void)` signature of the callback hidden ...
Comment: Thanks, unfortunately this allows both `c(undefined)` and `c(new Error(), '1');` as well as the correct forms, which would break my contract with the library giving me the callback.
Comment: This isn't really possible, but not because TS but because it is inherently unsafe. The way you declared `Callback` in the original post is actually fine but then the callbacks need to have a signature of `function c2(error: Error | undefined, value?: string)`. If you think about it this makes sense: `c2` might be invoked with `Error` being undefined so you'll have to handle that case _somehow_.


Unable to run ASP.NET web application in MEDIUM trust level

Question: I developed an Web Application and published it on my Shared Hosting. After that I am receiving following error-

To resolve it, I contacted my hosting providers and they told me to set my application to run in Medium Trust and to contact with my developer (that is me this case :P).
Now, I added <trust level="Medium" /> in my web.config file and it is not even running on my local machine now.
After many research I thought to test this feature with brand new project-

Created a brand new ASP.NET MVC project and set trust level to Medium. (No success)
Created another project as empty. Added a default.aspx page and set the trust level to Medium (No success again).

Now I am unsure how to resolve this.
Any help will be much appreciated!
Comment: Have you find the answer? I have the same problem as well. http://stackoverflow.com/questions/41974750/system-security-permissions-fileiopermission-error-when-trying-to-upload-a-file
Answer: MVC5 does not support medium trust. Either use MVC4 or change trust level to full. There are several posts related to this issue.


How to log an error from a catch block and at the same time rollback the transaction?

Question: BEGIN TRANSACTION
    BEGIN TRY
        --DO_ACTION
        --COMMIT_TRANSACTION
    END TRY
    BEGIN CATCH
        --LOG_ERROR (e.g. INSERT INTO ErrorTable (ERROR_MESSAGE(), ...))
        --ROLLBACK
    END CATCH

I'm trying to do the following however, the ROLLBACK command is rolling back the logging of my error so the "ErrorTable" does not have anything in it.
How would I go about doing what I want to do in this situation?
Comment: Did you try switching the order of the statements. Rollback first then log?
Comment: im trying to capture ERROR_MESSAGE() as well. ill try to change the order now.
Comment: @Icarus, that worked. I switched the items. I roll back first, then log the error. thanks!
Answer: What you want to log in ErrorTable? If it is data, which not available yet after rollback, you can keep that in table variable, then insert into ErrorTable after rollback. The table variables not participate in transactions.


Why is $\nabla u (r\cdot 0) = r\nabla u (0)$ true for a harmonic function $u$?

Question: I've stumbled across an older post here trying to solve the same problem the asker of the post had. The solution that was provided stated that for a harmonic function $u$ on $\mathbb{R}^n$ we have that $\nabla u (r\cdot0) = r\nabla u (0)$ for any $r > 0$. I'm not quite sure that this is true. Here's a counter example that I found:

$u((x,y)) = e^x \sin(y)$ is harmonic
$\nabla u((x,y)) = \begin{pmatrix}
e^x \sin(y) \\
e^x \cos(y)
\end{pmatrix}
$
$\nabla u((r\cdot 0,r\cdot 0)) = \begin{pmatrix}
0 \\ 1
\end{pmatrix} \neq r\begin{pmatrix}
0 \\ 1
\end{pmatrix} = r\nabla u((0,0))$

Am I missing something or is the claim indeed wrong?
Answer: You probably got the defintion of $u_r$ wrong. $u_r(x,y)=e^{rx}\sin (ry)$ and $\nabla u_r(0,0)=(0,r)$ and not $(0,1)$
Comment: Oh, my bad. Thanks a lot!