R data.table .SD unexpected behaviour

Question: I was trying to calculate some basic statistics of a data table and I've come to this (for me) unexpected behaviour.
If I calculate using  everything using "explicit" indexes everything works as expected as in the following example:
library(data.table)
n <- 100; reps <- 6; n1 <- 2
df <-  as.data.frame(cbind(matrix(seq_len(n*n1), ncol=n1),
      matrix(sample(0:1000, n*reps, replace=TRUE), ncol=reps)))
dt <- data.table(df)

dtmean <- dt[, lapply(.SD[,c(seq(2,5))], mean, na.rm=TRUE), by=c("V1")]

but if I use
a=2
b=5

dtmean <- dt[, lapply(.SD[,c(seq(a,b))], mean, na.rm=TRUE), by=c("V1")]

the results is not what I expect (previous lines)
Is this intentionally how data.table should work?
so the first part of code for n=10 gives
   V1  V3  V4  V5  V6
 1:  1 504 399 430 564
 2:  2 547 294 274 700
 3:  3 555 305 781 326
 4:  4 144 840 983 221
 5:  5 894 659 169  38
 6:  6 788 289 598 433
 7:  7 810 378  86  22
 8:  8 848 212 701 565
 9:  9 412 707 890 160
10: 10  82 580 927 607

while the second
    V1 V1 V2 V3 V4
 1:  1  2  3  4  5
 2:  2  2  3  4  5
 3:  3  2  3  4  5
 4:  4  2  3  4  5
 5:  5  2  3  4  5
 6:  6  2  3  4  5
 7:  7  2  3  4  5
 8:  8  2  3  4  5
 9:  9  2  3  4  5
10: 10  2  3  4  5

shouldn't they give me same results?
the function mean here does not calculate anything since V1 has all different values, the question is about selecting of the indexes, I don't understand why they work in different ways.
Comment: `dt[, lapply(.SD[,seq(a,b),with=FALSE], mean, na.rm=TRUE), by=c("V1")]` *works*. I'm *guessing* that `data.table` thinks `a` and `b` should represent variables inside the `.SD` environment, so preventing that behavior *within `.SD`* is the key. I don't know if it is truly intentional that `seq(2,5)` works and `seq(a,b)` does not, but the `with=` definitely side-steps the issue here.
Comment: BTW, `dt[, lapply(.SD[,a:b], mean, na.rm=TRUE), by=c("V1")]` also works (`a:b`, no `with=`). I think it's definitely a corner-case of NSE within `data.table`. I don't know if it's a bug, I'm hoping one of the `data.table` devs can inform the discussion. (If not, it might do well to bring this up as an [issue](https://github.com/Rdatatable/data.table/issues/).)
Comment: What exactly are you taking `mean` of? From your output it seems you are just selecting columns. `dt[, c(1, 3:6)]`
Comment: please see the edited question
Answer: You should use .SDcols to control what's included in .SD in this case:
dtmean <- dt[, lapply(.SD, mean, na.rm=TRUE), by="V1", .SDcols=seq(a,b)]

To do it your style, you should use with=FALSE on the inner .SD call:
dtmean <- dt[, lapply(.SD[, seq(a,b), with=FALSE], mean, na.rm=TRUE), by=c("V1")]

.SD is itself a data.table, so [ has the same semantics, i.e., the issue is the same as the difference between
dt[ , seq(a,b)]

and
dt[ , seq(a,b), with=FALSE]

Addendum to note that .SDcols can also be used to determine a,b inline in some cases, e.g. if a:b is just the numeric columns of the table, we can use:
dt[ , lapply(.SD, mean, na.rm=TRUE), by=V1, .SDcols=is.numeric]

Or if a:b have a pattern in their name, e.g.:
dt[ , lapply(.SD, mean, na.rm=TRUE), by=V1, .SDcols=patterns("ends_with_x$")]

R data.table .SD unexpected behaviour


Properties of the boundary of a set

Question: let $X$ be a topological space. Let $\emptyset \neq A \subset X$ be such that $A=\partial A$
Which one of the following is then guaranteed to be true?
i) $\exists x \in A: \forall N \in N(x): N \cap (X \backslash A)=\emptyset$
ii) $int(A) \neq \emptyset$
iii) $A= \bar{A} $ Where $\bar{A}$ is the contact point which our teacher denoted boundary points + interior points
My own thoughts to this question are the following:
it cannot be ii) since $int(A)$ must be empty since $A$ only contains the boundary points.
Furthermore it cannot be iii) because $\bar{A}$ contains interior points as well where $\partial A=A$ only contains boundary points
When I try to paint i) I cannot make it fit as well. My thoughts are that since the boundary points of A must be contained in X since $A \subset X$. Then when I look at the last $N \cap (X \backslash A)=\emptyset$ I cannot see how the intersection between the neighborhoods without $A$ is empty. I mean if you remove the set the neighborhoods of the set will still be there? And when the Neighborhoods are still there they must still be contained in X? So in my view it would make more since if it was $N \cap (X \backslash A) \neq \emptyset$. But I could be misunderstanding something.
Comment: iii) is correct because $\overline A=\partial A\cup\operatorname{int}(A)=A\cup\emptyset=A$. -- For i), consider $X=\Bbb R$ and $A=\{0\}$
Comment: In number 1, does $N(x)$ mean the set of all neighborhoods of $x$.  I've never seen that notation.
Comment: Thank you Hagen I see it now since $\hat{A}=int(A) \cup \partial A$ and $int(A)$ is empty we're just left with the union of the empty set and the boundary points of A, which is just the boundary points of A. Would i) be equal if we had $\neq$ instead of =
Comment: Fleabodd: yes it should be read as : there exists an x in A such that for all neighborhoods around x
Comment: Isn't a boundary the set of points that are limit poits of A and X/A?  So be definition every neighborhood of a boundary point with have points that are in A (unless A has not limit points) and points that are in X/A (unless X/A has no limit points).  If X/A has no limit points the i) is possible but in general if X/A does have limit points i is not possible.
Comment: Think about what you just said:  "int(A) must be empty since " and then "it cannot be iii) because A¯ contains interior points as well".  Now go back to "int(A) must be empty" and "A¯ contains interior points".  Think about that...
Answer: Number $i$ isn't correct for example suppose that $X = R^2$ that $R$ is a real space and $A = S^1$ for any $x$ in $S^1$, any neighborhood of $x$, $N \cap (X - A)$ isn't empty. Number $ii$ is wrong and $iii$ is correct.
Answer: The boundary of any set is closed, as $\partial A = \overline{A} \cap \overline{X\setminus A}$ is the intersection of closed sets.
So if $A = \partial A$, $A$ is closed and so $\overline{A} = A$.

Properties of the boundary of a set


java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "__aeabi_memmove4"

Question: I've used NDK cross compiled many different version of library and used them in my Android application. They just work fine, until final release of my app, my fellow worker have tested the application on his XiaoMi 4 and this error appeared.
First I thought it maybe because of some particular platform's library's lost, but soon after I extract the .apk file and find everything was actually there.
I have searched for google found nothing that can solve the problem.
PS: In my new version of application, I just changed few lines in my C library and all of them is just about if-else-return stuff. I'd never used any of those memcpy-memmove functions, let alone memmove4.
If anyone can explain this to me? what is __aeaib_memmove4 ?
Comment: And people should always explain for the down vote.
Comment: I would have tried a different ndk version and see if that changes everything. Also, did you look here: http://stackoverflow.com/questions/39541599/error-loading-package-jni-cannot-locate-symbol-aeabi-memcpy ?
Comment: @yakobom The first thing that came into my mind is: maybe the NDK on my mac is different. So I tried compiling my library on newly installed ubuntu, and windows, no success. The problem just occurs on `XiaoMi4` but works just fine on other devices. So, only explanation is: my current NDK version is too high(and contains some features that `XiaoMi4` doesn't support).
Comment: Compiling your library on a newly installed ubuntu does not say anything regarding the NDK version you have installed on it. As I suggested - if supporting that device as well is important to you, why don't you try an older NDK?
Answer: So I finally solved the problem by upgrading the APP-PLATFORM in my Android.mk file from 8 to 17, which is my targetSDKversion, so the error is gone.


Exibir os valores que são iguais comparando as 2 matrizes

Question: Pela primeira vez me vi perdido nos exercicios acho que não peguei bem a lógica, mas estou estudando para entender. Vou mostrar meu código fonte por completo é pequeno e a questão. Ai gostaria da ajuda de voces para entender aonde estou errando.
-----Leia duas matrizes 20 x 20 e escreva os valores da primeira que ocorrem em
qualquer posição da segunda.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int matrizx[3][3], matrizy[3][3], i, j, cont = 0;
    printf("----Primeira Matriz----\n");
    for (i = 0; i < 3; i++) {
        printf("Informe os X valores da %dº linha \n", (cont = cont + 1));
        for (j = 0; j < 3; j++) {
            scanf("%d", &matrizx[i][j]);

        }
    }

    printf("----Segunda Matriz----\n");
    cont = 0;
    for (i = 0; i < 3; i++) {
        printf("Informe os Y valores da %dº linha \n", (cont = cont + 1));
        for (j = 0; j < 3; j++) {
            scanf("%d", &matrizy[i][j]);

        }
    }
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
                if (matrizx[i][j] == matrizy[i][j]) {
                    printf("%d", matrizx[i][j]);
                }
            }
        }
        return EXIT_SUCCESS;
}

Pessoal nesse ultimo bloco que é resṕonsável por fazer a analise que é a questão, ele só consegue pegar os primeiros valores repetido, que ele encontrar entre as matrizes porem somente a primeira  linha que  ele encontrar que os valores são iguais e exibido tais valores mas ele não prossegui com a analise para exibir outros valores.
Tentei utilizar uma variavel auxiliar para ajudar a armazenar mas sem sucesso.
Aguardo respotas galera!
Comment: Você está verificando se os elementos **na mesma posição** das matrizes são iguais e não é isso o que o exercício pede. Uma solução é para cada elemento da primeira matriz comparar com **todos** os elementos da segunda matriz. Não tem muito sentido esta variável `cont`, basta imprimir `i+1`.
Answer: Segue resolução sugerida utilizando python:
def verifica(matriz, numero):
   for linha in matriz:
      for coluna in linha:
         if coluna == numero:
            print(coluna)

for x in matriz1:
   for y in x:
      verifica(matriz2, y)

Observe que eu fiz no segundo bloco um loop pegando número por número da primeira matriz e aplicando na função criada no primeiro bloco. Essa função, por sua vez, percorre a segunda matriz comparando cada número desta com o número recebido no parâmetro da função.
Do jeito que vc havia feito, vc apenas comparava números em posições iguais, e a questão pede que basta ocorrer em qualquer posição da segunda. Por isso vc varre as duas matrizes, comparando a primeira com tudo que está na segunda.
Answer: Dessa forma ai, você só está percorrendo os elementos das mesmas posições. Tente fazer algo nesse esboço aqui:
int v1 = 0, c1 = 0, c2 = 0;
do{
    if(matrizx[c1][c2] == matrizy[c1][c2]){
        printf("%d ", matrizx[c1][c2]);
    }
    c2++;
    if(c2 == 3){
        c2 = 0;
        c1++;
    }
}while(c1 != 3);

Evite trabalhar definindo valores estáticos. Pra teste ok, mas depois coloquei algo mais dinâmico, pode ser até pegando o valor do próprio usuário.


Simple Complex analysis integration

Question: If we let $\gamma$ be the circline path from $ 0$ to $1$, how do we list all possible values of
$$\int_{\gamma} z^3dz$$
One of which, I think, could be over the real axis, s.t.
$$\int_{\gamma} z^3dz = \int_{0}^1 t^3dt = \frac{1}{4}$$
Another could be the closed path starting at $0$, but how do I initiate this integral?
Is the top integral correct?
Answer: First of all, for a fix path $\gamma$ from any point $z_0$ to $z_1$, $$\int_{\gamma}z^3dz$$ is well defined.
But more is true, since your function $f(z)=z^3$ is entire (holomorphic everywhere), the path integral does not depend on the choice of path.
If you have a function with some singularities, you can still define the integral over some path (that doesn't pass through any singularities). Then, for any two homotopic paths $\gamma_0$ and $\gamma_1$ from $z_0$ to $z_1$, you have
$$\int_{\gamma_0}f(z)dz=\int_{\gamma_1}f(z)dz.$$

Simple Complex analysis integration


Flutter app error - getter 'value' was called on null

Question: I'm building one app where on top of Camera view I need to show something. Here is my code.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';

List<CameraDescription> cameras;

void main() async {
  runApp(new MaterialApp(
    home: new CameraApp(),
  ));

}

class CameraApp extends StatefulWidget {
  @override
  _CameraAppState createState() => new _CameraAppState();
}

class _CameraAppState extends State<CameraApp> {
  CameraController controller;
  var cameras;
  bool cameraGot = false;

  Future<Null> getCamera() async {
    cameras = await availableCameras();
    setState(() {
      this.cameras = cameras;
      this.cameraGot = true;
    });
  }

  @override
  void initState() {
    getCamera();
    super.initState();

    if(this.cameraGot) {
      controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
      controller.initialize().then((_) {
        if (!mounted) {
          return;
        }
        setState(() {});
      });
    }

  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    // camera widget
    Widget cameraView = new Container(
      child: new Row(children: [
          new Expanded(
            child: new Column(
                children: <Widget>[
                  new AspectRatio(
                    aspectRatio:
                        controller.value.aspectRatio,
                        child: new CameraPreview(controller)
                  )
                ]
            ),
          )
      ])
    );

    return new Scaffold(
      body: new Stack(
        children: <Widget>[
          !this.controller.value.initialized ? new Container() : cameraView,

           // ---On top of Camera view add one mroe widget---

        ],
      ),
    );
  }
}

Whenever I'm building the app I'm getting following error...
I/flutter ( 6911): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value

Can't able to fig. out what's the error.
Comment: This helped me and now app works flawlessly, https://stackoverflow.com/questions/58380075/flutter-shows-a-red-error-screen-before-loading-data-from-firebase-using-stream
Answer: If you have created and assigned value to the variable and still it shows getter 'value' was called on null,
try to Run or Restart your app instead of Hot Reload. Because Hot Reload will not call initstate() (where variables assign their values) which will be only called by Restarting the app.
Answer: In the initState, you don't always instantiate a controller.
Which means it can be null. Therefore inside the build method, you need to check null to not crash
(!this.controller?.value?.initialized ?? false) ? new Container() : cameraView ,

Comment: I tried this but still, I'm getting the same error.
Comment: there's more then one place where you use controller. You need to check it everywhere
Comment: At this line also I've made changes like yours ```aspectRatio: (this.controller?.value?.aspectRatio) ?? false ``` but still no luck. Now, the error showing is ``` type 'bool' is not a subtype of type 'double' where```
Comment: Is controller?.value? are optionals like in swift ? @RémiRousselet
Answer: aspectRatio: (this.controller?.value?.aspectRatio) ?? false

aspectRatio is a double value and you assigned it to false when it is null. Give it a double value.
Answer: I had this problem before and putting a height into the parent widget of AspectRatio fixed it.
Answer: giving height to widget which is throwing error solved my issue
Answer: I solved the problem this way:
children: <Widget>[
    (controller== null)
                      ? Container()
                      : controller.value.Initialized
                          ? Container(child: CameraPreview(controller))
                          : Container(),
    ],

Answer: Most of the time. HOT RESTART (R) will fix this error.
Comment: This will just restart the app, won't fix the error!
Comment: Please elaborate your answer. Try to give some good example or explain it properly.
Comment: this removes error but again when you start app gives same error in my case
Comment: Worked when the problem surfaced during the Cupertino products app Flutter tutorial.


Unable to do a git pull - related to upgrade from Ubuntu 11.10 to 12.04?

Question: Everytime I execute git pull origin master on my laptop, I get an error.  This does not happen on any of my other computers or linux servers.  The only difference with my laptop is that I recently upgraded from ubuntu 11.10 to 12.04. Here are my terminal commands that generate the error:
www-data@john-laptop:~/huf$ git init
www-data@john-laptop:~/huf$ git remote add origin http://firstname.lastname@example.com/em-microsite
www-data@john-laptop:~/huf$ git pull origin master
Password for 'http://firstname.lastname@example.com':
error: The requested URL returned error: 401 (curl_result = 22, http_code = 401, sha1 = 65a9a62cd53a7533ce48a463d5fa5622734bc38b)
error: Unable to find 65a9a62cd53a7533ce48a463d5fa5622734bc38b under http://firstname.lastname@example.com/em-microsite
Cannot obtain needed commit 65a9a62cd53a7533ce48a463d5fa5622734bc38b
while processing commit 642d437e3080f869503f663b2ea0013cb85ebe8a.
error: Fetch failed.

Does anyone know what's wrong and how I can fix?   As mentioned, i don't encounter this error on any other linux computers and servers.
Additional notes: I typed in the same username and password on 8 different computers/passwords. The only time it fails is on my www-data@john-laptop computer. I suspect this might have something to do with my upgrade from ubuntu 11.10 to 12.04. Maybe i'll try re-installing git on that computer.  Does anyone know of related issues?  git works differently on different OS?
Comment: Why the downvote and close?  Isn't this the place to be asking about git server and/or linux based servers?
Comment: It says your username and password are wrong. So check those.
Comment: I did not downvote, or VTC; but I strongly suspect that they're on account of [SF] being for Professional System Administrators *only*, who should know that 401 means "user error", not a problem with the software.
Answer: The requested URL returned error: 401 == Unauthorized
Check your username and password or other form of authorization.
Comment: I typed in the same username and password one 8 different computers/passwords.  The only time it fails is on my john@laptop computer.  I suspect this might have something to do with my upgrade from ubuntu 11.10 to 12.04.  Maybe i'll try re-installing git on that computer.  Do you know anything that might be related?
Comment: @John Do you have access to logs? That way you can verify if the username/pw you see matches what the server sees. At least with that you can see if its a server problem or client problem


Checking for bounding box intersections/collisions with a view frustum

Question: I want to check a view frustum against the axis aligned bounding boxes of some objects, to check roughly whether those objects are in the field of view or not. Speed is not a big deal.
Answer: I figured out that building a world-space model of the view frustum and checking for bbox collisions with it was the wrong way to go about this. A much simpler method is to go the opposite way and convert each vertex of a given bbox to screen-space, and if any vertex of the bbox is within the screen bounds then count that bbox as visible. I get the screen-space position by multiplying against the camera matrix and then accounting for perspective based on the field of view of the camera.
Here's the code:
<code>vertexMatrix = matrix([vertex.x,vertex.y,vertex.z,1])
productMatrix = (vertexMatrix * camMatrix)
pVectSS = vector(prodMatrix[0][0],prodMatrix[0][1],prodMatrix[0][2])

pointX = ((pVectSS.x/(-pVectSS.z))/tan(radians(hFOV/2)))/2.0+.5
pointY = ((pVectSS.y/(-pVectSS.z))/tan(radians(vFOV/2)))/2.0+.5
</code>
key:
<code> camMatrix = camera inverse world-space matrix
 pVectSS = position vector screen-space
 hFOV = horizontal field of view
 vFOV = vertical field of view
</code>
Comment: There are several cases where the bb is within the frustum but its corners are not
Answer: That will work. However, usually one would rather extract the frustum planes and calculate the distances to these. You said "speed is not a big deal", but eventually you may find that it is. After all, one does frustum culling to make things faster.
Multiplying a vertex with a matrix takes the equivalent of 4 dot products, therefore you need the equivalent of 32 dot products to check all 8 corners. Calculating the distance of a point to a plane takes a dot product and an addition, which is somewhat more efficient in the worst case and much more efficient in the average case (since you can often discard an object after clipping after one or two planes, and never more than three). There are a number of optimizations for clip planes that exploit temporary coherence, which I will not go into deeper detail.
Additionally, you can do some coarse culling beforehand by calculating the distance of the center point to a plane and check whether that is greater than the bounding box's radius. This will cull objects that are clearly "in" or "out" very cheaply. Or, alternatively, you could compare the dot product of your view vector to the cosine of your field of view value plus some "padding" (or alternatively, just see if it is positive) as a first ultra-coarse check. As you will remember, the dot product of two vectors tells you how much they point into the same direction. Something that has a negative dot product with your view vector certainly is something you can safely discard, because it's behind you.
Comment: I should have elaborated why speed is not a factor in this case; the script is used for pre-processing a 3d scene to decide which objects to export to a ray-trace renderer, so in the scheme of things its runtime speed isn't important, just implementation speed :). My answer was actually a bit wrong too, as there is an edge case where a large object is close to the camera and its verts are all outside the FOV, so I ended up just drawing screen-space bbox around the world-space one, which is a pretty bad hack, but good enough for now.
Comment: For a raytracer, even only a handful of fragments here and there at boundaries may make a huge difference. You could consider drawing your scene using OpenGL (with fixed functionality if you want, since speed does not matter so much, and it's easy), and run an occlusion query for each object (supported by pretty much every graphics card since at least half a decade). No z-test, so transparent objects don't cull what's completely behind them, we're not interested in a pretty render anyway. All we want is a positive number in the query for any object that has as much as one fragment drawn.
Comment: Though another thing comes to mind: What about objects that are culled (regardless of the method) but needed anyway? When someone says "raytrace", the first thing that comes to mind are shiny things with reflections. An object can very well be visible in a reflective surface when it is far outside the viewing frustum. That may be not very noticeable in some situations, but will give very funny effects in others, especially with animation. If that can be a problem, you should rather not discard anything in the scene export.
Comment: Yeah, you're right, in this case it was necessary to cull objects because each object was in the region of 3 million poly's, plus all the reflections are very diffuse, so they aren't particularly affected by distant objects. The ray-tracer didn't want to cull objects itself since, like you say, reflective objects are usually affected by off-screen objects.


What is the meaning of the notation $\theta \sim p(\theta)$ and $y \sim p(y|\theta)$?

Question: I've seen this notation pop up in some Bayesian statistics notes but despite my best efforts with Google I've not had any luck discovering the meaning. The only helpful context that I have is that $y$ is the observed data and $\theta$ is some sort of parameter. As for giving an example of this notation in use, I've seen De Finetti's theorem summarized as "$Y_1 , ... , Y_n | \theta$ are i.i.d. and $\theta \sim p(\theta)$ if and only if $Y_1 , ... , Y_n$ are exchangeable for all $n$".
EDIT: Note, I'm not asking how something like $Y \sim N(\mu, \sigma^2)$ is read, I know exactly what that means. It's the $p$ parts that are confusing me.
Comment: @aginensky $\sim$ **does not** mean "proportional with unknown constant". It means *is distributed as*. The "is proportional" notation is $\propto$ and Bayesians do not use different notation then the rest of the world.
Comment: I don't agree that the alleged duplicate question and its answers have anything to do with the question being asked here and vote to reopen this question. It is hard to believe that there are not already _other_ questions on this site of which J.Min's question is a duplicate, but the one used by @Tim as a reason for closing this question is not a duplicate.
Comment: Context, along with direct quotes, have already been given. As for what's confusing, I don't know how I could be more clear. As far as I can tell the statement "theta is distributed the probability density function of theta" simply doesn't make sense, nor does the $y$ example.
Comment: "Probably" the answer you want is that in the context of Bayes theorem,
Comment: @J.Min maybe you could link the paper where you've seen it?
Comment: agh,  i got cut of.  In the context of Bayes theorem ~ means proportional with an unknown constant, i.e. P~Q means $P = K*Q$ for some unknown K.  This can be useful If one is interested in ratios, say $P_1/P_2$ and one knows that $P_1 $ ~ $ Q_1$ and $P_2 $ ~  $Q_2$ and one can calculate the Q's.
Comment: Specifically this can be used to calculate in things like Markov Chain Monte Carlo.
Answer: The notation is overloaded (or abused) so $p$ refers both to the probability density function as well as to the distribution. This seems a lot simpler than to have say capital letters indicate the distribution and lower case letters indicate the pdf/pmf.
Alternatively the $\sim$ notation can be thought of as overloaded so that it means the random variable on the left has the distribution on the right if the quantity on the right is a distribution. But if the quantity on the right is a pdf/pmf then $\sim$ means that the random variable on the left has the pdf/pmf of the quantity on the right.
Comment: Point taken, although if nothing else a source would be reassuring.
Comment: Ah, i suspected as much. Do you have any source for this claim?
Comment: Why would you need a source?  Either this explanation will make sense of the notes you're reading or it won't.  No number of sources will change that.
Answer: The notation is very misleading with $p(\cdot)$ being heavily overloaded with multiple meanings and complete disregard for the difference between random variables and the values that they take on.
There is a parameter $\theta$ of unknown value which is modeled as a random variable $\Theta$, discrete or continuous depending on what $\theta$ is believed to be. Assuming that $\theta$ is believed to take on discrete values, $$\Theta \sim p_\Theta(\theta)\tag{1}$$ is saying that $\Theta$ is being modeled as a discrete random variable with probability mass function $p_\Theta(\theta)$, or to paint refined gold and gild the lily, the function $p_\Theta(\cdot)$ has the property that $$P\{\Theta = \theta_i\} = p_\Theta(\theta_i).$$ There are $n$ observations $x_1, x_2, \ldots, x_n$ which are also modeled as random variables $X_1$, $X_2$, $\ldots$, $X_n$. Assuming that everything is discrete, on a trial of the experiment, these random variables $\Theta, X_1, X_2, \ldots, X_n$ have values $\theta, x_1, x_2, \ldots, x_n$ of which we can observe only $x_1, x_2, \ldots, x_n$.  Now, the conditional probability mass function of the $X_i$ given that $\Theta$ has value $\theta$ is $$p_{X_1, X_2, \ldots, Xn \mid \Theta = \theta}(x_1, x_2, \ldots, x_n \mid \Theta = \theta)\tag{2}$$
meaning that
$$P\big\{X_1 = x_1, X_2 = x_2, \ldots, X_n = x_n \mid \Theta = \theta_i
\big\} = p_{X_1, X_2, \ldots, Xn \mid \Theta = \theta_i}(x_1, x_2, \ldots, x_n \mid \Theta = \theta_i).$$
Notice that $p$ has different subscripts in $(1)$ and $(2)$ to emphasize that there are two different functions being used here; one with just one argument and another with $n$ arguments, a far better arrangement than $p$ meaning different things depending on where it occurs and also better than the "canonical"

Let $X \sim f(x)$ and $Y \sim f(y)$ be random variables $\ldots$

or the physicists'

$X \sim f(X), Y \sim f(Y), X,Y \sim f(X,Y)$

where the density of $X$ can be quite different from the density of $Y$ and one is supposed to figure out from the letter used as the argument of $f\cdot)$ as to whether the density function of $x$ is meant or the density function of $Y$.
Comment: The "canonical" example, although frequently seen, is either mathematical nonsense or means something else altogether.  "$f$" apparently is a function and "$x$" and "$y$" its arguments, whence--reading this in a conventional way--we would have to understand $f$ as being a function whose values are distributions!  The "physicists" example makes no sense at all, because it's perfectly circular: it describes $X$ and $Y$ in terms of themselves! The example in the question--"$\theta\sim p(\theta)$"--is particularly egregious abuse.


Numbers with same even and odd digit numbers

Question: Show that there are exactly $281250$ six-digit numbers that have three even numbers and three odd numbers.
My answer is: $1000000\cdot \binom{6}{3}\cdot \left( \dfrac12 \right)^6-100000\cdot \binom{5}{2}\cdot \left( \dfrac12 \right)^5$.
Mi reasoning is: from $000000$ to $999999$, there are $1.000.000$ numbers. But those that start with $0$ must be subtracted because they would not be $6$-digit numbers. Then we have $1.000.000\times 1/2$ you take off all the ones that are not even in the first digit. $1/2$ all the ones that are not even in the second digit. $1/2$ all the ones that are not even in the third digit And now $(1/2)^3$ all the ones that are not odd in the fourth fifth and sixth digit. Then $\binom{6}{3}$ as they will be the different combinations of the $3$ even numbers and over the $6$ positions. Once you have done all this, you have to subtract all the ones that start with $0$. To do this by a similar reasoning we take the $100.000$ numbers that start with $0$. We multiply by $1/2$ and $1/2$ to subtract those that are not even numbers from the first and second positions and then $(1/2)^3$ to remove those that are not odd from the rest of the positions. And then we multiply it either by $\binom{5}{2}$ of the different combinations of the $2$ pairs between the five digits or $\binom{5}{3}$ of the different combinations of the $3$ odd numbers over the $5$ digits (as we see it is the same $\binom{5}{2}$ as $\binom{5}{3}$).
Is it correct?
Answer: Rewriting your answer as $$5^3\cdot5^3\cdot {6 \choose 3}-5^2\cdot5^3\cdot {5 \choose 2}$$ and explaining it by

the number of six digit strings with three digits even and three digits odd, minus the number of six digit strings where the leading digit is $0$ and two of the others are even and three odd

suggests to me that your answer is correct


UMVUE for Exponential probabilties

Question: Let $X_i$ be i.i.d $exp(\lambda)$ and take any $a > 0$.
I want to find the UMVUE of $P(X_i < a ) = 1-\exp(-\lambda a)$.
My attempt
By properties of the exponential family we know $\sum_i X_i$ is a complete sufficient statistic for $\lambda$.
Hence we only need to:

Find an unbiased estimator of $P(X_i < a)$
Condition it on $T(X) = \sum_i X_i$ and apply Lehmann-Scheff Theorem

An obvious candidate for an unbiased estimator is using indicator functions. For example
$$\delta (X) = 1(X_1 < a)$$
Is an unbiased estimator. Hence the estimator
$$T(X) = E[\delta(X) | T(X) = t]$$
Is the UMVUE of $P(X < a)$. However, I am having trouble deriving this. The problem I am having is the fact I have conditioned a continuous random variable on a discrete condition $T(X) = t$. How can  I proceed?
Comment: That you have conditioned on a continuous random variable taking a particular value is not a problem. We are considering the event  $\{t-h\le T\le t+h\}$ as $h\to 0$ as is usually the sense for conditional distributions in the continuous case.
Comment: I reckon [this](https://stats.stackexchange.com/questions/172215/find-the-joint-distribution-of-x-1-and-sum-i-1n-x-i/7) post should answer your question. I had found the conditional expectation directly (conditional probability) using well-known results involving the Beta and Gamma distributions in my answer.
Comment: @StubbornAtom apologies for asking the same question twice! I am reworking through Lehmann-Casella and forgot I had asked it. I have given an alternative answer (hence bumping this) as I think it will be useful to people who might stumble across this. It is similar to the method used for normal probabilities.
Comment: Wow! That's a really clever work around to avoid the integration. Thanks @StubbornAtom
Answer: Going to post a late answer as it's quite simple but useful trick. The UMVUE is indeed given by
$$P(X_i < a|T)$$
The trick is to use Renyi's representation which says that
$$\frac{X_1}{\sum_{i=1}^n X_i} =_d U_{(1)}$$
Where $U_{(1)}$ is the 1st order statistic from a uniform(0,1) random sample
$$U_1, U_2, \dots U_{n-1}$$
$$P(X_1 < a | \sum_i X_i = t) = P \left(\frac{X_1}{\sum_i X_i} < \frac{a}{t}|\sum_i X_i=t \right) = P\left(\frac{X_1}{\sum_i X_i} < \frac{a}{t}\right)$$
The last inequality follows from Basu's theorem which says every complete sufficient statistic is independent of every ancillary statistic. Since $X_i$ come from a scale family, it follows $X_i/\sum_i X_i$ is ancillary. Hence the probability is independent of the complete sufficient statistic $T(X) = \sum_i X_i$.
Hence by the above Renyi's representation, using the fact that the minimum of a Uniform(0,1) sample (of size $n-1$) has distribution $P(U_{(1)} \leq u ) = 1- (1-u)^{n-1}$, it follows that the UMVUE is given by
$$P(X_1 < a | \sum_i X_i = t) = P\left(U_{(1)} < \frac{a}{t} \right) = 1 - \left(1-\frac{a}{t} \right)^{n-1}$$
ie.
$\delta (X) = 1 - (1 - \frac{a}{\sum_i X_i})^{n-1}$ is UMVUE

UMVUE for Exponential probabilties


An analogue to Cantor's theorem

Question: Cantor's theorem states that for all sets $$|A| < |2^A|$$
I was interested in a similar proposition. If $A$ is a set, denote by $A! := \{f : A \rightarrow A \mid f \text{ is a bijection}\}$. Is it true in general that $|A| < |A!|$?
It is not to difficult to show that $|\mathbb{N}| < |\mathbb{N}!|$. To see this, let $B \subset \mathbb{N!}$ be the set of permutations which are either the identity or have some number of even naturals swapped with their right neighbor. (0 1 (3 2) 4 5 (7 6) 8 9 10 11 12 ... is an example). Then $B$ is uncountable because if we map unswapped pairs to 0 and swapped pairs to 1, this constitutes a bijective mapping into the set of infinite binary strings, which we know to be uncountable by the classic diagonalization argument. Then as $B \subset \mathbb N!$, $\mathbb N!$ is uncountable.
Unfortunately this proof does not yield an approach to the general case. Any ideas?
Comment: It is not true when $A$ has one or two elements.
Comment: $|A|\le|A!|$ is easy: fix $a\in A$, there's an obvious bijection between $A$ and the set of all transpositions $(a,x)$ plus the identity permutation. It's $|A|\lt|A!|$ that's the interesting question.
Comment: Say the question is whether $|A| \leq |A!|$, then. Or better yet say A is infinite as that is the interesting case.
Answer: Taking a hint from Unit's comment down below (ultimately coming from Factorials of Infinite Cardinals by Dawson and Howard, it seems), here's a case differentiation proving the result in ZF (as far as I can tell).

In case $|A| = |2 × A|$: Mapping $2^A → (2×A)!,~ B ↦ σ_B$, where $σ_B$ swaps the two copies of $B$ in $2×A  = A \sqcup A$ pointwise and fixes the rest, is injective. If $2×A \cong A$ you have $(2×A)! \cong A!$ and hence this proves $|A| < |2^A| ≤ |A!|$.
In case $|A| < |2 × A|$: Assume $|A| > 2$ and fix a two element set $2_A ⊂ A$ and a check-point $ξ ∈ A\setminus2_A$. Then the mapping $2_A×A → A!,~(α,x) ↦ (α~ξ~x)$ is evidently left-inverted by $A! → 2_A×A,~τ ↦ (τ^{-1}(ξ),τ(ξ))$, hence it's injective, proving $|A| < |2×A| ≤ |A!|$.

I hope this is correct.
Comment: @Unit: What do they say about $X\lt X!$? Is that provable without choice, or is $X=X!$ possible?
Comment: Theorem 1.1 says if $|X| \ge 3$ then $|X| < |X!|$. Since it is true in ZF that $|X| \le |2\times X|$, they proceed by cases: "if $|X| < |2\times X|$", and "if $|X| = |2\times X|$".
Comment: $2\times A\cong A$ is true given the Axiom of Choice, but I don't think it is necessarily true without AC. It would be interesting to see if the result could be proved _without_ AC.
Comment: @HenningMakholm I know, that's what I'm trying to improve. ;-) Maybe using version (2). I'm trying to find an argument for the existence of such a $σ$ without choice. Edit: Oh, it's not?
Comment: @Henning: It's not, and that topic has been discussed before too. :-)
Comment: Have a look at *Factorials of infinite cardinals* by Dawson and Howard.
Comment: For version 2, I see no reason why $\sigma|_{B^c}\cup \mathrm{id}_B$ would be a bijection. Does $\sqcup$ (whose meaning in this context I'm not sure of) somehow fix that?
Comment: In particular, "In the absence of the axiom of choice, any one of the three alternatives (i) $X!$ and $2^X$ are incomparable, (ii) $X! > 2^X$, or (iii) $X! < 2^X$ are possible."
Comment: @Unit: Actually, there is a paper by David Pincus which deals with this topic, "A note on the cardinal factorial" (Fundamenta Mathematicae vol.98(1), pages 21-24(1978)) which is a nice workout without choice.
Comment: Slightly confused here - I'm unfamiliar with the notation $2 \times A$ and $A \sqcup A$. What do these mean? I imagine the former is $\{0,1\} \times A$
Comment: @dalastboss Yes, all of them are supposed to mean $\{0,1\} × A$. (I'm neither a logician nor a set theoriest, though, so my notation might be off.) But have a look at wiki on [disjoint union](https://en.wikipedia.org/wiki/Disjoint_union) and [coproduct](https://en.wikipedia.org/wiki/Disjoint_union#Category_theory_point_of_view).

An analogue to Cantor's theorem


Mixture distributions moments if one distribution has undefined/infinite moments

Question: Consider probability density functions $f_{1}\left(x\right)$ and $f_{2}\left(x\right)$ and the mixture distribution
$$f_{3}\left(x\right)\equiv pf_{1}\left(x\right)+\left(1-p\right)f_{2}\left(x\right)$$
Assume that the moments associated with $f_{1}\left(x\right)$ are all clearly defined, but the moments of $f_{2}\left(x\right)$ may not necessarily be (e.g. a Cauchy or Levy distribution).
To calculate the expected value one would find
$$\int_{-\infty}^{\infty}xf_{3}\left(x\right)dx=p\int_{-\infty}^{\infty}xf_{1}\left(x\right)dx+\left(1-p\right)\int_{-\infty}^{\infty}xf_{2}\left(x\right)dx$$
Presumably if $\int_{-\infty}^{\infty}xf_{2}\left(x\right)dx$ is infinite or undefined, then the expected value only exists when $p=1$.
Is this logic correct, even if $p$ is close to but less than $1$? Does it extend to higher moments as well?
Answer: Yes, you are correct. If $X_1 \sim f_1$, $X_2 \sim f_2$, and $X_3 \sim f_3$, then your equation shows that $$E(X_3) = p \cdot E(X_1) + (1-p) \cdot E(X_2)$$ Therefore if either one of $E(X_1)$ or $E(X_2)$ in non-finite/non-existent then $E(X_3)$ will be non-finite/non-existent also if $p \in (0,1)$ - this is true even if $p$ is very near $0$ or $1$.
To get some intuition for this, note that the mixture distribution can be thought of a drawing from $f_1$ with probability $p$ and $f_2$ with probability $1-p$. Bearing that in mind, take an example where $f_1$ is the density of the reciprocal of a standard normal (a distribution with infinite mean), $f_2$ is the standard normal density and $p$ is some very small value (say $.01$). Consider sampling variables that have density $f_3$ - of the $1\%$ that are drawn from $f_1$, there will be some extreme values characteristic of a distribution with non-finite mean.
You're also correct that this same logic would apply to higher moments - replace $x$ with $x^k$ in your integrals and you can make an exactly analogous argument. Where it gets more complicated is when, for example, both integrals are non-finite but this seems beyond the scope of the question :)
Comment: @John, if you were to generate data from that distribution, one way to do that would be to have $99\%$ of it from a $t_{100}$ distribution and $1%$ of it from a $t_1$ distribution. Well, that $1\%$ will be extremely long-tailed and, as such, will occasionally produce extreme outcomes, leading to the perhaps counterintuitive result that the variable's mean doesn't exist. It's not always clear by looking at a plot of the density function that the mean will not exist - for example, the difference between a $t_1$ and $t_2$ density is subtle but one has a mean while the other doesn't!
Comment: @Macro I am not convinced by your answer. In fact you start with John's equality $\int_{-\infty}^{\infty}xf_{3}(x)dx=p\int_{-\infty}^{\infty}xf_{1}(x)dx+(1-p)\int_{-\infty}^{\infty}xf_{2}(x)dx$ but $xf_1(x)$ and $xf_2(x)$ are not positive functions hence this equality is not straightforward. If one of the integral is undefinite then this equality has no sense, and if one of the integral is infinite then this equality remains to be proved.
Comment: Ooops sorry ! I haven't seen that the original question assumes that $E(X_1)$ is defined !
Comment: Mathematically that makes perfect sense, but I still find it a little bit counter-intuitive. For instance, consider $p=0.99$ for a t-distribution with 100 degrees of freedom mixed with a t-distribution with 1 degree of freedom. The resulting pdf definitely looks like it would produce a finite expected value.
Comment: @Marco True enough regarding the subtlety of the densities. It isn't particularly challenging to simulate from the distribution that I mentioned. The problem is that mathematically the expected value is undefined, but it is possible to calculate an expected value of the simulated data that is technically incorrect.
Comment: @John The standard Cauchy density also "looks" like the random variable has expected value $0$: nice symmetric density with half the area in the interval $[-1,+1]$ etc. What's not to like? And why should the existence of a sample mean, whether from actual or simulated data, of a finite sample have anything to do with the existence, or lack of existence, of the population mean?
Comment: @Macro Taking $p=1/2$ for simplicty I said that the equality $\int x f_3(x) = \frac12(\int xf_1(x) + \int xf_2(x))$ is not straightforward (and sometimes it has not even a sense) and this is the starting point of your answer.
Comment: @StéphaneLaurent, if the right hand side is the sum of a constant and a divergent integral (i.e. $\infty$), it's clearly $\infty$, which is effectively what my answer says. Again, I'm still not sure how that's controversial. I have to go now but will respond to any further comments later.
Comment: Macro is correct, but the point @Stéphane is getting at is a subtlety that is not immediately obvious from the answer. That is, it implicitly assumes that linearity of expectation holds for the case when the expected value of one random variable exists, but is divergent, and the expected value of the other is finite (it does, but should be checked). In the case where both are finite, there is no issue and in the case where both exist but are divergent, then (existence and) linearity does not hold for all choices of constants. So, in some sense this example lies at the boundary of the two.
Comment: @cardinal, the identity $$ \int_{-\infty}^{\infty} x \big(pf_{1}\left(x\right) + (1-p)f_{2}\left(x\right) \big) dx= \int_{-\infty}^{\infty} x f_{1}\left(x\right)dx+\left(1-p\right)\int_{\infty}^{\infty}xf_{2}\left(x\right)dx $$ still works with infinite integrals if you adopt the convention that $a+\infty=\infty$ where $a>0$ and is possibly infinite, right? I get that if neither integral is defined or if you're doing $\infty-\infty$ then it's a problem , but perhaps you're saying something more.
Comment: There is also a problem when $E(X_2)$ is undefined. Your answer is right but it is not rigorously proved.
Comment: Hi, Macro. Yes, but that is essentially the point of the question. One must show that we can separate the integrand into two pieces and evaluate them separately (or establish the nonexistence by looking at the individual pieces).


Voltar para o inicio do código após um if ou switch case em C

Question: Estou com uma dúvida referente ao if.
Estou desenvolvendo um programa para o fim de semestre da faculdade e toda vez eu preciso usar um if e no fim do if, eu preciso que volte para o começo do programa. Estou tendo dificuldade em fazer isso.
Exemplo:
OBS: O código abaixo é ilustrativo, pois o meu é muito grande e não conseguirei postar aqui.
char op;

print("Digite algo");
scanf("%s", &op);

if (op == "nome") {

//algo aqui

}

if (op == "telefone") {

//algo aqui

}

if (op != 'nome' && op != 'telefone') {

//queria colocar algo aqui que fizesse o usuario voltar ao começo do codigo e pedir o valor da op pra ele de novo.

}

Essa minha dúvida também está relacionada ao switch case, onde no default eu queria colocar algo nesse estilo (De voltar para o começo do código).
Alguém pode me ajudar a entender?
Comment: Coloque o resto do código para ver onde ele tem que voltar.
Comment: Seu codigo tem problemas está a armazebar uma string num char e a vericar strings com `==` não irá funcionar. Na minha opinião, poderia usar `goto` não iria prejudicar muito a legibiliade, ou Como @bigown já disse poste o resto do código.
Comment: Ah entendi. Então, o meu código verdadeiro é muito grande, por isso não postei...Esse foi um exemplo rápido do que eu tenho dúvida. Eu deveria ter especificado isso lá em cima. :/ Vou editar. Mas obrigada mesmo assim. ;)
Answer: Podes usar um do-while. Enquanto não for digitada uma opção válida o programa irá continuar a pedir um input do utilizador.
#include <stdio.h>

int main(void) {

    char op;

    do {
         printf("Digite algo\n  0 - Sair\n  1 - Nome\n  2 - Telefone\n");

         scanf(" %c", &op);

         switch(op) {
               case '0': //sair
                   printf("Escolheu sair do menu\n");
                   break;
               case '1': //nome
                   printf("Escolheu opção nome\n");
                   break;
               case '2': //telefone
                   printf("Escolheu opção telefone\n");
                   break;
               default:
                   printf("Escolheu uma opção inválida\n");
                   break;
         }
    } while (op != '0');

    return 0;
}

Comment: Ah, obrigada. Vou tentar fazer aqui com o Do-While. ;)


PHP - How can I store data in an array to split it afterwards without getting in trouble?

Question: Ok. Here is the scenario.
I'm getting data(of a statusmessage) of my database table and storing every result in my array. Every result contains multiple rows.
It contains
statusID, posterID, statusMessage, dateTime, sumRating, sumVotes

So when I got multiple status messages in my table I want to print them all on the site.
Logically I know just do this
for($i = 0; $i < sizeof($results); $i++)
        {
            echo $results[i];
        }

And now I get all data of all type.
But now, when I want to play a little with the data and format it or, let's say, I don't want the data to be printed out one after one. I want the posterID, then I want a little PHP code or CSS or whatever.
So, what I'm doing now, is, that I currently save my data like this
foreach($statusMessageResult as $row){
            $results[] = $row['statusID'] . "," . $db->getUsername($db->getUserNameById($row['posterID'])) . "," . $row['statusMessage'] . "," . $row['dateTime'] . "," . $row['sumRating'] . "," . $row['sumVotes'];
        }

So now, in my for-loop, I just split the current entry of the result-array at every comma.
$statusMessage = $results[$i];
            $statusMessageSplit = explode(",", $statusMessage);
            echo "This status is written by: " . $statusMessageSplit[1] . " and has the ID: " . $statusMessageSplit[0] . "
";

What my problem is, that, when a user writes a
,

in his status Message it will be split again. So, what can I do to solve this better?
Comment: Uhm... just an idea: an *array of arrays*...!?
Comment: Change the delimiter from ',' to '|'?
Comment: @Jordan Because surely nobody will ever write anything with an "|" in it.
Comment: @deceze Precisely ;) Your solution is better ;)
Comment: Do what deceze says! It does not make sense to create a string array just so you can split up the string to a new array. Create a multidimensional array and then do the formatting.
Answer: You could do it like this using two-dimensional/jagged arrays:
foreach($statusMessageResult as $row)
    $results[$row['statusID']] = array($db->getUsername($db->getUserNameById($row['posterID'])), $row['statusMessage'], $row['dateTime'], $row['sumRating'], $row['sumVotes']);

//usage:
foreach($results as $index => $rowArr)
    echo "StatusID: $index:\r\n" . var_export($rowArr);


How to catch GTK focus state in gtkrc?

Question: GTK+ 2.x has the follow states: NORMAL, PRELIGHT, ACTIVE, INSENSITIVE, SELECTED for use in GTK themes and I can do things like...
bg[NORMAL] = "#f6f6f6"

.. to change background color when in NORMAL state.
Also, I can change the background image of a button (when the mouse is over it) by changing the PRELIGHT state image.
But I was not able to find a way to change the button background when the user cycle the focus using the TAB arrow (ie. when a dashed rectangle appears around the button). I want to do this using themes in gtkrc, is this possible ?
Answer: I don't think so. The RC file documentation doesn't even mention "focus", so I don't think it's possible to theme that in this way.
Comment: It's a shame gtk doesn't have such simple feature. I've searched a lot for this and found the same conclusion as you. Thank you.

How to catch GTK focus state in gtkrc?


In app subscription trial period completion notification

Question: I am implementing android subscription in my app. Subscription document says the app will get notified on successful payment with purchase token and other details.
Subscription i am going to add is having trial period and i would like to alert user few days before trial period completion. Document doesn't says if will return any kind of response when user purchase subscription for trial period with $0.0 cost.
If Google play doesn't notify app for the trial period expiration or on when it charge user $0.00 for trial period, how can i notify the user few days back of trial period completion?
Thanks in advance
Answer: I have read full document and there is nothing mentioned about this situation. If you have any back-end server(recommended in case of in-App) you can store purchase date(returned from google at the time of purchase) on your server and every launch you can query your server for remaining trial days and inform user.
Another way is you can use push notification instead of query your server and send notification to your user.This approach will be having advantage and disadvantage
Advantage: You can inform user even your app is in background.
Disadvantage: user can stop notification from your app.


Why do elements in $\mathbb R[x]/(x^2)$ look like at most degree one polynomials?

Question: What do elements in $\mathbb R[x]/(x^2)$ look like? Intuitively, I know they are polynomials of degree one but if we stick with the definition of quotient ring, the elements look like $f(x)+(x^2)g(x)$.

How does this show that the elements are polynomials of degree at most $1$?
Comment: No, the elements look like $f(x)+(x^2)$ and $(x^2)=\{x^2g(x)\}$. Anyway, any power of $x$ which is $\ge2$ within $f(x)$ can be subsumed into the $(x^2)$ ideal, so you're only left with the powers of $x$ smaller than $2$.
Comment: First, the elements of a quotient ring look like sets of polynomials because they are sets of polynomials.
Answer: Because every polynomial $P(x)$ can be written in one and only one way as $x^2Q(x)+R(x)$, where $\deg R(x)\leqslant1$. So, it is natural to identify $P(x)+x^2\mathbb{R}[x]$ with $R(X)$, whose degree is $0$ or $1$.
Answer: Because in a polynomial modulo $x^2$, all terms of degree $\ge 2$ are killed, just as in the representation of a element in $\mathbf Z/100\mathbf Z$, you keep only the last two digits.
Answer: A nicer way of looking at the quotient $\mathbf{R}[x]/(x^2)$ is the following: $\mathbf{R}[x]$ is just a free $\mathbf{R}-$algebra (with the usual multiplication) on elements $\{1,x,x^2,\ldots\}$. Now, by quotienting by $(x^2)$, we are declaring that any element of our quotient ring from which $x^2$ can be factored out is trivial. You can think about this as imposing an algebraic relation of $x^2=0$. Then, the polynomials of $\mathbf{R}[x]$ are of the form
$$ a_nx^n+\cdots+a_1x^{1}+a_0$$
After quotienting, we have that all of the monomial terms with degree $\ge2$ are killed, so that we have a resulting polynomial of $a_1x^1+a_0$. Constructing the isomorphism between these two rings makes this formal.


centralizar botao messenger facebook

Question: Não estou conseguindo centralizar o botão do facebook de forma nenhuma!
Se alguém puder me auxiliar, agradeço!
Segue HTML do que tentei fazer:

Javascript:

Imagem da forma que eu quero que fique:
Comment: Mas alinhar o que onde? Vc que alinhar a div `` na horizontal no centro da página? Ou na vertical no meio da página? De mais detalhes
Comment: Eu gostaria que fosse ao centro da página, mas se for possível. Centralizar no canto inferior esquerdo da página.
Comment: Cara tá difícil de entender o que vc escreveu... centralizar na esquerda? ou está no canto esquerdo ou está no centro da página...
Comment: Desculpe a a forma que eu expliquei. Editei o post, queria que ficasse daquela forma que o botão do whats está.
Comment: Pq não usa positivo fixed?
Comment: position: fixed; O botão nem se mexe. Assim como eu fiz acima
Answer: Tenta assim
style="display: block !important; margin-left: auto !important; margin-right: auto !important; width: 6em !important;"

centralizar botao messenger facebook


Looking for follow set of Grammar in discrete math

Question: $E\rightarrow Tx$
$x\rightarrow +E|$empty string
$T\rightarrow (E)|intY$
$Y\rightarrow*T|$empty string
I had hard time looking for follow set for $T$ and $Y$. Cause it will trace back to each other. If I do $Y$, then it will trace back to $T$ when $T$ trace back to $Y$. It is a loop. So how do I look for follow set under this circumstance?
Thank you.
Answer: I hope it can help you.

FOLLOW function
FOLLOW(A) is defined as the set of terminal symbols that appear
  immediately to the RHS of A.

for the start symbol S place  in FOLLOW(S).
if there is a production  $A \to \alpha B\beta$ then everything in FIRST$(\beta)$ without $\epsilon$ is to be placed in FOLLOW(B).
if there is a production  $A \to \alpha B\beta$ or $A \to \alpha B$ and FIRST$(\beta)=\{\epsilon\}$ then FOLLOW(A)=FOLLOW(B). that means
  everything in FOLLOW(A) is in FOLLOW(B).

$E\to TX \\
X\to+E|\epsilon \\
T\to(E)|intY \\
Y\to*T|\epsilon$
$E\to \underline {\text{T}}\text{X}\tag{ 2}$
FIRST [X]$-\{\epsilon\}$ $\subseteq $ FOLLOW [T]
{+} $\subseteq $FOLLOW [T]
$T\to (\underline{E})\tag{ 1,2}$
FIRST [ ) ]$-\{\epsilon\}$ $\subseteq $ FOLLOW [E]
{),\$} $\subseteq $FOLLOW [E]

$E\to \text{T}\underline{\text{X}}\tag{ 3}$
FOLLOW(E) $\subseteq$ FOLLOW(X)
$\bullet$ $\epsilon \in FISRT(X) $ so :
FOLLOW(E) $\subseteq$ FOLLOW(T)
$X\to \text{+}\underline{\text{E}}\tag{ 3}$
FOLLOW(X) $\subseteq$ FOLLOW(E)
$T\to \text{int}\underline{\text{Y}}\tag{ 3}$
FOLLOW(T) $\subseteq$ FOLLOW(Y)
$Y\to \text{*}\underline{\text{T}}\tag{ 3}$
FOLLOW(Y) $\subseteq$ FOLLOW(T)

FOLLOW(E) $\subseteq$ FOLLOW(X)
FOLLOW(X) $\subseteq$ FOLLOW(E)

FOLLOW(X) = FOLLOW(E) = $\{),\$\}$

FOLLOW(T) $\subseteq$ FOLLOW(Y)
FOLLOW(Y) $\subseteq$ FOLLOW(T)

FOLLOW(T) = FOLLOW(Y)

{+} $\subseteq$ FOLLOW(T)
FOLLOW(E) $\subseteq$ FOLLOW(T)

FOLLOW(T) = FOLLOW(Y) = $\{),\$,+\}$

(1) FOLLOW(A) $\subseteq$ FOLLOW(B)
 : FOLLOW( B ) contains at least the FOLLOW( A ) as a subset.
(2)First and Follow Sets Example


SSH into newly deployed Container on GCP Compute Engine

Question: I want to simply SSH into a container deployed on GCP Compute Engine without jumping through hoops.
First, I create a compute instance with a container:
gcloud compute instances create-with-container instance_name --container-image gcr.io/my-container-path:latest

Then try to ssh into it:
gcloud compute ssh instance_name --container CONTAINER_NAME

The problem is that the CONTAINER_NAME is unknown. It seems there is no way to set the container name when you create the instance in a deterministic fashion.  So, after you create the instance, you need to run "docker ps" on it to determine the random name before you can use the SSH functionality.
This seems like such a standard usage pattern that I must be missing something. Is there a better way?
Answer: I am not aware of an option to name containers at virtual machine instance creation.
As a solution, you could run a command to list the container images. This command would be run once to get the image name. Put it into a shell script.
gcloud compute ssh $INSTANCE_NAME \
--project $PROJECT_ID \
--zone $ZONE_NAME \
--ssh-key-file $SSH_PRIVATE_KEY \
--command "docker ps"

Note: you can set up the CLI to not require specifying the project and zone to simplify the command:
gcloud config set project PROJECT_ID
gcloud config set compute/zone ZONE_NAME

The command can be simplified more if the instance is using the default SSH private key, which is ~/.ssh/google_compute_engine.
That reduces the command to:
gcloud compute ssh $INSTANCE_NAME --command "docker ps"

Answer: A single command version to connect to the running container:
gcloud compute ssh my-vm --project=my-project  --container=$(gcloud compute ssh my-vm --project=my-project --command 'sudo docker ps --format {{.ID}}')

Comment: Great answer - thank you


Copy path to variable in array using Kint

Question: In D7 using dmp() with Krumo in produced output like this:

Double clicking on a variable value, in this case "foobar" shows the path through the array to that value (the highlighted text in the image above).
Now with D8 it's using Kint not Krumo and produces output like this:

Is there anyway to copy the path to "foobar" using kint?
This is the text that I want: ['example']['#attributes']['class'][0]
Comment: Great question. Right now there is no way that I know of, I ran into the same issue. I used to copy the path in D7 with Search Krumo but as far as I can tell, there is no equivalent in D8 with Kint. This might be a good feature request for the Devel module but it definitely slows down development time in D8.
Comment: Consider using xdebug instead. Since I've started debugging with xdebug & phpstorm I haven't looked back at DPM even once.
Comment: Yeah - I do get xdebug out when the debugging gets really heavy but I also love a quick bit of `dpm`. Search krumo is an awesome module. Maybe I should just write search kint!?!
Comment: @Eyal - Can you point us to a good tutorial on getting started with xdebug/phpstorm (with remote Drupal server if possible) ?
Comment: @NicCottrell look for the tutorials on phpstorm and xdebug.
Answer: It seemed there was no solution so I just copied the search_krumo module and changed it a bit so it works with Drupal 8 and kint and made search_kint.
I've only just done the first push so isn't showing as a download yet; and there is only a development snapshot release, at the moment, but it's something to get started with.
So far, it has worked well with my testing.
EDIT: search_kint now has a full release.
Comment: wow, fantastic, can't wait to try it!


Replace string with Node standard (no query) Sequelize

Question: I have Node server that uses MariaDB (MySQL) via Sequelize.
I have some rows in my db that looks like this, for example:

Id
clips

1
["videoId123456","videoId8910111213"]

2
["videoId123456"]

3
[]

4
["videoId123456"]

The "clips" column is a string, but in an array structure.
My task is to find a way to remove specific videoId from the clips column. For example, if the API route gets the Id "videoId123456", it will be deleted from rows 1,2,4. If it gets the Id "videoId8910111213" it will be deleted from row 1.
I know how to do it by pure MySQL, something like:
UPDATE player
SET clips = REPLACE(clips ,'"videoId1234567"','')
WHERE clips LIKE '%"videoId1234567"%';

I know I can run pure SQL commands with Sequelize as string like:
await sequelize.query(
`   UPDATE player
    SET clips = REPLACE(clips ,'"videoId1234567"','')
    WHERE clips LIKE '%"videoId1234567"%';
`, {
  type: QueryTypes.UPDATE
});

But I wonder if there any way to do it by pure Sequelize, something like:
player.update({
  'clips': 'clips.replace('"videoId1234567"','')'
   where: { 'clips': [Op.like]: '"videoId1234567"' }
});

Thanks.
Comment: Your `clips` look like perfectly valid JSON, which is an observation that guides how you actually work with data in that column. What is the actual table schema? Is the column _really_ a string, or is it a JSON datatype?
Answer: You can use Sequelize.fn amd Sequelize.col to achieve the goal to use the replace SQL function:
player.update({
  clip: Sequelize.fn('replace', Sequelize.col('clip'), '"videoId1234567"','')
}, {
   where: { clip: { [Op.like]: '"videoId1234567"' } }
});

P.S. It would be better not to just replace substrings in this JSON-like array and prefer using SQL functions that can work with JSON to work with an array (if it's applicable to MariaDB).


It's election and graduation eve!

Question: First things first:
CONGRATULATIONS, MAGENTO STACK EXCHANGE IS GRADUATING!
A few weeks ago, I quietly dropped a comment on the 2015 moderator nomination post to say that we on the SE team wouldn't be appointing a new pro tem moderator... because you had been approved for graduation, and we wanted to give you a moderator election instead. The comment didn't seem to get much attention, which was just fine with me; I intentionally didn't make a big deal about it because we didn't have the details ironed out at the time.
But now we do! (Or, at least, we're a lot closer.) As I alluded to above, the fact that you've graduated means that your pro tem mods' terms of service are ending, and you now get to elect your own moderators from within your community. Magento's first moderator election will begin on Monday, August 17, 2015. Please join me in taking a moment to thank Alex, benmarks, Marius and your past pro tem mods for all their work getting the site to where it is today!
Before you get too excited about the upcoming election, there is a bit more news; this isn't just an election announcement. As those of you who follow network-wide events may know, we announced some changes to the way we think about the site lifecycle earlier this year, and the response to that announcement made us start work on breaking up the elements of graduation into independent pieces. On Monday, when your election starts, you'll be the first site that gets to try out this new "graduation without design" approach.
Specifically, this means:

you will no longer see the "beta" label attached to your site's name
you will become eligible for question migration paths with the rest of the network
you will be able to select your own community ads

Since you are the first site to get these features outside of dev, there may be more bugs than normal. Please report any that you see here on meta like you would any other bug.
Comment: What fantastic news! The hard work has paid off!
Comment: WOOOOOOOOHOOOOOO :D
Comment: Brilliant!  Thank you everyone who has put in so much hard work.
Comment: yes.. We reach destiny. Congrts too all..:)
Comment: Wohooo this is the moment we (MSE people) waiting a long for it is looking like a festival with graduation and moderator elections, way to go congrats to everyone and All the Best for nominators
Answer: This has been a long time coming. Thanks for making such an amazing place for us to hang out.
Magento brand team is eager to get involved. In the past I believe that eBay Enterprise's creative team has said they'd help.
Hip-hip-hooray!
Comment: We get an own domain? Looks like @philwinkle owns mageoverflow.com
Comment: Do you still own this www.mageoverflow.com domain we've secured for graduation?
Comment: @fschmengler correct and I'm happy to hand over at any time.
Comment: [It's unlikely that we'll get our own domain](http://meta.stackexchange.com/a/248455/188727), though I'd love it if we did get to use MageOverflow.com.
Answer: This is a great news... Thanks everyone who made this really possible..
We together worked for this a lot. Finally it paid off..
First of all, Thanks to Marius, the great teacher. His work in this site is unimaginable. As a member and moderator of this site, he is always close to us and is directing us in the right way.
Second Kudos goes to #MageStackDay. Thanks Sander and Anna for organizing those amazing days. It brought us from 68% to 82% answer ratio. I can say this event is definitely a historic event for us, the magento community.
Thanks Benmarks and Alex. You are awesome, we are sure.
I want to mention Alanstorm, Fabian, Amit for their amazing contributions to this community..
Finally, congratulations every one... thanks for bring us from beta.. Now inhale and exhale Magento. This is our independence day !!!!
Comment: Thank *you* for your contribution!
Comment: gald to hear that ,,thanks all for contribution
Comment: @philwinkle thanks for u and ur broadcast !!

It's election and graduation eve!


java.lang.NullPointerException with android fragment

Question: I am trying to implement Fragments in my application. The problem occurs when I change tabs (I'm using drawer layout), I get a java.lang.NullPointerException error. I tested the code on the main activity and it worked smoothly. the only problem is when I apply it on fragment. here is the code:
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

public class FragW extends Fragment {
    Spinner spinwatt ;
    Button calculate;
    EditText wattEdit;
    EditText costEdit;
    TextView resultText;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragw,container,false);
        calculate = (Button) getView().findViewById(R.id.calculate);
        wattEdit = (EditText) getView().findViewById(R.id.wattEdit);
        costEdit = (EditText) getView().findViewById(R.id.costEdit);

        calculate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float wattVar = Float.parseFloat(wattEdit.getText().toString());
                float costvar = Float.parseFloat(costEdit.getText().toString());

                if (spinwatt.getSelectedItem().toString().equals("µW"))
                    wattVar = wattVar * (float) 0.000001;
                else if (spinwatt.getSelectedItem().toString().equals("mW"))
                    wattVar = wattVar * (float) 0.001;
                else if (spinwatt.getSelectedItem().toString().equals("kW"))
                    wattVar = wattVar * 1000;
                String resultvar = Float.toString(costvar * wattVar);
                resultText.setText(resultvar);

            }

        });
        spinwatt = (Spinner)getView().findViewById(R.id.spinwatt);
        ArrayAdapter<CharSequence> wattAdapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.wattArray, android.R.layout.simple_spinner_item);
        wattAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinwatt.setAdapter(wattAdapter);

        return v;

    }

Here is the logCat
10-13 12:27:13.429    2563-2563/az.test2 D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-13 12:27:31.468    2563-2563/az.test2 D/AndroidRuntime﹕ Shutting down VM
10-13 12:27:31.468    2563-2563/az.test2 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409961f8)
10-13 12:27:31.488    2563-2563/az.test2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at az.test2.FragW.onCreateView(FragW.java:25)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:795)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:998)
        at android.app.BackStackRecord.run(BackStackRecord.java:622)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1330)
        at android.app.FragmentManagerImpl$1.run(FragmentManager.java:417)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4340)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

Line 25 is: calculate = (Button) getView().findViewById(R.id.calculate);. however, all the lines that are like this cause this error (line 25, 26, 27, 55). I have also tried to initialize the variables with the definitions (in lines 16 to 20) I still got the same error.
Please tell me what to do.
Comment: yet another question about getView inside of onCreateView
Comment: getView is null in onCreateView() because you didn't return view. use in onActivityCreated() or use **v** instead of getView()
Answer: change this
    calculate = (Button) getView().findViewById(R.id.calculate);
    wattEdit = (EditText) getView().findViewById(R.id.wattEdit);
    costEdit = (EditText) getView().findViewById(R.id.costEdit);

to
    calculate = (Button) v.findViewById(R.id.calculate);
    wattEdit = (EditText) v.findViewById(R.id.wattEdit);
    costEdit = (EditText) v.findViewById(R.id.costEdit);

initialized your Views from inflated view in Fragment
Answer: In onCreateView(), getView() returns null as you haven't yet returned the view to the framework.
Call findViewById() on the View v you just inflated instead.
Comment: Thanks for your help, it made me understand my error.
Answer: Your view is not yet created so getView() is null,Therefore change
calculate = (Button) getView().findViewById(R.id.calculate);
wattEdit = (EditText) getView().findViewById(R.id.wattEdit);
costEdit = (EditText) getView().findViewById(R.id.costEdit);
spinwatt = (Spinner)getView().findViewById(R.id.spinwatt);

to
calculate = (Button) v.findViewById(R.id.calculate);
wattEdit = (EditText) v.findViewById(R.id.wattEdit);
costEdit = (EditText) v.findViewById(R.id.costEdit);
spinwatt = (Spinner)v.findViewById(R.id.spinwatt);


When dropping non significant variable (p-value > .4), $R^2$ drops a lot. What can be the reason?

Question: I have a linear model with 7 regressors, where 2 are statistically non significant (p-value > 0.4), with 40 observations. The model has not indication of multicollinearity (tolerances and VIF were accounted for) nor heterocedasticity.
However, when I try to remove one of the non significant regressors, the $R^2$ of the model drops a lot (from 0.7 to 0.4).
What can be the reasoning behind this?
Comment: Is there any missing data? That is, does the sample size increase when you drop this variable? You say you have 40 cases but are you sure that the model with the variable has 40 cases and is not affected by listwise deletion based on missing data?
Comment: It is helpfull to show your model. There are many open ends. For instance: How did you test the significance of those variables, and if If you did Anova which type of sums did you use and what is the F-score and what degrees of freedoms change?
Comment: With N as low as 40, a fairly important covariate can be nonsignificant. They could also be acting as mediators.
Answer: It's apples and oranges. A covariate with a high $p$-value can still increase $R^2$ by a good amount, because more goes into the test that produces the $p$-value than just the increase in proportion of variance accounted for.
Answer: Probably the predictors in question include cases that exert a lot of leverage or influence.  These likely outliers could be contributing a deceptively large amount to the magnitude of coefficients and the model's overall fit.  RSQ could indeed by inflated by such cases, when there is no consistent pattern by which a higher value for the predictor is accompanied by a higher (or lower) value for the outcome.  The mechanism that calculates p-values will "recognize" such a situation.


Sync user accounts over multiple linux servers

Question: What is the best way to sync multiple user accounts and home directories over multiple servers, they will all be the same OS. The servers are in different locations around the world, so if one goes down the others are still available. at the moment there are users on one server but if that server goes down there is no way, other than re-creating users and rsyncing the directories over. So just wondering if there is a better way? I haven't used LDAP but could this be a job for it or not?
Comment: What is the use case for this, BTW? Is the environment for a company spanning the global, a web forum or something a bit different?
Comment: BTW, how many users? And I assume SSO (single sign on?).
Comment: And one more thing: Depending on each server they log, are they supposed to be granted access to specific resources or privileges?
Comment: Sorry for the late reply, everything is on the 'one' server, and all other servers are pretty much just mirrors of each other, with different hostnames, ips (so different servers / same data) the data stays the same on all. and also its no so much for services its more for keeping the user accounts in sync (same passwd on all servers / same gid uid)
Comment: Well, if it isn't too many users, I recommend ErikA's answer.
Answer: I'd recommend starting to use a config management system (Puppet and Chef are two good options at the moment) to deploy user/group data to your servers.
Ideally, you'd have one central LDAP or NIS server, but due to your distributed nature, using a config management system to keep your local user/group databases in sync would be a better option for you.
Answer: You can use LDAP for central user management, with replicas on all servers. And some cluster filesystem for the home directories, like: GlusterFS or XtreemFS.
Answer: You need to weigh the cost of setting up the LDAP server vs the number of users. As others have noted, if you only have a few users, stick to the easy solution.
If you want a LDAP setup, it is also possible to configure your LDAP server in replication across sites and to set the local machines to their local LDAP.
Instructions for OpenLDAP replication.


Delphi 5: Embedding a Software Cert in the final EXE's automatically

Question: I use a Software Certificate for my installation files but would also like it to be embedded in my final Delphi5 program files. I know I can run some command line switch to do this (don't remember exactly what it is since the installation program does it automatically).
I would like to have it embedded in the program when I do a final build. Is there any way to automate this when doing a final build on a project in Delphi5? Might as well get my money's worth from the cert.
Comment: Use signtool from the MS toolset
Comment: Thanks for the answer. Can this be done automatically as the project is being built from within Delphi5?
Comment: No. You have to script that yourself. Write a script to build at command line with dcc32. Later versions of Delphi support build actions.
Comment: I don't remember if D5 supported post-build events, but I don't believe it did, which would mean that it isn't possible from within the IDE.
Comment: @KenWhite no, it did not. Build events are part of the Galileo IDE, which Delphi migrated to in D8.NET.
Answer: The Delphi 5 IDE provides no tools to modify the executable post-build. Later versions of Delphi offer post-build actions. But not Delphi 5.
It is possible to create an IDE plugin that will perform post-build actions. Tools like madExcept and EurekaLog do exactly that for similar reasons.
In order to sign the executable you might use signtool from the MS tool chain. That's what you need to execute after the build.
Personally I am not sure it is that critical for you to sign the executable from IDE builds. You don't need it signed to debug. In your position I would make sure that my release builds were scripted using the command line compiler. At which point signing the executable is a natural task and easy to tack on to the end of the script.
Comment: Specifically `IOTAIDENotifier50.AfterCompile`
Comment: Thanks, all.I have a new app that used a different installer that does the cert stuff for me. I noticed that with that app, neither the download or Windows complained when being installed or run afterward. The older app without the embedded cert in the installation, if embedded with the installer or command line when I upload new updates might indeed work the same way. I mean, no complaints from Windows on installation is a given, no complaints from windows on running might end up being the same as my newer app. Thanks, all.


sql increment line numbering

Question: I am working with oracle and I need incremental line numbering each time i run query. I know usually solution is using rownum but:
query 1:
1  1st row
2  2nd row
3  3rd row

I will now sort query by some value and ouput should be
1 3rd row
2 1st row
3 2nd row

How can I achive that kind of behaveour?
EDIT:
I think my question wasnt clear. I do not need solution using rownum, what i need is simple number at each line of my query it should allways be in sequential order (1,2,3,4,5).
So:
I run a query and my initial results are
Line nr     Some value
1            line 1
2            line 2
3            line 3
4            line 4

Now i will run same query with different order by
Line nr     Some value
1            line 4
2            line 3
3            line 2
4            line 1

Note: I  am interested in column Line nr
Comment: `ROW_NUMBER() OVER (order by some value)`
Comment: @Tagyoureit - Do you want a query which will change the order of rows for every subsequent run?
Comment: Please take another look at my questing i have added additional explanation.
Answer: SELECT ROW_NUMBER() OVER ( ORDER BY some_value ) id,
       value
FROM   your_table
ORDER BY some_value

or:
SELECT ROWNUM AS id,
       value
FROM   (
  SELECT value
  FROM   your_table
  ORDER BY some_value
)

Example:
CREATE TABLE your_table ( value, some_value, some_other_value ) AS
SELECT 'Line 1', 4, 2 FROM DUAL UNION ALL
SELECT 'Line 2', 3, 4 FROM DUAL UNION ALL
SELECT 'Line 3', 2, 1 FROM DUAL UNION ALL
SELECT 'Line 4', 1, 3 FROM DUAL;

Query 1:
SELECT ROW_NUMBER() OVER ( ORDER BY some_value ) id,
       value
FROM   your_table
ORDER BY some_value

Output 1:
        ID VALUE
---------- ------
         1 Line 4
         2 Line 3
         3 Line 2
         4 Line 1

Query 2:
SELECT ROWNUM AS id,
       value
FROM   (
  SELECT value
  FROM   your_table
  ORDER BY some_other_value
)

Output 2:
        ID VALUE
---------- ------
         1 Line 3
         2 Line 1
         3 Line 4
         4 Line 2

Query 3 - Using DESC ordering:
(Remember to update the ordering in both places)
SELECT ROW_NUMBER() OVER ( ORDER BY some_other_value DESC ) id,
       value
FROM   your_table
ORDER BY some_other_value DESC;

Output 3:
        ID VALUE
---------- ------
         1 Line 2
         2 Line 4
         3 Line 1
         4 Line 3

Comment: Please take a look at the example I have added to my answer - it exactly matches your requirements (i.e. `id` is the equivalent of your `line_nr`).
Comment: @Tagyoureit See update 3 - you need to change it to `DESC` ordering in both places. Query 2 is much easier to maintain with respect to changing order as there is only a single `ORDER BY` statement.
Comment: Thank you for this answer but its not what i am looking for. Please take another look at my original question i have explained it a little more into detail.
Comment: Taking from your example (Qerry 1) if i run it as u said i will get correct numbering. But if i take your solution and change order by to desc id (line_nr) will be in descending order. I want it to stay in ASC order all the time. Line number should be in ASC order.
Comment: Ok i really feel and look dumb now. Thank you for pointing out my mistake and thanks for your time.

sql increment line numbering


Does excessive humidity affect the ability to play pianissimo? (On the piano)

Question: I have trouble playing pianissimo but ff produces a good tone. Could humidity have caused this?
Comment: There is information you could add here that will help you get a good answer. For example, could you play pianissimo before? And what kind of problem are you having now: pianissimo is too loud? Doesn't make any sound at all? The keys feel different? More detail will go a long way.
Comment: And especially where your piano is in the world. Others may be in similar climates, and would have first hand experience to share.
Answer: Yes, humidity can affect keys but I suspect your question is deeper than that.
Dynamics come from the speed at which you strike the key.  If you are having problems playing softly, you are not feeling the weight of your arms nor the pull and your arms resistance to gravity.
Play a chord and very slowly play down into the keys from the hinge of your elbow.  Experiment with different speeds to find the even pianissimo sound you desire. Try to play to the point of sound.  That is the little bump you feel when you very slowly depress a key and not make a sound.  You will feel that bump, then with additional pressure, it will give way and you will hit the key bed without making a sound.  Never press into the key bed.  Pressing only produces tension and you can't raise your hand back up because you are pressing down.  You can't move in two directions at the same time.  It is simple physics.  Every motion must have an opposite motion.
Note also when you play that quiet chord, you are not using your fingers but playing from the arm.  Each finger should come from that same source combined with in/out, up/down, rotations, groupings and gravity.   Grouping, rotation and gravity will give you that quiet sound you desire.
Answer: Humidity is the death of a piano.  I hope you're not talking about a grand piano.  Humidity can cause wood and leather to swell or soften, which could most definitely affect the feel, sound and action of the piano.
I very strongly recommend closing windows and running a de-humidifier.
Comment: Pianos are manufactured to suit the climate of the territory they are sold into. If you live in a predominantly humid area & dehumidify the air, you will do as much damage as vice versa.


Example of Quasi-circular domain

Question: Can someone provide me with an example of a quasi-circular domain?
A domain $D\subset\mathbb{C}^n$ is said to be m-quasi-circular, (where $m=(m_1,m_2,..,m_n); m_i$ being positive integers),
if D is invariant under the map $f_{m,\theta}$ for all $\theta \in \mathbb{R}$.
$$f_{m,\theta} : D\rightarrow \mathbb{C}^n$$
$$(z_1,\dots,z_n)\mapsto (e^{im_1\theta}z_1,\dots,e^{im_n\theta}z_n)$$
Note: If $m_1=m_2=m_3=....=m_n=1$, then the domain is called circular domain.
Can you give an example of a quasi-circular domain that is not circular? Say (2,3)-quasi-circular domain in $\mathbb{C}^2$.
Answer: Symmetrized bidisc is a quasi-circular domain that isn't a circular domain.
$$\mathbb{G}=\{(z_1+z_2,z_1z_2)\in \mathbb{C}^2: z_1,z_2\in B(0,1)\}$$
Clearly, this is a (1,2)-quasi-circular domain.
To see that this is not a circular domain, notice that $(2,1)\in \bar{\mathbb{G}}$ but $(-2,-1)\not \in \overline{\mathbb{G}}$.

Example of Quasi-circular domain


Ephemeral vs. EBS vs. Amazon S3

Question: I am trying to determine what storage to use for Cassandra and Cassandra backups.  EBS is the most expensive of the lot so that one I may have pretty much eliminated.  ephemeral storage is cheaper compared to S3 if I am planning to commit to pay upfront for 3 years.  Not sure how it compares relative to S3 in terms of performance.  Anyone have experience for the two use cases (running a database and storage for backup)?
Answer: With Cassandra its recommended to use ephemeral for you data and backups to S3. EBS is generally considered an anti-pattern and not recommended but the ssds can work.  Check out http://docs.datastax.com/en/cassandra/2.1/cassandra/planning/architecturePlanningEC2_c.html
Comment: Why not use ephemeral storage for backup as well?  It is cheaper than S3 and I am guessing faster from a recovery standpoint?
Comment: cheaper mostly, tend to have a lot of backups. You want to keep your data drives ~50% empty if using default compaction strategies so you don't want too many snapshots sitting around. Also with data going away with ephemeral you get a little more safety.
Comment: Do not use ephemeral storage for backups. The contents will be lost if the instance is stopped. Amazon S3 does not have any storage space limits, so you can keep your backups as long as desired. BTW, Netflix uses Cassandra on Amazon EC2, storing data on ephemeral volumes. Just search YouTube for a video at an AWS or C* conference.
Answer: The idea is that you store your database files on EBS, your cache files on ephemeral storage and your backups are saved to S3.
Ephemeral storage is purely for the purpose of temporary caching. It is deleted whenever the server reboots. If the box goes down you lose everything on it. DO NOT store important data on Ephemeral storage!
EBS is a SAN attached disk, you can stripe data across them to produce the performance you need. It is designed for storing working data on, and is safe from anything that could happen to the VM.
S3 is akin to a remote file share, it doesn't have the performance you need to install working data to, and can't (easily) be mounted, hence is ideal for backing up to. You can then have archiving and long term storage options set.
Edited to be more Cassandra specific
While Cassandra is designed to be fault tolerant, and accept the complete loss of cluster nodes. Unless you are designing it to be heavily distributed across multiple regions you still run the risk of losing all of your data up to the point of your last back up if you don't use EBS volumes. Since you are concerned about cost I am guessing that you aren't looking to be massively distributed, so it would be more cost effective to have all of your databases on EBS volumes that way if a region fails you won't lose data to ephemeral storage.
Comment: There is no practical reason to avoid EBS anymore - gp2 gives predicable iops, and EBS optimized instances give more than enough performance, Cassandra can easily max out CPUs without taxing gp2. The was reliability issues have been addressed, it's no longer a spof in a region.
Comment: Are you sure about ephemeral storage being lost across reboots?  I read somewhere (probably on stackoverflow) that data survives over reboots but not if  you shut down the instance.  If my information is accurate, what is the downside of using ephemeral storage?
Comment: @JayDesai the problem is that it isn't guaranteed to survive, generally if you reboot ephemeral storage will stay, but if the host your machine is running on is approaching a maintenance schedule you would be transferred to another host and lose the storage. Also if there is an issue with the region / host you will lose the storage.
Comment: You generally get the safety from ephemeral drive shutdowns by spreading data across different regions and availability zones. EBS should generally be avoided unless you have strong reasons. In this C* has different recommendations than other databases. Its focus on high availability and great multi-dc replication makes the data durability in ephemerals less of a concern.

Ephemeral vs. EBS vs. Amazon S3


InputText component behaves unexpectedly

Question: To add events and formatters to the InputText component of Blazor, I have created an inherited component, InputText2.
It looks like this:
public class InputText2 : InputText
{
    [Parameter]
    public Action<string> OnBlur { get; set; }

    [Parameter]
    public Func<string, string> Formatter { get; set; }

    protected override bool TryParseValueFromString(string value, out string result, [NotNullWhen(false)] out string validationErrorMessage)
    {
        var parseResult = base.TryParseValueFromString(value, out result, out validationErrorMessage);

        OnBlur?.Invoke(value);

        return parseResult;
    }

    protected override string FormatValueAsString(string value)
    {
        var result = Formatter?.Invoke(value) ?? value;
        //CurrentValueAsString = result;

        return result;
    }
}

The Formatter parameter takes a Func that modifies the string in some way. In my example, I wanted postal codes in the format "12345" to be formatted "123 45". In FormatValueAsString, result gets the correct value, but this is not reflected in the UI after rendering. However, if I do set CurrentValueAsString to result, then it works. But I can't find any reason for this. And in other examples, that property is never touched either. Also, it seems to be able to create loops between FormatValueAsString and TryParseValueFromString.
Anyone seen this before?
Answer: FormatValueAsString is just used by InputBase to format the CurrentValue in the getter for CurrentValueAsString.
The value that is bound to the input control and hence what you see on the page is the value of CurrentValue
So, if you want the displayed value to use the formatted value, you need to set CurrentValue to that formatted value - and this is what happens when you include the line to set CurrentValueAsString = result - the setter on CurrentValueAsString sets CurrentValue.


How i can get user desktop path from windows services?

Question: This is my code, i need my service to make a shortcut to an application on user desktop if the shortcut not exist. when i debug my application inside visual studio it will put the shortcut on my desktop, but when i run the service on windows it always will put the shortcut on C Drive not on my desktop.
<code>  private void CreateShortcut()
    {
        object shDesktop = (object)"Desktop";
        WshShell shell = new WshShell();
        //string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        string shortcutAddress = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\CadEisancy.lnk";
        IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
        shortcut.Description = "New shortcut for a Notepad";
        shortcut.Hotkey = "Ctrl+Shift+N";
        shortcut.TargetPath = @"C:\RankWindowsApp\RankWindowsApp\bin\Debug\RankWindowsApp.exe";
        shortcut.IconLocation = @"C:\RankWindowsApp\Icon.ico";
        shortcut.Save();
    }
    protected override void OnStart(string[] args)
    {
        //Create Shortcut On Desktop
        CreateShortcut();
    }
</code>
My code:
![MyCode][1]
Comment: Duplicate to https://stackoverflow.com/questions/22232646/enumerate-windows-of-user-desktop-on-another-session
Comment: If you dig further enough, you should see why this one is duplicate. Windows session isolation is a complex concept that most developers don't realize, but everyone who writes Windows service must study it, or questions like yours won't be answered/resolved. The linked thread already covers the necessary background information.
Comment: Hi! Please post your code in a `code` block and not as image.
Comment: @LexLi Its not duplicated.
Answer: The solution is to get the current logged user session code, then get the name of his Profile depending on the session and finally we can specify his desktop path.
Answer: How  your service is configured ? If you are not running under user account, the service will use its own profile as you see in your output .
I have answered mostly similar answer in the following look. Please have a look if you feel that helps.
https://stackoverflow.com/a/46540108/1556780
Comment: Thank you.The solution is to get the current logged user session code, then get the name of his Profile depending on the session and finally we can specify his desktop path.


Topology of algebraic variety

Question: I have an algebraic variety given by a polynomial $1+x(1+y)^2$ over $\mathbb C$. Is there any reasonable way to see how topologically the algebraic variety defined by this polynomial looks like?
Comment: In your case it's easy to see that your curve is isomorphic to $\Bbb C^*$
Comment: Your curve is $\{ (\frac{-1}{z^2}, z-1), z \in \Bbb{C}^*\}$ which is isomorphic to $\Bbb{C}^*$. To *see* it, look first at $\{ (\frac{1}{z}, z), z \in \Bbb{C}^*\}$ then apply $(u,v) \to (-u^2,v-1)$
Answer: The open sets of that variety are the variety itself take away finite number of (algebraic) curves and points. Is this what you mean by "topologically see"?

Topology of algebraic variety


Why Mathematica (Reduce) can't find clear solution for almost trivial inequalities?

Question: Suppose we want to solve the inequality $ax^2+bx+c<0$. For simplicity, presume that $a>0$ and $b^2-4ac>0$. In this form, this is almost a trivial problem. Despite that, if we want to solve it with Mathematica (Reduce), version 8, the
Assuming[a > 0 && b^2 - 4*a*c > 0, Reduce[a*x^2 + b*x + c < 0, x, Reals]]

command generates dozens of lines (instead of simply being -(b/(2 a)) - 1/2 Sqrt[(b^2 - 4 a c)/a^2] < x < -(b/(2 a)) + 1/2 Sqrt[(b^2 - 4 a c)/a^2], in which this solution is present somewhere deeply, but it is full of

unnecessary case separations (as if it couldn't interpret the $b^2-4ac<0$ condition, and although it was given as assumption, it repeats this in the solution in equivalent forms),
impossible conditions (such as $a\leq 0$ which should have been ruled out by the assumptions),
branches with clearly contradictory conditions (such as x < -(b/(2 a)) - 1/2 Sqrt[(b^2 - 4 a c)/a^2] ||  x > -(b/(2 a)) - 1/2 Sqrt[(b^2 - 4 a c)/a^2] at the very beginning).

The usage of
Reduce[{a > 0, b^2 - 4*a*c > 0, a*x^2 + b*x + c < 0}, x, Reals]

and especially
FullSimplify[Reduce[{a > 0, b^2 - 4*a*c > 0, a*x^2 + b*x + c < 0}, x, Reals]]

alleviates the issue a bit (which is itself surprising given of what Assuming should do... or at least what I thought it should do...), but it is still far from what I've expected as a result. (Especially because this last command, although it produces the shortest output, it doesn't even give an explicit solution for $x$.)
Thank you in advance!
Comment: How about `FullSimplify[Reduce[{a x^2 + b x + c < 0, b^2 > 4 a c, a > 0}, x, Reals, Backsubstitution -> True], b^2 > 4 a c && a > 0]`? The problem with using FullSimplify on its own is that it assumes nothing; you have to either give assumptions as its second argument, or wrap it in `Assume[]`.
Comment: @Greg, the third domain argument for `Reduce[]` ensures that every variable is treated as a member of the domain. On the other hand, since everything in the first argument is an inequality, using `Reals` is in fact not needed...
Comment: Clearly, what Mathematica finds almost trivial and what you find almost trivial are two entirely different things. Solving inequalities algorithmically is not an easy problem. Did you make sure that $b$ and $c$ are treated as real numbers as well?
Answer: As far as I know, Reduce doesn't use the assumptions system, only Refine, Simplify, FullSimplify and FunctionExpand do.
So you could manually put the assumptions into Reduce, then remove them from the result using the simplify mechanism:
$Assumptions = a > 0 && b^2 - 4*a*c > 0;
Reduce[a*x^2 + b*x + c < 0 && $Assumptions, x] // FullSimplify

which yields

If you include $b\neq0$ in your assumptions, then you get the simple result that you're looking for:
$Assumptions = a > 0 && b^2 - 4*a*c > 0 && b != 0;
Reduce[a*x^2 + b*x + c < 0 && $Assumptions, x] // FullSimplify

(* Returns:
(-b - Sqrt[b^2 - 4 a c])/(2 a) < x < (-b + Sqrt[b^2 - 4 a c])/(2 a)
*)

Comment: @Tamas: The $b\neq0$ assumption is not included in the $b^2>4ac$ assumption, since $c$ can be less than zero. This is (almost) clear from the image posted in my answer. PS If you're happy with the answer, press the tick button to accept it!
Comment: I just noticed that this is basically what J.M. did in the comments above (although the `Backsubstitution -> True` was not necessary).
Comment: Ah, it works without that option. Great! :) Of course, the only trouble with mucking with `$Assumptions` is that you might forget that you assigned values to it, especially with long sessions. If you can't trust your memory, it is best to use `Assume[]` instead.
Comment: @J.M.: Sure, for one off assumptions, the explicit argument or `Assumptions` option or `Assuming[]` is best. `Assuming` basically just `Block`s `$Assumptions` anyway.
Comment: @ J. M.: Actually, by including b!=0 it works perfectly! (As well - obviously these are equivalent approaches.) Thank you!
Comment: @Simon: Thank you very much, this is exactly what I was looking for! The only interesting thing is the necessity of the b!=0 condition. Even if b=0, the solution should be still (-b - Sqrt[b^2 - 4 a c])/(2 a) < x < (-b + Sqrt[b^2 - 4 a c])/(2 a), shouldn't it? I understand that there is no solution if b=0 and c>0 (which is implied by Mathematica's output without the b!=0 condition), but this is INCLUDED in the b^2>4ac assumption...
Comment: @Simon: Sure! :) I was just waiting for your answer on this "additional" question!