StrokeType.OUTSIDE causes high amounts of lag when used on a label inside a ScrollPane

Question: public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        ScrollPane scrollPane = new ScrollPane();
        VBox vbox = new VBox();

        for (int i = 0; i < 50; i++) {
            Label label = new Label("Label " + i);
            label.getStyleClass().add("test");
            vbox.getChildren().add(label);
        }

        scrollPane.setContent(vbox);

        Scene scene = new Scene(scrollPane, 500, 500);
        primaryStage.setScene(scene);
        scene.getStylesheets().add("/style.css");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

style.css:
.test.label .text {
    -fx-fill: white;
    -fx-stroke: red;
    -fx-stroke-type: outside;
}

JDK and JavaFX 13
The labels render just fine but when I try to scroll it lags really much.
I expect it to be as smooth as it is when used without -fx-stroke-type: outside;, for example, replacing the contents of style.css with
.test.label .text {
    -fx-fill: white;
    -fx-stroke: red;
    /* -fx-stroke-type: outside; */
}

fixes the scrolling lag but the stroke overlaps the fill as it is drawn inside of the text.
I've tried running with Java and JavaFX 11 as well but there was no difference.
Comment: That performance is terrible.  I recommend [filing a bug report](https://wiki.openjdk.java.net/display/OpenJFX/Submitting+a+Bug+Report).
Comment: What is ScrollType.OUTSIDE?  Did you mean to write "stroke-type: outside" in the title?
Comment: Yes, that's correct. I will fix it now.
Comment: @jewelsea Thanks for the suggestion, I submitted a bug and I hope it gets fixed soon but meanwhile I will use the workaround I posted below.
Answer: I worked out how to get better performance on the scrolling without using Nand's work-around.  I used some of the advice from this question:

JavaFx animation poor performance, consumes all my CPU

Specifically, the advice to cache nodes:
node.setCache(true);
node.setCacheShape(true);
node.setCacheHint(CacheHint.SPEED);

Once I added these function calls to the labels generated in Nand's test program, scrolling performance was perfectly fine (rather than visibly incredibly laggy).
The initial drawing of the scene, before the rendering is cached is a bit slow (it takes a second or so).  The slowness of the initial drawing can be best observed if you increase the number of labels from 50 to 500.  But, once the scene has been drawn once and the nodes cached, scrolling no longer slows down the frames per second performance of the application.
In context, this solution is:
public void start(Stage primaryStage) {
    ScrollPane scrollPane = new ScrollPane();
    VBox vbox = new VBox();

    for (int i = 0; i < 500; i++) {
        Label label = new Label("Label " + i);
        label.getStyleClass().add("test");
        vbox.getChildren().add(label);

        label.setCache(true);
        label.setCacheShape(true);
        label.setCacheHint(CacheHint.SPEED);
    }

    scrollPane.setContent(vbox);

    Scene scene = new Scene(scrollPane, 500, 500);
    primaryStage.setScene(scene);
    scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
    primaryStage.show();
}

where style.css is as supplied in the question.
To speed up the initial drawing of the scene you can use a drop shadow effect, which simulates the outline, providing a similar look.  Different settings for the effect (e.g. using one-pass-box rather than gaussian), will provide slightly different rendering, so it is a bit customizable.
.shadow-outline.label .text {
    -fx-fill: white;
    -fx-effect: dropshadow(gaussian, red, 1, 1.0, 0, 0);
}

Answer: I created a workaround so that I can use this feature until this bug is solved. (I've reported it to Oracle).
    public static Canvas outlined(Font font, Color fill, Color stroke, String text) {
        Text temp = new Text(text);
        temp.setFont(font);
        Bounds bounds = temp.getBoundsInLocal();
        Canvas canvas = new Canvas(bounds.getWidth(), bounds.getHeight());
        GraphicsContext ctx = canvas.getGraphicsContext2D();
        ctx.setFont(font);
        ctx.setTextBaseline(VPos.TOP);
        ctx.setFill(stroke);
        ctx.fillText(text, -1, -1);
        ctx.fillText(text, 1, -1);
        ctx.fillText(text, -1, 0);
        ctx.fillText(text, 1, 0);
        ctx.fillText(text, -1, 1);
        ctx.fillText(text, 1, 1);
        ctx.fillText(text, 0, 0);
        ctx.setFill(fill);
        ctx.fillText(text, 0, 0);
        return canvas;
    }

I know it can probably be improved to support stroke-width higher than 1 but I do not need that feature at the moment so this is enough for me.


calling asp.net mvc action method using jquery post method expires the session

Question: i have a website where i provicde a link. On clicking the link a controller action method is called to generate a zip file after creation of zip file is done, i show the link to download the zip file by replacing the link to create a zip with the link to download the zip.
the problem is that after zip file creation is over and link is shown, when user clicks on the link to download the zip file, they are sent to login. After providing correct credentials in the login page they are prompted to download the zip file. they sould not be sent to the login page. In the action to generate zip file i haven't abondoned the session or haven't not done anything that abondons the session.
the user should not be sen't to login page after successful creation of zip file user should be able to download the file without login.
i search internet on this problem, but i did not find any solution. In one of the blog written by hanselman i found this statement that creates the problem with the session: Is some other thing like an Ajax call or IE's Content Advisor simultaneously hitting the default page or login page and causing a race condition that calls Session.Abandon? (It's happened before!)
so i thought there might be some problem with ajax call that causes the session to expire, but i don't know what is happening?
any help
please
thanks
Comment: Try and narrow down the problem first.
Comment: it's like this after users click on the link to create zip file the zip file is created successfully but the session gets expired. this is not what i want.

Why does the session has to get expired after making a jquery post call to controller action to create a zip file?

i hope u understand the problem.
Answer: guys i found the solution to this problem. The problem was like this: I created a zip file in application folder and in .net 2.0 it is a rule that any change to the application files and folder causes the session to expire. As soon i created the zip file in the directory somewhere other than directory in application folder, everything worked fine.
anyways
thanks
Answer: I think problem is with permission on the folder where you've created the Zip file.
Answer: The Session has nothing to do with access to ressources.
If a prompt is shown to login it means that the resource that the user wants to donwload is protect by FormsAuthenication or WindowsAuthentication.
If you dont want this, then check the Authorisation section in web.config.
Comment: even if don't click the link to download and click other links on the web page, i get the login.
Comment: Does this happen on your local development webserver, local iis or on a production webserver?
Comment: it happens both while debugging in visual studio and on production server. i have already hosted the website, and yes it happens even there.
Comment: In this post http://www.hanselman.com/blog/TroubleshootingExpiredASPNETSessionStateAndYourOptions.aspx under troubleshooting section Scott Hanselman has written this: Is some other thing like an Ajax call or IE's Content Advisor simultaneously hitting the default page or login page and causing a race condition that calls Session.Abandon? (It's happened before!)
Comment: i am using jquery post method to call the controller action to create zip file.


Proof that for $a,b,c\in \mathbb{R}$, hold that $\left |\sqrt {a^2+b^2}-\sqrt {a^2+c^2} \right |\leq \left |b-c \right |$.

Question: Proof that for $a,b,c\in \mathbb{R}$, hold that $\left |\sqrt {a^2+b^2}-\sqrt {a^2+c^2}  \right |\leq \left |b-c  \right |$.
Give me a clue, I don't have any idea to work with that inequality.
Comment: Nothing bad will happen if you upvote from time to time the answers you get. I see that you have 18 questions asked with a lot of answers on them and only a single upvote...
Answer: $$
\left|\sqrt {a^2+b^2} - \sqrt {a^2+c^2}\right| =\frac{\lvert b^2-c^2\rvert}{\left|\sqrt {a^2+b^2} + \sqrt {a^2+c^2}\right|}
= \big||b| - |c|\big|\cdot \frac{|b| + |c|}{\left|\sqrt {a^2+b^2} + \sqrt {a^2+c^2}\right|}
 \\\leq \big||b| - |c|\big|\le |b-c|
$$
Answer: Apply the Mean value theorem to the function $f(x)=\sqrt{a^2+x^2}$.
Answer: Consider the points with coordinates $A(0,a),B(b,0),C(c,0)$.
You are stating that the sides of $ABC$ fulfill the triangular inequality.


Bootstrap Nav Collapse via Data Attributes Not Working

Question: I'm trying to get a Twitter Bootstrap 3 navbar to collapse via data attributes but it's not expanding.
For reference, the project is an ASP.NET C# MVC project running DNN (DotNetNuke) CMS.
When manually calling the collapse method via javascript it works fine for example:
$('#main-menu').collapse()

This leads me to believe that the javascript files are fine and something's wrong with the data attributes. I've compared every element to a working example and cannot see what's causing the issue. Here's the complied HTML:

            <button class="navbar-toggle collapsed" data-target="#main-menu-collapse" data-toggle="collaspe" aria-expanded="false">
                Toggle Navigation

            </button>

Home

                    BG New Page

Some Page

Some More Context

FWIW, removing the navbar-style class makes no difference.
Comment: FYI, I've voted to close as off-topic
Comment: Change that `data-toggle=collaspe` to `data-toggle=collapse`.
Comment: @ImmanuelValle Thanks, stupid typo!!
Answer: Change data-toggle="collaspe" to data-toggle="collapse".


Issue Understanding Lighting in OpenGL

Question: I am having some problems understanding how lighting works in OpenGL (especially understanding the pre-defined variables. is there a list of them somewhere?). I have been messing around in my Vertex Shader file to shade my shpere. So I managed to shade it but I don't know what I did. Here is the code:
Vertex Shader:
#version 330
precision highp float;

in vec3 in_Position; //declare position
in vec3 in_Color; //color passed from the cpp file

//mycode
in vec3 in_Normal;

// mvpmatrix is the result of multiplying the model, view, and projection matrices */
uniform mat4 MVP_matrix;

vec3 ambient;

out vec3 ex_Color;

void main(void) {

// Multiply the MVP_ matrix by the vertex to obtain our final vertex position (mvp was created in *.cpp)

gl_Position = MVP_matrix * vec4(in_Position, 1.0);

//mycode
ambient = vec3(0.0f,0.1f,1.0f); // just a test vector

ambient = ambient * in_Position ; // HERE IS WHAT I DONT GET!

ex_Color = ambient;

}

I am multiplying each point on the sphere with a MVP matrix, and then with an ambient variable.
Fragment Shader:
#version 330
precision highp float;

in vec3 ex_Color;
out vec4 gl_FragColor;

void main(void) {

gl_FragColor = vec4(ex_Color,1.0);

}

What does "precision highp float;" does? I know that the vertex file passes the color to the  fragment shader and then that fragment gets "interpolated". Ok how does interpolation works? How does Opengl know where to stop the interpolation ?
Comment: "is there a list of them somewhere" Yes. [The OpenGL specification.](http://www.opengl.org/registry/) Really, you need to stop asking these questions piecemeal and just go [look up a good tutorial already](http://www.opengl.org/wiki/Getting_started#Tutorials_and_How_To_Guides). These kinds of questions aren't doing anyone any good. You're basically asking, "How does this entire part of OpenGL work?"
Comment: @TrtTrt: You don't want to take the time to learn correctly, so instead you ask us to basically write tutorials for you. I'm not sure I understand your logic. And what's wrong with using "custom libraries"? Or do you believe that you gain something by reinventing the wheel? Learning something as complicated as graphics programming requires being able to cut right to the actual issue at hand. And that means using libraries to deal with things that _don't matter_.
Comment: @NicolBolas: This "I don't have time" argument, and the whole lot of questions asked by Trt Trt remind me awfully of Skybuck Flying over at the comp.graphics.api.opengl newsgroup http://goo.gl/UTDik
Comment: @NicolBolas I am aware of the tutorials, I just don't have time, and most of them use custom libraries. SO that's why I asked this.
Answer: ambient = ambient * in_Position ; // HERE IS WHAT I DONT GET!

That makes two of us. I have no idea what it is that you intend to accomplish with this. That will certainly produce a color. But it won't be meaningful in any real way. It certainly doesn't qualify as "lighting".

What does "precision highp float;" does?

Nothing. Not in desktop OpenGL. I really have no idea why someone put that there; the precision highp stuff is for GL ES compatibility, but version 3.30 shaders are fundamentally incompatible with GL ES 2.0, since ES 2.0 doesn't use in/out qualifiers and desktop GLSL 3.30 does.

Ok how does interpolation works?

Way too broad to answer here. This is better answered here, which is part of my much larger tutorial series.

How does Opengl know where to stop the interpolation ?

The edge of your triangle.

Issue Understanding Lighting in OpenGL


Problema Nextval Postgres Delphi

Question: Estou fazendo uma aplicação, no qual preciso incrementar uma sequence e verificar se aquele valor já foi usado em outra tabela, pois caso já tenha sido devo ignorar e gerar um novo valor para a sequence até encontrar um valor único.
Esse é meu SQL:
select nextval('controlesequencia')as proximo,  -1 as soma
union
select currval('controlesequencia') as proximo, sum(quantidade) as soma from (
select count(*) as quantidade from manobrista where
CAST(('0' || COALESCE(segundo_codigo,'0')) AS INTEGER) = currval('controlesequencia')
union
select count(*) as quantidade from lancamento where
CAST(('0' || COALESCE(num_registro,'0')) AS INTEGER) = currval('controlesequencia') and data_saida = '') as mensalista

Quando executo no Delphi o valor retornado no nextval é um caractere estranho do mapa de caracteres.
DM.ProximoControle.FieldByName(Proximo).AsInteger;

Como faço para pegar o valor corretamente?
Comment: Diretamente no banco o sql funciona normalmente sem problema.
Comment: Você poderia mostrar um pouco a mais do código? Onde você viu o caracter estranho? Foi no debug?
Comment: Você disse quando quando executa no delphi retorna um caracter estranho, qual é ele?
Se tentar direto no banco de dados o sql funciona normalmente?
Comment: O Delphi não consegue converter o valor retornado para integer, quando troco para outro retorno, por exemplo, string o retorno não é um inteiro é um caracter.
Comment: //Procedimento que abre o sql, e executa a consulta apenas abre e fecha o sql

DM.GetProximoControle();
While DM.ProximoControle.eof do
begin
 if(DM.ProximoControle.FieldByName(SOMA).AsInteger =0) then
       begin
      unico := DM.ProximoControle.FieldByName(PROXIMO).AsInteger;
      break;
  end;
 DM.ProximoControle.next;
end;
Comment: Você tentou fazer um cast para bigint ? tipo: select cast(nextval('controlesequencia') as bigint) as proximo,  -1 as soma ...
Comment: Como esse código q VC postou esta funcionando se a pergunta do seu while esta eof quando deveria ser not eof ?@Priscila Almeida
Answer: DM.GetProximoControle();
While DM.ProximoControle.eof do
 begin
   if(DM.ProximoControle.FieldByName(SOMA).AsInteger    =0) then begin  unico := DM.ProximoControle.FieldByName(PROXIMO).AsInteger; break;
 end;
DM.ProximoControle.next;

Essa rotina esta sendo executada de forma errada, pois mesmo sem fazer testes e possível perceber, que  a pergunta no while  esta errada porque mesmo quando temos apenas um registro e queremos iterara-lo devemos colocar not eof para que o bloco seja executado pelo menos uma vez.
Assim o resultado dessa rotina é inesperado.

Problema Nextval Postgres Delphi


Help on population differential equation

Question:
$$\frac{\mathrm dr}{\mathrm dt} = kr \left(1-\frac{r}{r_*}\right) -\alpha fr,$$
  where $k>0$ is a constant representing the rabbit breeding rate, $r_*>0$ is the (constant) maximun sustainable rabbit population size in the absence of predation, $f>0$ is the population of foxes, and $\alpha>0$ is the (constant) rate or predation of rabbits by foxes.

I am told that the fox population is constant.
I'm trying to solve this differential equation. I tried using the Bernoulli equation method, however it did not work out, which is shown here (habbit of mine is I accidently made $r_*$ that was for the maximum sustainable rabbit population size in the absence of predation later into $A$ since it was easier:)
$$\frac{\mathrm dr}{\mathrm dt} = kr -\frac{kr^2}{r_*} -\alpha fr$$
Define $w(t)$ by $w=r^{1-2}=\frac{1}{r}$, so that $$\frac{\mathrm dw}{\mathrm dt} = -\frac{1}{r^2} \frac{\mathrm dr}{\mathrm dt}$$
$$\implies \frac{\mathrm dw}{\mathrm dt} +kw = \frac{k}{r_*} +\alpha fw,$$
where this would become $$e^{kt} w(t) = \frac{e^{kt}}{A} +\frac{\alpha fwe^{kt}}{k} +c.$$
As I made $m(t)=k$, leading to $e^{\int k} = e^{kt}$ and the left hand side was inverse product rule and the right hand side was integration
$$ \implies w(t) =\frac{1}{A} +\frac{\alpha fw}{k} +ce^{-kt}$$
$$\implies r(t) = A +\frac{k}{\alpha fw} +\frac{e^{kt}}{c}$$
Comment: Why not just write the problem as $$r' = r(C_{1} + C_{2} r)$$ where $C_{1} = k-\alpha f$, $C_{2} = -k/r^{*}$. This is clearly separable.
Answer: The equation is separable.  To better see this, start by multiplying everything out and collecting up the constants:
$$\frac{\mathrm dr}{\mathrm dt}
= kr \left(1-\frac{r}{r_*}\right) -\alpha fr
= kr - \frac{kr^2}{r_*} - \alpha f r
= \underbrace{-\frac{k}{r_*}}_{A}r^2 + \underbrace{(k-\alpha f)}_{B}r
= Ar^2 + Br,$$
which is more clearly separable.  In particular (by a standard abuse of notation), it may be rewritten as
$$
\frac{1}{Ar^2 + Br} \,\mathrm{d}r = \mathrm{d}t
\implies \int \frac{1}{Ar^2 + Br} \,\mathrm{d}r = \int \mathrm{d}t.
$$
As far as the differential equation is concerned, I would say that we are basically done at this point.  However, we probably want something a little more explicit, so maybe we ought to carry out the integration.
The right-hand side is relatively easy to work with, so let's ignore that for now.  On the left-hand side, complete the square in the denominator to get
$$
\int \frac{1}{Ar^2 + Br} \,\mathrm{d}r
= \int \frac{1}{A\left(r + \frac{B}{2A}\right)^2 - \frac{B^2}{4A}}\,\mathrm{d}r.
$$
Make the change of variables $s = r + B/2A$ to obtaina
$$
\int \frac{1}{A\left(r + \frac{B}{2A}\right)^2 - \frac{B^2}{4A}}\,\mathrm{d}r
= \int \frac{1}{As^2 - \frac{B^2}{4A}}\,\mathrm{d}s
= \frac{1}{A} \int \frac{1}{s^2 - \left(\frac{B}{2A}\right)^2}\,\mathrm{d}s
= \frac{1}{A} \int \frac{1}{s^2 - C^2}\,\mathrm{d}s,
$$
where $C = B/2A$ (gathering up the constants so that we don't have to deal with them).  While there are more clever approaches that one might take here, I think that cranking out the partial fractions is the most elementary thing which we could do.  This gives us
\begin{align}
\frac{1}{A} \int \frac{1}{s^2 - C^2}\,\mathrm{d}s
&= \frac{1}{A} \int \frac{1}{2C(s-C)} - \frac{1}{2C(s+C)} \,\mathrm{d}s \\
&= \frac{1}{2AC} \int \frac{1}{s-C} - \frac{1}{s+C} \,\mathrm{d}s \\
&= \frac{1}{2AC}\left( \log(s-C) - \log(s+C) \right) \\
&= \frac{1}{2AC} \log\left( \frac{s-C}{s+C} \right),
\end{align}
where I am assuming (in the last step) that $s > |C|$.  This is a reasonable assumption, as $s$ is related to the population of rabbits, which itself must be a positive number.  At this point, the original right-hand integral has been evaluated.  The next step is to restore the original variable $r$, using the fact that $s = r+C$.
\begin{align}
t + K
&= \int \,\mathrm{d}t \tag{$K$ is the constant of integration} \\
&= \int \frac{1}{Ar^2 + Br} \,\mathrm{d}r \\
&= \frac{1}{2AC} \int \frac{1}{s-C} - \frac{1}{s+C} \,\mathrm{d}S \\
&= \frac{1}{2AC} \log\left( \frac{s-C}{s+C} \right) \\
&= \frac{1}{2AC} \log\left( \frac{r}{r+\frac{B}{A}} \right).
\end{align}
Since the goal is to determine the rabbit population $r$, we solve to get
\begin{align}
&t + K = \frac{1}{2AC} \log\left( \frac{r}{r+\frac{B}{A}} \right) \\
&\qquad\implies 2ACt + K = \log\left( \frac{r}{r+\frac{B}{A}} \right) \tag{note: this is not the same $K$} \\
&\qquad\implies K \mathrm{e}^{2ACt} = \frac{r}{r+\frac{B}{A}} \tag{$K$ changed again} \\
&\qquad\implies \left( K \mathrm{e}^{2ACt} - 1 \right)r = -\frac{B}{A}K \mathrm{e}^{2ACt} \\
&\qquad\implies r = \frac{B}{A}K \left( \frac{\mathrm{e}^{2ACt}}{1 - K \mathrm{e}^{2ACt}} \right) = -\frac{B}{A} \left( \frac{\mathrm{e}^{2ACt}}{K + \mathrm{e}^{2ACt}} \right). \tag{$K$ changes again here}
\end{align}
Finally, restoring the original constants from
$$ A = -\frac{k}{r_*},
\quad
B = k-\alpha f,
\quad\text{and}\quad
2AC = 2A\frac{B}{2A} = B = k-\alpha f, $$
we obtain the solution
$$
\boxed{r(t) = \frac{r_*(k-\alpha f)}{k} \left( \frac{\mathrm{e}^{(k-\alpha f)t}}{K + \mathrm{e}^{(k-\alpha f)t}} \right).}
$$
I am sure that there are some silly arithmetic errors in here somewhere, but I'll be damned if I can find them.  In any event, I built a Desmos demonstration which can be used to play around with this a bit.  The curves that I get for "reasonable" values of the constants look like logistic growth curves, which is what we would expect.  So, I think I did something right.
Comment: Nice detailed answer. Note that partial fractions on $[r(Ar+B)]^{-1}$ would give you the result directly instead of partial fractions on $(s^2-C^2)^{-1}$.
Comment: @TheSimpliFire Indeed.  That would have been easier.  Don't know why I didn't see that. :(


Variables cancelling after matrix rotation

Question: Matrix Rotation Question
The above question is from a past exam paper.  Unfortunately, I am struggling with the arithmetic as follows:
Using the standard 2D matrix rotation transformation, i obtained the following equations:
$$
\frac{a}{2} - \frac{3^{1/2}b}{2} = b
$$
$$
\frac{3^{1/2}a}{2} + \frac{b}{2} = a
$$
However when I try to solve these, the variables cancel. Is this intended or is my approach/procedure incorrect?
EDIT: here is my solution:
(from the standard 2D rotation matrix)
$$
cos\frac{\pi}{3}a - sin\frac{\pi}{3}b = b
$$
$$
sin\frac{\pi}{3}a + cos\frac{\pi}{3}b = a
$$
I treated the rotation matrix as a transformation of (a,b) to (b,a)
EDIT 2:
Seeing as there are infinite solutions to this problem, does that indicate that it is the span of vectors that follow the above relationship that satisfy the conditions?
Comment: You have not reflected the exam question adequately.  It could have been phrased: find all points that will move the same under an anticlockwise rotation of $\pi/2$ around the origin moves them to the same place as a reflection in the diagonal line given by $a=b$.
Comment: Is that still a vector span also?
Comment: I'm not entirely sure how you interpret that.  The solutions vectors (a,b) to the equation form a subspace that is spanned by, in this case, one vector.  The answers below also imply this.
Answer: The variables does not ''cancel'', but we have: $a=(2+\sqrt{3})b \qquad \forall b \in \mathbb{R} $.
Do you understand what does this means?
Comment: Oh, does it mean that any vectors that follow this relationship fit the above conditions?
Comment: Yes: any vector of the form $[(2+\sqrt{3})b,b]$ is a solution.
Answer: For any $b$, $a$ is $$a = (\sqrt{3}+2) b$$
Another way to look at it, would be if the magnitude $s = \sqrt{a^2+b^2}$ is to be preserved then $$\begin{aligned}
a & = s \frac{\sqrt{3}+1}{2^{3/2}} \\
b & = s \frac{\sqrt{3}-1}{2^{3/2}} \end{aligned} $$


localhost:8080/hello-world returns 404 - enonic xp

Question: I have created enonic project hello-world site. the content studio shows site URL as /hello-world
But when browser calls localhost:8080/hello-world it returns 404 error log from enonic server.
How to fix this issue?
Answer: You have to configure your XP_HOME/config/com.enonic.xp.web.vhost.cfg file with something like this:
enabled = true

mapping.a.host = localhost
mapping.a.source = /hello-world
mapping.a.target = /site/default/master/hello-world
mapping.a.idProvider.system = default

You can read more about it in the official XP-documentation about vhost.


Como abrir a Calculadora usando intent?

Question: Gostaria de saber como faço para chamar uma aplicação Nativa na minha aplicação.
Gostaria de colocar um menu de calculadora, quando o usuário clicasse, abrisse a calculadora do android.
Obrigado.
Comment: Ainda não consegui. Vou abrir outro tópico para explicar melhor. Posso ? Pois queria colocar partes do meu código aqui para entenderem melhor. E pela resposta aqui tem limite de caracteres.
Comment: O foco desta pergunta é como abrir a calculadora, se nenhuma das resposta o atende deve comentar em cada uma delas o porquê. Só deve criar outra pergunta se o foco for outro. Em todo o caso pode sempre [editar](http://pt.stackoverflow.com/posts/131269/edit) a pergunta e acrescentar mais informações.
Answer: Deve utilizar um Intent juntamente com o método startActivity();
Pelo que se pode ler na documentação, para lançar a calculadora o Intent deve indicar a categoria CATEGORY_APP_CALCULATOR:
Intent intent = new Intent();
intent.makeMainSelectorActivity (Intent.ACTION_MAIN,
            Intent.CATEGORY_APP_CALCULATOR);
startActivity(intent);

Testei o código mas não funciona.
Encontrei este aqui que testei e funciona(pelo menos no emulador).
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName("com.android.calculator2",
                                      "com.android.calculator2.Calculator"));
startActivity(intent);

Answer: Viva,
 o seguinte código garante que a tua app abre a calculadora em qualquer dispositivo.
ArrayList<HashMap<String,Object>> items =new ArrayList<HashMap<String,Object>>();
final PackageManager pm = getPackageManager();
List<PackageInfo> packs = pm.getInstalledPackages(0);
for (PackageInfo pi : packs) {
if( pi.packageName.toString().toLowerCase().contains("calcul")){
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("appName", pi.applicationInfo.loadLabel(pm));
    map.put("packageName", pi.packageName);
    items.add(map);
 }
}

//Podes agora abrir a calculadora executando:
if(items.size()>=1){
String packageName = (String) items.get(0).get("packageName");
Intent i = pm.getLaunchIntentForPackage(packageName);
if (i != null)
  startActivity(i);
}
else{
      // Application not found
}

Esta info foi encontrada aqui -> https://stackoverflow.com/questions/13662506/how-to-call-android-calculator-on-my-app-for-all-phones
Dá uma olhada à documentação Android no link abaixo, para saberes como abrir outras apps nativas.
https://developer.android.com/guide/components/intents-common.html

Como abrir a Calculadora usando intent?


Apache uses more memory than PHP's memory_limit

Question: I am having some issues on a server where multiple Apache processes are being spawned and eating up the physical memory and swap.
Each httpd process consumes around 130MB of RES. However, PHP's memory_limit is set at 32MB.
The initial thinking is that there is a memory leak in PHP code - however, I don't see any particular code that could be causing this... granted the codebase is not necessarily efficient, however, what other explanations are there for such large memory consumption by Apache given memory_limit is set quite low?
Comment: Because apache does other things then just running php?  What other modules do you have running?
Answer: memory_limit is the maximum memory that apache is allowed to allocate per script. If you have multiple scripts running, on the same instance, it's normal that httpd uses more than 32MB.
Comment: +1 you need to tune Apache's settings: MaxClients, KeepAlive, etc. Search the web for "Apache performance tuning".


Copy table and append to larger archive table - google sheets script

Question: I have a set of data on a sheet from cell C11 to column J with a dynamic number of rows.
What I am trying to do is simply copy that table of data to the first empty row on a different master sheet which begins A1:H at ever increasing length as these smaller tables get added to it.
Ideally I would like this set up as a script to slightly automate the process for other users.
The problem that I have is that where I have a formula in my small table to add a variable date to the values when they are first copied and pasted there "=if(D11>0,$D$7,""). Unfortunately this inclusion of formula causes a disruption to my main task by being included when being copied even though remaining blank and then causing gaps and run errors with the code I found somewhere online.

      function getDynamicRows(){
     var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Data Entry');
  var sourceRange = sheet.getRange('C11:J');
  var data = sourceRange.getValues(); // Array of arrays [[Row1],[Row1],[Row3]]

  // add data to next empty row in the static sheet.
  var targetSheet = ss.getSheetByName('2020 Data');
  data.forEach(function(row){
    targetSheet.appendRow(row)
  })}

Any help I can get with this would be very much appreciated.
Answer: Use getDisplayValues() instead of getValues()
Using getDisplayValues() will make sure that you will copy the values the way you see them in the source sheet without any interference with formulas
Sample:
      function getDynamicRows(){
     var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Data Entry');
  var sourceRange = sheet.getRange('C11:J');
  var data = sourceRange.getDisplayValues(); // Array of arrays [[Row1],[Row1],[Row3]]

  // add data to next empty row in the static sheet.
  var targetSheet = ss.getSheetByName('2020 Data');
  data.forEach(function(row){
    targetSheet.appendRow(row)
  })}


how can I change props of component that pass from higher component . reactjs

Question: this is my upper component.
const Add_singlepage = () => {
    const [feed,setFeed] = useState(null);//getFeddd.php
    const [show,setShow] = useState({sh_categorytitle:true,sh_category:false});

    return (

          <Nav1 />

          {
             show ?
              <CategoryTitle show={show} getFeed={feed} /> //consider this - I pass show data
              :
              <Category />
          }

   );
 };

I pass some data as props in categoryTitle and I want control and change it in them.
this is my CategoryTitle
import React from 'react';

const CategoryTitle = (props) => {
const {show} = props;
const next1 = ()=>{
    setShow({...show,sh_category:true,sh_categorytitle:false});
}
return (

          ali
          <button onClick={next1} >reza</button>

    );
};

export default CategoryTitle;

I know there is a wy like context - but I dont want do that.
Answer: pass setShow too, as props, and this is what we call it callback works,
<CategoryTitle show={show} setShow={setShow} getFeed={feed} />

this is how call it in child,
const CategoryTitle = (props) => {
    const {show, setShow} = props;
    const next1 = () => {
        setShow({...show,sh_category:true,sh_categorytitle:false});
    }
}

Comment: It's work tnk-y
Answer: You could add a props named onChangeShow in CategoryTitle and do
const next1 = ()=>{
    props.onChangeShow();;
}

Then, in Add_singlepage you create a callback handleOnChangeShow (would be setShow here) and you pass it as props to CategoryTitle.


url dinâmica no ajax

Question: Como eu faço para o Ajax pegar a URL atual? Pois nela estão os valores que vão para o php. Se eu fizer assim funciona
  jQuery.ajax({
    url: "http://localhost/jogoteocratico/consulta.php?dificuldade=1&rodada=1",
    type: "GET",
    dataType: 'json',
    success: function(returnjson) {
    var i=0;
     $('#proxima').click(function exibir(){
       i++;
       document.getElementById("id_pergunta").innerHTML = returnjson[i].id_pergunta;
       document.getElementById("pergunta_jogo").innerHTML = returnjson[i].pergunta;
       document.getElementById("desafio_jogo").innerHTML = returnjson[i].desafio;
       document.getElementById("resposta_jogo").innerHTML = returnjson[i].resposta;

     });

Mas se eu fizer assim, não funciona:
$(document).ready(function mostrarPergunta(){
  var url = window.location.href;
  jQuery.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        success: function(returnjson) {
        //  for(i=0; i<returnjson.length; i++){
          //  alert(returnjson[i].pergunta);
         //}
        var i=0;
         $('#proxima').click(function exibir(){
           i++;
           document.getElementById("id_pergunta").innerHTML = returnjson[i].id_pergunta;
           document.getElementById("pergunta_jogo").innerHTML = returnjson[i].pergunta;
           document.getElementById("desafio_jogo").innerHTML = returnjson[i].desafio;
           document.getElementById("resposta_jogo").innerHTML = returnjson[i].resposta;

         });

Comment: Qual é a diferença entre os dois exemplos? Para usares a query string atual podes fazer `url: "/jogoteocratico/consulta.php" + location.search,`
Comment: @sergio, assim funcionou, muito obrigado.
Answer: Podes usar o location.search para ir buscar a querystring do URL (), e depois usar caminhos relativos, sem.
Ficaria assim:
jQuery.ajax({
    url: "/jogoteocratico/consulta.php" + location.search,
    type: "GET",
    dataType: 'json',
    success: function(returnjson) {

Comment: Editei a pergunta colocando o código que não funcionava, mas fica aqui o adendo de que a sua resposta funcionou. ;)
Answer: var url = window.location.href;

jQuery.ajax({

  url: url,
  //outras coisas vão aqui

});

A chamada para  window.location.href irá pegar a url atual da página. Passe isso para a chamada do método ajax e você terá uma "referência dinâmica" para a url atual da página;
Comment: Eu fiz assim, dei um alert na url, ta pegando certinho, mas me retorna erro interno do servidor,
Comment: @TiagoSilveira Agora isso não é culpa da requisição feita por Ajax. Isso é algo no teu código no back-end. Agora você precisa debugar teu código pra ver o que há de errado nele.

url dinâmica no ajax


Azure Data Flow generic curation framework

Question: I wanted to create a data curation framework using Data Flow that uses generic data flow pipelines.
I have multiple data feeds (raw tables) to validate (between 10-100) and write to sink as curated tables:

For each raw data feed, need to validate the expected schema (based on a parameterized file name)

For each raw data feed, need to provide the Data Flow Script with validation logic (some columns should not be null, some columns should have specifici data types and value ranges, etc.)

Using Python SDK, create Data Factory and mapping data flows pipelines using the Data Flow Script prepared with the parameters provided (for schema validation)

Trigger the python code that creates the pipelines for each feed, does validation, write the issues into Log Analytics workspace and tear off the resources at specific schedules.

Has anyone done something like this? What is the best approach for the above please?
My overall goal is to reduce the time to validate/curate the data feeds, thus I wanted to prepare the validation logic quickly for each feed and create python classes or Powershell scripts scheduled to run them on generic data pipelines at specific times of the day.
many thanks
CK
Answer: To validate the schema, you can have a reference dataset which will be having the same schema (first row) as of your main dataset. Then you need to use "Get Metadata" activity for each dataset and get the structure of each dataset. Your Get Metadata activity will look like this:

You can then use "If Condition" activity to matches the structure of both datasets using equal Logical Function. Your equal expression will look something like this:

If both datasets' structure matches, your next required activity(like copy the dataset to another container) will be performed.
Your complete pipeline will look like this:

The script which you want to run on your inserted dataset could be performed using "Custom" activity.  You again need to create the linked service and it's corresponding dataset for your script which you will run to validate the raw data. Please refer: https://learn.microsoft.com/en-us/azure/batch/tutorial-run-python-batch-azure-data-factory
To schedule the pipeline as per your specific pipeline will be take care by Triggers in Azure Data Factory. A schedule trigger will take care of your requirement of auto trigger your pipeline at any specific time.


Pivot an unknown field value

Question: I'm running Oracle 11.
I have a table of customers references shorto04 with documents to be printed. There are many type of documents and I don't know them all in advance.
Here is an example of data:

shorto04
wdocname

7739096
SL00A

7739096
TR00A

7740767
AV00BITA

7768159
SL00AFRA

7768159
TR00AFRA

7768159
AD00AFRA

7768159
PL00AFRA

7771629
SL00A

7780966
TR00A

7780966
AD00A

7812187
SL00A

7812187
TR00A

7812187
AD00A

7817697
SL00AGBR

7817697
TR00AGBR

7817697
AV00BGBR

7818401
SL00AGBR

7818401
TR00AGBR

7818412
SL00AGBR

7818412
TR00AGBR

7829375
SL00AGBR

7829375
TR00AGBR

7829375
PL00AGBR

7832296
SL00A

7832296
TR00A

7832296
AD00A

7832297
SL00A

7832297
TR00A

7832297
AD00A

7840205
OD00IGBR

7840205
SL00DGBR

7840205
AV00DGBR

Boss asked to count all different types and how many we have.
So I started with a query like the belolw:
Select *
from
(
select shorto04, SUBSTR(wdocname, 1,5) as docs
 from O04T91
)
pivot
(
count(docs)
for docs in ( 'TR00A' , 'OD00A')
)

of course my sql result is far from what I need:

ShortO04
tr00a_
od00a_

7709902
1,000000
0,000000

7725337
1,000000
0,000000

7729012
1,000000
0,000000

7729062
1,000000
0,000000

7739096
1,000000
0,000000

7740767
1,000000
1,000000

7768159
1,000000
0,000000

7771629
1,000000
0,000000

with my method I'd need to hardcode in the query all possible document types and if there will be any new ones they will not be counted.
here is an example of a partial expected result:

ShortO04
tr00a
od00a
ad00a
av00b
sl00a
od00i
av00d
etc
etc
etc
etc

7709902
1
0
1
0
1
0
0

7725337
1
0
1
0
1
0
0

7729012
1
0
0
1
1
0
0

7729062
1
0
0
1
1
0
0

7739096
1
0
1
0
1
0
0

7740767
1
1
0
1
0
0
0

7768159
1
0
1
0
1
0
0

7771629
1
0
1
0
1
0
0

7780966
1
0
1
0
1
0
0

7812187
1
0
1
0
1
0
0

7817697
1
0
0
1
1
0
0

7818401
1
0
0
0
1
0
0

7818412
1
0
0
0
1
0
0

7829375
1
0
0
0
1
0
0

7832296
1
0
1
0
1
0
0

7832297
1
0
1
0
1
0
0

7840205
0
0
0
0
0
1
1

7840228
1
1
1
0
1
0
0

Any help would be greatly appreciated.
thanks
Comment: You would have to use dynamic SQL, or pivot in an external reporting tool; but would that output really be useful? Does the requirement to "count all different types and how many we have" actually mean "for each shorto04", or do you only really want the total across all customers?
Comment: OK, but if you had that pivot result you wouldn't be able to do anything further with it, without more dynamic SQL, as an outer query would also need to know the column names. I think you might need to rethink your approach...
Comment: this is just the core of the query, I'm adding the customer name etc as they request different documents fo the same type (i.e. 3 label types when just 1 is needed and allowed by our policy... and so on). This will end up in an action to our customers. Take shorto04=7740767 as example, "tr" and "od" are two labels, system prints both and worker staple just one and throw the other.
Answer: You can select distinct values via
select distinct wdocname
from shorto04;

And generate your query like this:
SELECT
    'SELECT Shorto04, ' ||
    LISTAGG(
      '(SELECT COUNT(*) FROM ORDREF tmp  WHERE tmp.shorto04 = ORDREF.shorto04 and wdocname = ''' ||
      wdocname ||
      ''') AS ' ||
      wdocname ||
      ' FROM ORDREF GROUP BY Shorto04;'
    , ',') WITHIN GROUP(ORDER BY wdocname) AS query
FROM (
    SELECT DISTINCT wdocname
    FROM ORDREF
) t;

SELECT Shorto04,
       (SELECT COUNT(*) FROM ORDREF tmp WHERE tmp.shorto04 = ORDREF.shorto04 and wdocname = 'OD00A') AS OD00A,
       (SELECT COUNT(*) FROM ORDREF tmp WHERE tmp.shorto04 = ORDREF.shorto04 and wdocname = 'TR00A') AS TR00A
FROM ORDREF
GROUP BY Shorto04;

Basically, you add the main column, then the subselects in a comma-separated manner having the distinct wdocname as the input. The query was untested. If you create a SQL Fiddle with sample data, I'm happy to test it more practically.
EDIT
Since a SQL Fiddle was provided, I was able to test the query in practice and I have adjusted the query to work in practice. Already updated it above.
Fiddle link: http://www.sqlfiddle.com/#!4/cd7e3/1
The first query, the one shared in this answer generates the query to be actually executed as a text. Oracle is capable to execute a text as query, see: Can an oracle SQL query execute a string query selected from a table?
Comment: here is my first try with SQL Fiddle http://www.sqlfiddle.com/#!9/72d450/1
Comment: This looks like untested code. If you had tested it you would have found that there are syntax errors from missing commas, too many commas in other places and then when you fix those you would have found that `CONCAT` only takes 2 arguments.
Comment: @MT0 it is indeed untested code, as I clarified in the answer because there was no input to work on. Since Emare has sent a Fiddle, I plan to look into it and adjust the code.
Comment: @emare thanks for the fiddle. Fixed the code accordingly, please take a look both here in the answer and the link I have given.
Comment: @MT0 edited my answer so now the code is correct, given the fact that we have a proper input now.
Comment: @LajosArpad thanks for your effort, actually I was looking a way not to enter all possible `wdocname` values in the `(SELECT COUNT(*) FROM ORDREF.......`. I have to figure out how `xmlserialize` works and put it in my query. So far I did not succeeded :(
Comment: @emare is `xmlserialize` a field?

Pivot an unknown field value


Turning a geometric vector bundle into a free $\mathscr{O}_X$-module

Question: Given a geometric vector bundle $V\to X$ on a scheme $X$, consider the sheaf of sections $\mathscr{I}(V/X)$ defined by $U\mapsto \operatorname{Hom}_U(U,V_{|U})$. The goal is to equip the sheaf of abelian groups $\mathscr{I}(V/X)$ an $\mathscr{O}_X$-module structure.
The idea is clear, take a trivializing affine cover $\{U_i = \operatorname{Spec} R_i\}$ of $X$. Over each $U_i$, we have
$$
\mathscr{I}(V/X)(U) = \operatorname{Hom}_{U_i}(U_i,V_{|U_i}) \cong \operatorname{Hom}_{U_i}(U_i, \mathbb{A}_{U_i}^n) = \mathscr{O}_{X|U_i}^n
$$
which has an obvious $\mathscr{O}_{X|U_i}$-module structure.

How do we glue the $\mathscr{O}_{X|U_i}$-module structures to an $\mathscr{O}_X$-module structure on $\mathscr{I}(V/X)$?

The problem is over the intersections $U_{ij} = U_i\cap U_j$, the two trivializing isomorphisms coming from $U_i$ and from $U_j$ give two distinct but isomorphic $\mathscr{O}_{X|U_{ij}}$-module structures on the same abelian group $\mathscr{I}(V/X)(U_{ij})$. But intuitively I can only fix one of them.
Comment: The trivialisations satisfy a certain coherence condition, which implies that you get sheaves that can be glued together.
Comment: @ZhenLin The coherence condition exactly says that the module structures on the intersections are isomorphic. I have a sheaf of abelian group already, I don't want to glue any sheaf but "glue an action".
Comment: A small modification of the proof of that theorem tells you that you can glue the actions as well.
Comment: @ZhenLin Yes, but on a different sheaf right? And then transfer the action from the isomorphism of sheaf of abelian groups?
Answer: Your vector bundle comes with a map $\mathbb{A}^1\times V\to V$ over $X$, that corresponds to scaling on fibers. You can use this scaling to define the action of $\mathcal{O}_X$ on sections of $V$.
Define a map of sheaves $\alpha\colon\mathcal{O}_X\times \mathcal{J}\to \mathcal{J}$ as follows: given sections $f\in \mathcal{O}_X(U)$ and $\phi\in \mathcal{J}(U)$, look at $f$ as a morphism $U\to \mathbb{A}^1$ and at $\phi$ as a morphism $U\to V|_U$. Set $\alpha(f,\phi)$ to be the section of $V|_U\to U$ determined by $U\stackrel{f\times\phi}{\longrightarrow} \mathbb{A}^1\times V|_U\to V_U$.
You can check that this defines a structure of $\mathcal{O}_X$-module on $\mathcal{J}$, and that this coincides with the ones you find using trivializations.


Apply @JsonProperty on either Setter OR Getter, not both

Question: I have this class:
public class Foo {
    private int bar;
    public int getBar() {
        return this.bar;
    }
    @JsonProperty("baaaaar")
    public setBar(int bar) {
        this.bar = bar;
    }
}

Now if I serialize this, I would get the following result: {"baaaaar": 0} which seems odd to me as I only applied @JsonProperty to the Setter. I thought the Getter would keep its default behavior, that is to use the property name, and "baaaaar" would only be used for deserialisation.
Is there a solution to this, or do I have to explicitly add @JsonProperty("bar") to the Getter as well?
Answer: By default a single @JsonProperty on getter OR setter does set the property for both. This does allow you to rename a property for your whole application
As mentionned on this answer you need to set both @JsonProperty if you want them to have different values like
public class Foo {
    private int bar;

    @JsonProperty("bar") // Serialization
    public int getBar() {
        return this.bar;
    }

    @JsonProperty("baaaaar") // Deserialization
    public setBar(int bar) {
        this.bar = bar;
    }
}

EDIT 1 :
You might use @JsonProperty(access = WRITE_ONLY) following the documentation and the access properties.
Comment: Thanks for your answer, indeed that's what I found out after some research, but I thought there could potentially be another way, something like, but not exactly, JsonProperty "access" parameter.
Comment: There might be, I just checked the doc.
Check my Edit.
Comment: @AlaAbid you might use `WRITE_ONLY` for deserialization or `READ_ONLY` for serialization.
Comment: Unfortunately it doesn't work somehow. When field itself is no longer visible in the response.
Comment: @saran3h you need to explicitly allow null values in your serializer.
Check this [answer](https://stackoverflow.com/a/6507965/11825162)


Different fields for proxy_set_header in nginx configuration

Question: I am very new to nginx configuration. I want to use it set virtual hosts so that I can run different Node JS apps on different ports on the same server, but have them served at different subdomains. After some searching I found a post on stackoverflow and it works well for what I want to do. Amongst other things, the code involved the following location block
location / {                                                              │
    proxy_set_header X-Real-IP $remote_addr;                              │
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;          │
    proxy_set_header Host $http_host;                                     │
    proxy_set_header X-NginX-Proxy true;                                  │
                                                                          │
    proxy_pass http://otherapp/;                                          │
    proxy_redirect off;                                                   │
}

Now I wanted to understand what the script does. I looked at nginx docs and notes posted by various people, and understood a few things. It appears to me that what I want will probably work even if I remove all the proxy_set_header lines in the above code EXCEPT proxy_pass. I want to learn what the different fields in the above code are doing. Probably they are useful for some things that I don't realize at the moment. Is there a place which lists all the fields for proxy_set_header module and explains them?
Thank you.
Answer: Essentially, what it's doing is providing information to the server that it's proxying to.  In order:

X-Real-IP - the server you're proxying to is going to see the nginx proxy system as the "client IP" in any sort of application logic or logging that it's doing, since the nginx service is the source of the TCP connection.  This is usually pretty worthless, especially in logs.  The backend server can use this header instead of its normal client IP for logging or other uses where it needs the client's IP.
X-Forwarded-For - this is a standard-ish header, which is similar to X-Real-IP, but provides added connection source entries for the entire chain of proxies the connection's passed through.  Can be a bit more of a headache to parse and work with from the backend server since there's possibly multiple entries.
Host - This is the one most likely to matter for your application.  Normally, the request that nginx makes to the backend server will contain in its Host header the address that you've configured (in this case http://otherapp/).  This is probably not desired if proxying to something doing name-based virtual hosting, or something that generates links based on the received host header.  This config is making it so that the Host header that the client sent nginx is sent on to the backend (equivalent to Apache's ProxyPreserveHost).
X-NginX-Proxy - All this is doing is acting as a marker that the proxy is used.  Probably not useful in most cases.
Comment: Thank you. Is there a site that has information about any other `fields`? The documentation on nginx site does not have that information.
Comment: @user191017 Any HTTP header (including ones you make up that you application handles) is fair game - see [here](http://en.wikipedia.org/wiki/List_of_HTTP_header_fields).
Comment: @user191017 Nginx website doesn't have information about english alphabet too. What are you asking is actually HTTP-protocol essentials. See: http://tools.ietf.org/html/rfc2616
Comment: After hunting around, this is the first description I've been able to find for "X-NginX-Proxy" - it seems many people use it but no-one explains it? Is there official docs somewhere?


Determine if SocketException from UdpClient.Receive was caused by a timeout

Question: I have a UdpClient receiving data with a timeout set, e.g.:
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 12345));
client.Client.ReceiveTimeout = 5000;     // 5 second timeout

while (!shutdown) {
    IPEndPoint source = null;
    byte[] data = client.Receive(ref source);
}

Receive is documented as throwing a SocketException if "an error occurred when accessing the socket". The behavior of setting ReceiveTimeout is also documented as throwing a SocketException if the synchronous operation times out.
If I get a SocketException from Receive when a timeout is set, how can I determine if the exception was caused by a timeout rather than a more serious error?
I did confirm that the exception thrown on timeout is an actual SocketException and not some specific subclass of it. The only thing I can really think of is checking the exception message, which is a hack that I'm not really excited about.
Answer: You need to examine SocketException.ErrorCode property for value 10060 (WSATIMEDOUT).
The complete list of ErrorCode values you can find here: https://learn.microsoft.com/windows/win32/winsock/windows-sockets-error-codes-2


Intersection of Countably Infinite Sequence of Sets

Question: Suppose $\{\Omega_k\}_{k=1}^{\infty}$ is a sequence of sets, where $\Omega_k$ is countably infinite and $\Omega_{k+1}\subset\Omega_k$ for all $k$. Is it possible to show that $\cap _{k=1}^{\infty} \Omega_k$ is countably infinite?
Comment: Ωk = { k+1,k+2,......}, so each Ωk contains all the integers after k+1 and so is countably infinite. However  ∩ Ωk = { }
Answer: No; in fact it is not even possible to show it is nonempty in general! For an example, consider $\Omega_k=(0,1/k) \cap \mathbb{Q}$.
By the way, this is a special case of an important fact from measure theory: the measure of a descending countable intersection is equal to the limit of the measures of the sets if one of the sets has finite measure. Otherwise it might be smaller than this limit. Your case is the situation with the counting measure; a similar situation occurs with $\Omega_k = [k,\infty)$ under the Lebesgue measure.
Comment: This was exactly the example I wanted. Beat me to it. +1


Notification icon on API Level 26

Question: I don't understand which icon android api 26 use for push notification when app is close. When I receive push notification it's always default icon with droid.
I remove all default icon from ressources, set android:roundIcon="@drawable/ic_launcher" (ic_launcher is a png)
Edit :
My issue is when this is the system tray display the notification https://firebase.google.com/docs/cloud-messaging/android/receive
Comment: change your notification after using it once.. cause sometimes the old notification id persists if you change any attribute change the id..
Answer: The icon which you have set in notification object is display
notification.setSmallIcon(R.drawable.icon);

For Example
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    resultIntent.putExtras(bundle);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            resultIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    Notification notification;
    Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound);
 notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.lg_logo)
                .setContentTitle(title)
                .setStyle(new Notification.BigTextStyle().bigText(msg))
                .setAutoCancel(true)
                .setContentText(msg)
                .setContentIntent(contentIntent)
                .setSound(sound)
                .build();
    notificationManager.notify(0, notification);

Comment: the issue is when it is the system tray that display the notification
Answer: user notification.setSmallIcon(R.drawable.icon); to set the small icon also when using an image don't make it larger than 250px X 250px.
Comment: the issue is when it is the system tray that display the notification
Answer: Put below code in You Manifest.xml
           <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_notification" />
           <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

Also, Make sure icon you have generated is as per the guidelines provided by Google.
Here is official guidelines
Comment: I have already did it, works well on android 7.1.2 but not on 8.0

Notification icon on API Level 26


How to correct traits for body-size across multiple species?

Question: Accounting for body-size in morphological data sets can be solved by using the residuals of simple linear regression with the trait~body-size.
But I've been getting some annoying results using this method, and was wondering whether another method would give more realistic results.
Let's start with two species that look different, one is larger and has short femurs, while the other is small with long femurs:
svl=c(24,26,14,26,27,19, 42,46,45,37,59,48),
femur=c(12,14,8,13,14,9,  14,15,16,12,19,17),
sp=c("a","a","a","a","a","a","b","b","b","b","b","b")
Below shows original data, then the corrected by linear regression and division by body-size.

My point here: Because of the range in size, the regression correction has predicted that the corrected femur length is not different between species. And yet when I created the data I specifically made sp A femur 1/2 of body size and sp B 1/3 of body size.
So: should I just stick to dividing by body-size to correct other morphological traits? Or is there a better modelling solution?
Thanks,
Alex
Comment: " Because of the range in size, the regression correction has predicted that the corrected femur length is not different between species." - no, it hasn't. It might not be stat. sig., but the sample size is very small.
Comment: I am not sure that I understand fully your problem. If your model is femur length = alpha + beta x body size + epsilon, and you want to test if beta differs from a species to another, you should really test that. Here not compare (by eyeballing) the regression residual without including a 'species' term, it hardly makes sense.
Comment: Try for example to fit a model like femur length = alpha + beta x body size + gamma × species x body size + epsilon, where species = 0, 1, and test if  gamma is 0.
Comment: Hi Elvis, thanks for the response. I did fit the model you suggested, but the objective here was not to check if they are different-but to correct for body-size. But are you suggesting that I can use separate regression equations to correct different species' traits provided 'gamma' is not 0? What happens when you're dealing with 20 species? Thanks
Answer: The problem you describe comes from the following: you are anticipating relations of proportionality among your variables, while your regression models deal with them on a linear, additive scale.
The solution is to analyze your data on size in logarithmic scales. Then, for example, your ratio of femur length to body size becomes a simple difference in log-scaled values, readily amenable (unlike raw ratios) to standard regression approaches. Given that measurement errors tend to be proportional to the value that's being measured rather than independent of the value, logarithmic transformations make a lot of sense in this type of work.
This is the approach that has been used for over a century in the discipline of allometry, which deals specifically with issues of body scaling. Working in log scales allows discovery of unexpected relations that might not appear from use of ratios, such as Kleiber's law, the scaling of metabolic rate with the 3/4 power of animal mass among mammals over a range from mice to whales.
Comment: Thanks for your clear response. I agree that most morphological variables are not linear with body size and that error does increase at smaller scales. However, I don't think this is relevant to the example I posted, which is assuming a linear relationship, and would still get similar 'corrected' femur lengths for both species, despite their being a proportional difference-unless I'm missing something? In the end I want a  PC plot that separates species along trait axis such as femur length. Cheers
Comment: Then I think you should give us much more details to work on!
Comment: @AlexR you said "when I created the data I specifically made sp A femur 1/2 of body size and sp B 1/3 of body size." Yes, those are linear relations between femur length and body size, but the lengths in such a _proportional_ model cannot be 'corrected' properly by the _additive_ corrections of a linear model _in the original length scale_. You demonstrated that in the second of your three plots. Your last plot, where you plot the ratio of femur length to body size, gives the types of 'corrected' lengths you want. Linear regression in log scale of size gives you that analysis directly.
Answer: In regards to using non-linear models to represent an apparently linear relationship you must consider the relatively narrow range of values your data represents. Meaning that a small section of a long arc appears to be relatively 'straight' or linear.
I suggest taking a look at this paper by Albrecht et al. (1993) "Ratios as size adjustment in morphometrics."
An issue with your current methods is discussed by Albrecht and co-workers; that a ratio of femoral length/body-size may not actually remove the effect of body size. Allometrically adjusted ratios can provide a more complete removal of the size effect, which can be evaluated by observing if the correlation coefficient for the Yadjusted is approximately zero.
There are many other variations in allometry that you should consider looking into as well.


Breaking a char array into parts based on \n

Question: this is my first question on stack and I'm beginner in c.I declared a char array a[100]={"this is a test\n2nd test}.Now I'm trying to divide this array and take the two parts before and after \n as separate strings.So I declared a 2d array ab[i][k] and used a for loop to copy the characters to ab[i]. if a[j]=='\n' , I put a NULL character at the current position of ab[i][k] and increment i by 1.But for some reason, both ab[0] and ab[1] are displaying "this is a test" when I used printf to display them.Any help or suggestions would be appreciated.
int i=0;
char a[100],ab[100][100],c;
fputs(a,stdout);
printf("%d ",strlen(a));
for(j=0;j<=strlen(a);j++,k++)
{
    if(a[j]=='\n')
    {
        ab[i][k]='\0';
        k=0;
        i++;
        continue;
    }
    ab[i][k]=a[j];
}
printf("%s\n",ab[0]);
printf("%s",ab[1]);

Comment: You should post your existing code.
Comment: its included now :)
Answer: You need to set k=-1; when you find \n, since it will be incremented at the top of the loop to 0 when you continue;.
You also need to declare int j, k=0; before the loop, to get your code to compile.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[]) {
    int i=0;
    char ab[100][100];

    char a[100] = "this is a test\n2nd test";
    printf("%d \n",strlen(a));

    int j, k=0;
    for(j=0; j<=strlen(a); j++,k++) {
        if(a[j]=='\n') {
            ab[i][k]='\0';
            k=-1;
            i++;
            continue;
        }
        ab[i][k]=a[j];
    }

    printf("1: %s\n",ab[0]);
    printf("2: %s\n",ab[1]);

    return 0;
}

23
1: this is a test
2: 2nd test

Comment: @Ryu No problem. Welcome to StackOverflow. You can click the tick/check-mark next to the best answer to your question, marking it as a solution. When you get enough reputation, you can click the up-arrow to upvote answers, questions and comments.
Answer: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    char ar[100] = "this is a test\n2nd test\nfoobar\netc";
    char sep[10][100];

    int i=0;
    char* token = strtok(ar, "\r\n");
    while(token != NULL) {
        sprintf(sep[i], "%s", token);
        printf("string #%02i: `%s`.\n", i, sep[i]);
        token = strtok(NULL, "\r\n");
        i++;
    }

    return 0;
}

strtok() splits a string by any of the characters passed as a delimiter (new line and carriage return, in this case) into tokens. Passing a null pointer to the function continues where it last left off. It returns a pointer to the beginning of the token,
sprintf() saves formatted data into a variable handling \0 for you, but you could also use memcpy() or strcpy() if you like.
Comment: Which would mean that you cannot detect empty lines, in this case.
Comment: didnt even know about strtok....it worked perfectly! thanks! :)
Comment: `strtok()` will produce strange results if the original string happens to contain`"\n\n"`. (strtok() is beyond repair, basically)
Comment: @wildplasser, can you elaborate on "strange results"? As far as I can tell, zero-length tokens would be ignored. Is there anything else?


Two easy probability tasks

Question: I'm struggling with two exercises for which I do possess answers, but I have no idea why they would be like that. I haven't done any statistics in a long time (restarting studies).
Question 1
Two buddies agreed to come to a meeting between 1 pm and 2 pm. Each one will come at random time and will be waiting for 20 minutes before going back home. What's the chance for them to meet?
I have an answer written down as 5/9 (to be more specific, (3600-1600)/3600)
It seems to be done by contradiction, but I haven't yet come to a conclusion what kind.
Question 2
Over a section $AB$ which has a length of $l$, two points $M$ and $L$ were chosen randomly.
Find the probability of $L$ being closer to the $M$ than $A$.
So what I have is something like this:
$$
A-------L-------M-------B
$$
where $|AL| = x$ and $|AM| = y$.
I concluded that in order for $L$ to be closer to $M$ than $|AM|$ there must be such that $|y-x|< x$, that is $-x < y-x < x$,  so  $y>0$ and $y<2x$.
So my question is, how do I get the probability from this equation? (default answer is 3/4)
Answer: A quick and easy way to address both questions is to plot the events.  Because the distributions of all the variables involved--arrival times of the buddies and locations of the points--are all uniform, the area of the plot (relative to the total area that could be plotted) gives the answer.
1. The Buddies Meet
Let $X$ be the time the first buddy arrives and $Y$ the time the second one does.  The condition of their meeting, measured in hours, is
$$X \le Y \le X + 20/60\text{ or } Y \le X \le Y + 20/60.$$
The plot of these points can be seen to comprise three squares, of $20/60=1/3$ hour on a side, plus two sets of diagonal half-squares of the same size.  That's the equivalent of five such squares.  Each square has $(1/3)^2=1/9$ the area of the whole square covering all possible arrival times $(X,Y)$ between $1$ and $2$ pm, whence the answer is $5/9$.

2. A Point Proximity Problem
This time, in the $(L,M)$ plane, the event is
$$|L-M| \lt |L-A|.$$
Geometrically it comprises a rectangle of base $(B-A)/2$ and height $(B-A)$ adjoined to a diagonal half-rectangle of the same dimensions.  Clearly these fill $3/4$ of the area of the square $[A,B]\times [A,B]$.

Even in more complicated problems involving non-uniform univariate, bivariate, (or even trivariate) probabilities, drawing pictures of events is often very helpful for understanding how to set up and compute the integrals that must be evaluated.
Answer: Since the question is flagged as self-study, I'll just provide some hints to (hopefully) help you derive the solution. I'll amend/complete my answer based on your progress.
Question 1
As a starting point, you might want express the information provided in the problem with some mathematical notation. To do so, define two (continuous) random variables, say $X$ and $Y$, corresponding to the arrival times (in minutes after 1pm) of the two buddies. What are the conditions on $X$ and $Y$ for the two buddies to meet, i.e., what is the domain of values for $X$ and $Y$ where the two buddies meet?
To compute the requested probability, one needs to know the joint distribution of $X$ and $Y$. It is not explicitly provided in the question; I'll assume that $X$ and $Y$ are independant and uniformly distributed on $[0, 60]$.
You have (at least) two options here. The first approach is based on a geometric reasoning and works it only because the variables are independant and uniformly distributed. The requested probability is given by the ratio of the area of domain of $X$ and $Y$ where the two buddies meet and the total area of the domain of possible vaues for $X$ and $Y$.
In the second approach the requested probability is obtained by integrating the joint density on the domain of $X$ and $Y$ corresponding to situations where the two buddies meet.
Comment: Even if the X and Y are not uniformly distributed, you should still be able to use this approach (assuming you know their actual distributions). You'll just need to integrate over the domain instead of just computing the relative area (which is basically integrating a constant function anyway).
Comment: For those who struggle with the same kind of task, this link http://www.mathpages.com/home/kmath124/kmath124.htm provided me  a satisfying reasoning to solve this (and Quantibex suggestion to use geometry)
Comment: Ok, then would you consider to add your solution to the question so that others could benefit from it?
Answer: For question 2 here are some things to consider.
This all assumes that the points will be placed based on a uniform distribution (reasonable but unstated assumption).
Your drawing shows the order A L M B, but from the description it seems that you could also see A M L B, in the later case L will always be closer to M than to A, what is the probability of seeing A M L B and seeing A L M B?
Now conditioning on the order A L M B, think about having placed M (and A is already there) and we know that L will fall between A and M, what proportion of the line will have L closer to A? closer to M?
Combine the answers to the 2 questions and you should see $\frac34$.

Two easy probability tasks


Linear combination of power law distributions

Question: I am exploring whether a linear combination of power law distributions is also a power law distribution. Specifically, if $X \sim (\alpha -1) x_{\min}^{(\alpha -1)} x^{-\alpha}$ and $Y \sim (\beta -1) y_{\min}^{(\beta -1)}y^{-\beta}$, we are interested in finding the distribution of $Z = \rho X + (1-\rho) Y, \rho \in (0, 1)$? ($X$ and $Y$ are independent)
I tried with the moment generating function approach:
If $M_Z(t)$ is the moment generating function of $Z$, $$M_Z(t) = E[e^{tZ}]=E[e^{t(\rho X + (1-\rho)Y}]=E[e^{t\rho X}]\cdot E[e^{t(1-\rho)Y}] = M_X(t\rho) M_Y(t(1-\rho)).$$
This brings us to the moment generating functions of the power law distributions themselves:
$$M_X(s) = \int_{x_{\min}}^\infty e^{sx}(\alpha -1)x_{\min}^{(\alpha-1)} x^{-\alpha} \, dx = (\alpha - 1)x_{\min}^{(\alpha-1)}\int_{x_{\min}}^\infty e^{sx}x^{-\alpha} \, dx. $$
Like it is mentioned here, this resembles the incomplete gamma distribution, but I cannot complete the derivation. And, more importantly, I am not sure if this will help me answer the original question, i.e., is the linear combination of two power law distributions also a power distribution?
Comment: It depends on what you mean by *power law distribution*.  If you mean *Pareto distribution* then I would guess the answer would be no.  If you mean particular behaviour in the tail (on a log-log scale roughly linear on the right) then I would guess the answer might be yes.
Comment: Incidentally, power law distributions have heavy tails and some of their moments are infinite, as are their moment generating functions for all $t \gt 0$
Comment: @Henry In this case, I do mean the log-log linear behavior in the tail. And you are correct, the moments are defined only for $t<0$ above. However, I am not able to complete the proof using this or through a differentiation of the cumulative distribution function.
Answer: The moment generating function doesn't exist for many heavy tailed distributions. In general if you take suitably normalized linear combinations of power-law distributed random variables with infinite variances (ie with tail parameter $\alpha<2$, the generalized version of central limit theorem shows weak convergence to a stable distribution with the same tail parameter. If $\alpha\geq 2$ the linear combinations will tend to converge toward a Gaussian. Note that when $\alpha=2$ the variance may still be infinite but convergence to Gaussian is still possible. An example of a heavy tailed stable distribution is the Cauchy. All stable distributions except Gaussian have power law tails. John P. Nolan has some useful notes on his website.
Comment: Thank you for pointing towards the stable distributions...


problemas com troca de cores por meio do javascript

Question: Estou com um problema em javascript onde a cada período de tempo troca-se a cor de um elemento.
Segue o código abaixo:

Este é o HTML:

Comment: Qual o problema? Seja um pouco mais específico...
Answer: Você está redeclarando a variável cor dentro da função, e com isso perde acesso à variável do escopo externo. Faça assim (aproveitei pra remover uma repetição desnecessária):

var timer = setInterval(modCor, 5000);
var cor = 0;

function modCor (){
    var logoImg = document.getElementById('logo');
    if (cor==0){
        cor = 1;
        logoImg.style.border = "thick solid #00FF00";
    }else if (cor == 1){
        cor = 0;
        logoImg.style.border = "thick solid #FF0000";
    }
}
#logo {
  width: 300px;
  height: 200px;
  background: #ccc;
  transition: all 1s;
}

O efeito de transição fica por conta do CSS.
Comment: Obrigado mesmo resolveu boa parte do meu problema, preciso de uma melhoria, como coloco um tempo de transição nas  trocas de cor ?
Comment: @NelsonFrancisco No CSS dá para controlar as transições, atualizei meu exemplo.
Answer: Se eu entendi bem, você quer um loop de background, bom tem uma função em CSS3 que dá para fazer isso por você, mas você pode esta imaginando como isso pode me ajudar? Bom você pode fazer com JavaScript é adicionar e remover class, você vai precisar de 3 itens: HTM , CSS e JAVA SCRIP;
HTML

a

CSS3
/*Alpha é uma class de cor inicial*/
    .alpha{
        width: 500px;
        height: 500px;
        background: #09f;
    }
    /*Beta é a class que faz a animação*/
    /*Ela sera adicionada e removida o tempo todo*/
    .beta{
        /*Nome da animação*/
        animation-name: cor;
        /*Tempo da animação 4s = 4 segundo / 0.5s = 0,50 segundos*/
        animation-duration: 4s;
    }
    /*Chama animação caso tenha class*/
    @keyframes cor{
        0% {background: #09f;}
        50% {background: #f00;}
        100% {background: #09f;}

    }

SCRIPT
//Define o elemento como uma variavel Global
    var elemento = document.getElementById("alpha");

    //Função principal
    function funcao(){
        //Loop por 5s setInterval(function(){}, 5000);
        setInterval(function(){
            //Linha abaixo é bom para verificar no console, F12 do teclado
            console.log("time");

            //Remove a class Beta
            elemento.classList.remove("beta");
            //Da um tempo de 1s para adicionar a Class Beta novamente
            setTimeout(adicionar, 1000);

        }, 5000);
    }
    //Função que adiciona a class
    function adicionar(){
        elemento.classList.add("beta");
    }

    //Chama a função principal
    window.onload = funcao();

Vale lembrar que o  tem que ser o último conteúdo, porque se não ele tem chance de não encontrar a div no documento, dá para ter uma praticidade mair usando o jQuery api e algumas outras de controle de interface.
Boa sorte e bom estudos com seu desejo =D
Comment: Que interessante, nesse caso irei trocar por meio do JS a class da minha div, dessa forma alterando a formatação aplicada é isso ?
Comment: Existe um negocio no css chamado animation, você esta aplicando uma animação em uma div.


Windows server 2008 R2 High Memory Utilization

Question: We are running a VM with Windows server 2008 R2, we see the physical memory utilization to be close to 100% always. Machine is running crystal reports server.
Task manager counts to 99% memory Utilization, where a sum memory used by all the processes from tasklist accounts for only 1/4 of the total available memory. Not sure if their is a memory leak, if so how to find and patch it ?
I agree going by summing up the tasklist values is not the correct approach as it may not account for cached and so on, but I am guessing it can be the first place to start with.
Physical Memory (MB)
Total 32767
Cached 120
Available 117
Free 0
Kernel memory (MB)
Paged 381
Nonpaged 200
System
----
Commit (GB) 19/63
Comment: Do you have Microsoft SQL Server installed on the machine?
Comment: What's the VM platform?
Answer: This could be a symptom of agressive File System Caching.
Download RAMMap from Sysinternals to find out what is taking up all this memory
As described in the kb article, you need to look for large Available or Standby Memory claims in the "Metafile" usage category:


Null-homotopic covering map means the covering space is contractible

Question: I am working on problems in the past Qual exams.
"Let $f:\tilde X\to X$ be a covering map between path-connected and
  locally path-connected spaces. Suppose $p$ is homotopic to a
  constant map. Prove that $\tilde X$ is contractible."
I remember doing this before, but I forgot the final touch: we have a homotopy $H_t : \tilde X \to X$ s.t. $H_0(\tilde x)=f(\tilde x)$ and $H_1(\tilde x)=x_0$ constant. We observe that $\operatorname{id}_{\tilde X}$ is a lift of $H_0=f$, hence there is a unique lift $\tilde H_t : \tilde X \to \tilde X$ of the homotopy $H_t$ s.t. $\tilde H_0= \operatorname{id}_{\tilde X}$ and $f\circ \tilde H_1=H_1=x_0$.\
I'm stuck here. It suffices to prove $\tilde H_1$ is constant. But I don't have much information about $\tilde H_1$ except that $\tilde H_t$ is a unique lift of the whole $H_t$. How do I conclude?
I don't know how to use the hypothesis "path-connected and
  locally path-connected" here since in Hatcher's book, these hypotheses usually needed in the Galois corespondence, which I don't think is relevant here. Even the lift above is due to Proposition 1.30 which does not need these requirements.
Comment: You might check: https://math.stackexchange.com/questions/3099323/when-is-the-map-rho-langle-x-c-rangle-rightarrow-langle-k-c-rangle
Answer: To be honest, I am not entirely sure why $\tilde{X}$ path-connected and $X$ locally path connected are assumed here. It seems like $\tilde{X}$ being connected is sufficient.
As you said, it is sufficient to show that $\tilde{H}_1$ is constant. Now note that since $f \circ \tilde{H}_1 = x_0$ is constant, we have that the image of $\tilde{H}_1$ is contained in the fiber of $x_0$ under the map $f$. But since $f$ is a covering map, this fiber is discrete and since $\tilde{X}$ is connected, the map needs to map into one connected component i.e. $\tilde{H}_1$ is constant.
Comment: Yes, the problem is correct. I'm just saying that it is not necessary to assume that $\tilde{X}$ is path connected, but connected suffices.
Comment: $\tilde X$ connected is in fact sufficient. It is also necessary because contractible spaces are connected.
Comment: so if $\tilde X$ is connected, the problem is solved. It does not mean this problem is wrong, right?
Comment: oh right, i thought connected implies path-con, i clearly misremember this


Estimate a value knowing the values of: the function, the derivative and the second derivative in 0

Question: Please suppose you have an unknown function r(x).
This function r(x) is defined in the range: [-5; 5]
You know that:
r(0) = 1;
r'(0) = -1;
r"(0) = 1.
Please estimate the value of r(x) in the point 1/10 (= 0.1), explaining the method or the theorems you've used to estimate.
Thank you in advance for your kind help.
Please suppose that in a certain classroom, Taylor Series concept has not yet been explained, so you aren't authorized to use Taylor Series to solve this problem.
Comment: Please explain the methods or the theorems that you know and which you think might be used to attack this problem. Thank you in advance.
Answer: using the concept of taylor series
$$
P(x) = \frac{r(0)}{0!} + x\frac{r'(0)}{1!} + x^2\frac{r''(0)}{2!} + \ldots
$$
as you are requiring an approximation stop at degree $ x^2$
then
$$r(x) \approx  1 - x + \frac{x^2}{2!} $$
at $x =0.1$ $$ r(0.1) \approx \frac{181}{200} = 0.905$$
Comment: @UltraCommit If you only knew the value, you would use a constant function. If you only knew the value + 1st derivative, you'd use a linear function. So in this case, you can use a parabola. Guess the equation $ax^2+bx+c$, figure out what $a$, $b$ and $c$ should be to match the given values and if you do everything correctly, you'll get the same answer.
Comment: OK, and if you are not authorized to use the concept of Taylor Series?  Please suppose that in a certain classroom, Taylor Series concept has not yet been explained.
Answer: If you have no idea of Taylor series, you need to approximate your function $r$ by another one, with 3 parameters (since you have 3 informations). Without more informations, the most reasonable choice is to approximate it using a parabola $f(x) = ax^2 + bx + c$.
To determine the values of $a$,$b$ and $c$, set $f(0)= r(0), f'(0) = r'(0), f''(0) = r''(0)$. You get immediatly the values of the parameters: $c=1$, $b=-1$ and $a=0.5$.
From there, $r(0.1) \approx f(0.1) = 0.5 (0.1^2) - 0.1 + 1 = 0.905$.
Without surprise, this yields the same answer as the Taylor serie.
Comment: Thank you very much for your explanation of the second method!


EntityQuery group by clause

Question: Using the EntityQuery API I am trying to add a group by clause to the query, however, it doesn't seem that one exists.  The EntityQuery API does not have a groupBy() method.
Current Code:
<code>$nodes = Drupal::entityQuery('node')
    ->condition('type', 'thing')
    ->condition('field_num_1', 'value', '=')
    ->condition('field_num_2', 'value', '=')
    ->range(0, 10)
    ->sort('title', 'ASC')
    ->execute();
</code>
Ideal Code:
<code>$nodes = Drupal::entityQuery('node')
    ->condition('type', 'thing')
    ->condition('field_num_1', 'value', '=')
    ->condition('field_num_2', 'value', '=')
    ->groupBy('field_num_3')
    ->range(0, 10)
    ->sort('title', 'ASC')
    ->execute();
</code>
Answer: For aggregate queries, you need to use the separate method, from https://www.drupal.org/node/1918702:
<code>$query = Drupal::entityQueryAggregate('node');

$result = $query
  ->groupBy('type')
  ->aggregate('nid', 'COUNT')
  ->execute();
</code>
groupBY() alone doesn't do anything. The normal entity query returns entity ID's. Always. It makes no sense to group by a field or anything else. Only in combination with aggregate.
Comment: but how do you get the node ids contained on that one? i can see nid_count 2 but how do i know?
Comment: Actually...I take that back, I think its working.  Awesome!  Thank you!
Comment: Is it possible to sort the aggregate results by a field within an entity of one of the results.  So example:  Drupal::entityQueryAggregate('node')->groupBy('field_custom_name')->aggregate('nid', 'COUNT')->sortAggregate('field_custom_another_name', 'SUM', 'DESC')->execute();
Comment: The statement "groupBy() alone doesn't do anything" is incorrect, it returns the values of the grouped column. However, most of the time this is not the result you want so you need to use the aggregate function as well.
Comment: Any way to return the nid list grouping by nid with a order? I mean, something like:
`
      $entityIds = \Drupal::entityQueryAggregate('transaction')
        ->condition('order_date', $from->getTimestamp(), '>')
        ->groupBy('nid')
        ->get the highest node ordering by order_date
        ->execute();
`
I don't want to count or something, only I want to get all transactions nid with a condition and, if any nid are in two rows, get the highest (or really, whatever!).
Comment: @estoyausente that does not sound like a nn aggregate query to me, just a normal query with a sort and range(0, 1).
Comment: Yes, it was the solution that I found :) Thanks Berdir!

EntityQuery group by clause


Attach Sources - Maven Dependancies [NetBeans]

Question: I am running NetBean 7.4 on Mac and I am sort of new to Maven dependancies.
I have been given a project that uses Maven to download a framework for networking simulation.
Turned out that the framework has a bug and the teacher gave us a public GitHub repository with all the source code for the framework, so that we can also modify it.
How do I connect the GitHub link (with sources) to NetBeans in order to being able to modify the framework classes? The "Attach Sources..." button that appears on the framework classes asks for a JAR or ZIP (if I download the ZIP from GitHub it doesn't work).
Moreover, it looks like the framework files in the Dependancies folder cannot be modified anyway (read-only files).
Thank you all.
Answer: to "connect" 2 different projects, the checked out source's version needs to be equal to the version in maven pom.xml.
So clone the github repository, figure out which branch/tag matches the version in your project and check it out. Then open the project(s). If you did that correctly (and assuming the github project is actually maven), your project's dependencies section will list them with project-like icon. Then the projects are linked.


Benjamini-Hochberg: choosing the False Discovery Rate / q value

Question: Background: the Benjamini-Hochberg procedure is a method for correcting for multiple p-values. (If you set p<.05, and you do 20 tests, then one test is likely to be a false positive. The B-H procedure corrects for this.)
When using this procedure, not only do you set a p value (usually .05), you also set a q value - the False Discovery Rate (or FDR). This does not necessarily need to be .05.
This CrossValidated thread discusses the correctness of choosing the q value after viewing your data, but it does not answer my question.
My question: what is usually considered a reasonable q value? I've seen everything from .05 to .20 used in literature, but I have found no guidance on what are the highest values that may be considered "conservative" and what is considered a stretch.
Answer: FDRs are commonly much greater than p-values, and recall the lowest FDR value represents a list of features and not one feature, like a p-value does.   So if the lowest value of FDR is for example 0.15 for a list of 15 features(genes), then at the very least you have to publish the list and state that the FDR is 0.15.  If reviewers expect to see lower FDR's then there's not much of an alternative.   Only lower p-values can drive FDR lower.  If you can generate a list of 10-15 or 20-30 features whose FDR is 0.05, then you should have no problem publishing this in the peer-reviewed literature.   However, FDR values of 0.1, 0.15, and 0.2 and greater are frowned upon -- i.e. are not considered "good."  This does not mean however, that you can't publish a list of features when FDR is not 0.05 or is greater than 0.05 -- it's a matter of the personal-experience-based FDR threshold assumed by the reviewer, laboratory, or journal.
Comment: Thank you, that is helpful. is it common to publish with FDR somewhere between .05 and .1?
Comment: Yes, that should work!
Comment: I think we should avoid confusion in terminology. There is a cutoff value chosen a priori (we can define it as Q or q*), so that the FDR must not overcome it. Then, there is a single q-value for each comparison, and we need at least one of them to be below such cutoff. So, we have a list of q-values, not of FDR values.
Answer: In my experience, there is no such thing on what the "best" FDR is. The "best" FDR
depends on your desired statistical power and type I error. In genetics, FDR 0.05 is common, but this is not mandatory.
When you report your results, you should make FDR to 0.1 or 0.05 unless you have a good reason not to. Your report will be consistent to the literature because other people also use 0.1 or 0.05. If you set your FDR to something like 0.0456, your paper might be rejected for inconsistency.
Answer: I don't think you should set both a p-value and Q (the upper value of FDR). The p-values are calculated and, with the BH correction, statistical significance depends on both the set of p-values and such Q.
The link you report actually sets a Q of 0.25 (and defends such choice even in case of all p-values between 0.10 and 0.24): I've never seen a Q above that. The reason for discrepancies across fields, in my opinion, may be understood by reading the original paper: https://rss.onlinelibrary.wiley.com/doi/10.1111/j.2517-6161.1995.tb02031.x
The FDR is given by the number of false positives on the number of significant findings. However, a crucial point is that, in case of no significant findings, the FDR is set to 0. This makes the FDR equal to the p-value in the single-test case (when the null hypothesis is true). Of course, this is not interesting because it's the degenerate case. However, the point is that, when the number of tests is low, or there's the possibility that all null hypotheses are true, using an alpha above 0.05 would be suspect. For example, with only two tests, you would consider two p-values between 0.05 and 0.1 as evidence of a double effect, and you would consider a p-value of 0.05 in one test as significant regardless of the value of the other test: this would be even less conservative than ignoring the fact you're doing two tests.
If, instead, it is not realistic to assume that all null hypotheses are true, it may make sense to use a higher Q, since the possibility of no significant findings becomes less realistic. Moreover, the formula in the original paper shows that you just select an upper bound for FDR, but that actual FDR is below the product between the chosen Q and the proportion of null hypotheses that are true (
$E(Q) \leq \frac{m_o}{m}q* \leq q*$, in the paper's terminology).   This implies that, the higher the ratio of false null hypotheses, the lower the real FDR. This explains why, in situations where a plethora of tests are performed, like in genetics, one may choose higher Qs.
Consider however that use of a Q of 0.05 allows you to express q-values as BH-adjusted p-values, and that you'll be sure to have both 1) BH-adjusted p-values more conservative than unadjusted p-values and 2) BH-adjusted CIs for significant findings (see, for example, here: https://onlinelibrary.wiley.com/doi/10.1111/psyp.12616) with a higher coverage than 95% and not including the null.
Instead, with a Q above 0.05, you could find significance in comparisons with a p-value above 0.05 (and with a 95% unadjusted CI including the null). Moreover, referees might not accept a Q above 0.05, for analogy between FDR and type-I error.


checkboxes in forms, unable to fetch the value posted in drupal

Question: <code>$langoptions = array(1=>'German',2=>'English',3=>'Spanish',4=>'French',5=>'Portuguese',6=>'Chinese',7=>'Italian',8=>'Japanese');

       $form['language'] = array(
        '#type' => 'checkboxes',
        '#title' => 'Language',
        '#multiple'=> TRUE,
        '#options'=> $langoptions,
      );
</code>
Created a list of check box like this and in callback I tried to access it as
<code>foreach ($_POST['language'] as $key => $value) {
    echo $value;
}
</code>
and it does not display any value, can any one help me in fixing this?
Answer: If you're using standard form API, the postdata should be in $form_state['values'] at hook_submit().
Just to be sure -- have you checked any of the checkboxes prior to submitting?  They will only be sent in POST if checked.
Comment: What kind of callback exactly? The submit callback? See http://api.drupal.org/api/drupal/includes--form.inc/group/form_api/7 for how you should be doing form handling in Drupal. A Hint: You never use $_POST ;)
Comment: @Berdir: while submitting I load the result in ajax, so I did not use hook_submit(), instead I call another path and that path has a callback function where I access my form element, pls see my code here,  $form['submit'] = array ('#type' => 'image_button', '#val' =>t('Submit'),'#src' => 'sites/all/themes/ncomputing/images/success_search.jpg','#ahah' => array('path' => 'suc_stories/getresult','wrapper' => 'success_stories_result','method' => 'replace','effect' => 'fade',),); in /getresult under hook_menu $items['suc_stories/getresult'] = array('page callback' => 'suc_stories_result_callback',
Comment: Yes I have checked the form and when I use a trace tool (like smart sniff to see what is posted) it shows language[1]=1&language[5]=5 in the post but it also shows language= empty. Like language[1]=1&language[5]=5&language=&name=Jaya, this is not done with standard form api, I am using the form with drupal_get_form in my module for a search function which requires criteria selected from this checkboxes, in my callback function I tried to fetch value as $_POST['language']


The largest convex set in the interior of a non-convex set

Question: We can define the convex hull, which is the smallest convex set containing a set $A$. I believe this can be viewed, essentially, as approximating any set from the outside via convex sets. Is there an analogous notion for approximating the inside of a non-convex set? In the sense that we may find the 'largest' convex set contained within a non-convex set?
Comment: Unfortunately such a set may not be unique. Consider a dumbbell-shaped set; there are two choices for the largest convex set inside it, one for each side of the dumbbell.
Answer: There is a fundamental issue here.  The convex hull of a set $A$ is the intersection of all convex sets containing $A$.  This definition "works", or "makes sense", because the intersection of convex sets is itself convex.
So to ask a corresponding question "from the inside", you would be looking at the union of all convex sets contained in $A$.  Problem is, the union of convex sets is generally speaking not convex.
You could ask something like "what is the largest (in volume or area) convex set contained in $A$?" and it might be possible to answer this.  However it would be fundamentally different from the usual "convex hull" question, and you could not reasonably expect any meaningful connections between the two problems.
In particular, if you take $A$ to be, for example, an annulus, then it is intuitively clear that no convex set within $A$ is going to be a "good approximation" to $A$.
Answer: The set of all rational numbers does not contain any convex set except single points so there is no convex susbet that is 'close' to this set.


How to use p series to prove that this series converges

Question: So I know that the $p$ series converges if $p > 1$ in a series that looks like:
$$\sum_{n=1}^\infty\frac{1}{n^p}$$   That's the p series.
So I have a question about this series:
$$\sum_{n=4}^\infty \frac{n^{2.5} - 1}{n^{6.5} +4}$$
When I used cauchy condensation, I got that
$$2^n \cdot \sum_{n=4}^{\infty}\frac{2^{2.5n}-1}{2^{6.5n} + 4}$$
I was wondering how I could reduce this to a p- series now and prove that it converges.
Comment: Do you know the ration comparison test? That would be more appropriate than the condensation test.
Comment: You can also check the behavior of the summand at infinity.
Comment: p series should not start with n=0
Answer: by comparison test
$$\sum _{ n=4 }^{ \infty  } \frac { n^{ 2.5 }-1 }{ n^{ 6.5 }+4 } <\sum _{ n=4 }^{ \infty  } \frac { n^{ 2.5 }-1 }{ n^{ 6.5 } } <\sum _{ n=4 }^{ \infty  } \frac { 1 }{ n^{ 4 } } $$
Answer: More generally,
\begin{align}
\sum_{n=1}^\infty \frac{n^a +o(n^a)}{n^b +o(n^b)}
&=\sum_{n=1}^\infty \frac{n^a}{n^b}\frac{1+o(1)}{1+o(1)}\\
&=\sum_{n=1}^\infty  n^{a-b}(1+o(1))\\
\end{align}
converges if
$b > a+1$
and diverges if
$b \le a+1$.
This is the case
$a=2.5, b=6.5$,
so the sum converges.
Answer: Notice $$
\frac{n^{2.5} - 1}{n^{6.5} + 4}
\leq \frac{n^{2.5}}{n^{6.5} + 4} \leq \frac{n^{2.5}}{n^{6.5}} = \frac{1}{n^{4}}.
$$
The series $\displaystyle \sum_{n=4}^{\infty} \dfrac{1}{n^4}$ converges (because it is a $p$-series with $p = 4 > 1$).
Therefore the series $\displaystyle \sum_{n=4}^{\infty} \dfrac{n^{2.5}-1}{n^{6.5}+4}$ converges by the comparison test.
Comparison Test: If $0 \leq a_n \leq b_n$ for all $n \geq N$ (for some fixed value $N$), and if $\sum_{n} b_n$ converges, then $\sum_{n} a_n$ converges.
In your example, $a_n = \dfrac{1}{n^4}$ and $b_n = \dfrac{n^{2.5}-1}{n^{6.5}+4}$.


Bad format for number 'gold' in column 1

Question: I have just started using MySQL today, so please without hate.
This is the table how it looks in phpmyadmin: https://i.stack.imgur.com/e4bqL.png
Here is the method I'm using: https://i.stack.imgur.com/MCY7U.png
Here is the error I'm getting: "Bad format for number 'gold' in column 1.", it's pointing on this line: return st.getDouble(1);
Thanks for any help!
Comment: Could you add the actual query to the question as text? Image links to external resources may not be very useful for any later readers of the question.
Comment: just use... select gold... instead of select 'gold'
Comment: *gold* is no *Double*
Answer: You're doing
SELECT 'gold' FROM `Economy` WHERE...

That will select the string literal 'gold' from the database, not the value of the gold field.
If you want to quote a field name, you need to use backticks;
SELECT `gold` FROM `Economy` WHERE...

...although the query in this case will work just as well without quoting the field name at all.


Deleting arrays that are permutations of another one in Julia

Question: This looks like a fairly easy thing to solve but I've banged my head on this problem for a couple hours now without making progress. I'm hoping someone here could help me. I have an array that contains 2 elements arrays inside. Something like:
a=[[1,2],[3,4],[2,1],[4,3]]

I would like to be able to delete the permutations of arrays inside and keep only one of them. With the previous example, I would like to go from a to:
b=[[1,2],[3,4]]

Using double for loops seems to not work (at least with the ways I tried). I hope you can help me!
Using double for loops seems to not work (at least with the ways I tried) as I came upon the same problem.
Answer: Just do Set(Set.(a)):
julia> Set(Set.(a))
Set{Set{Int64}} with 2 elements:
  Set([4, 3])
  Set([2, 1])

And of course you can have a Vector of vectors by using collect and perhaps sort each Vector:
julia> sort.(collect.(Set(Set.(a))))
2-element Vector{Vector{Int64}}:
 [3, 4]
 [1, 2]

Comment: That's really elegant!
Answer: You can use unique.
julia> a=[[1,2],[3,4],[2,1],[4,3],[3,3,4],[4,3,3]];
julia> unique(sort,a)
3-element Vector{Vector{Int64}}:
 [1, 2]
 [3, 4]
 [3, 3, 4]

If you need to distinguish the number of each element, you should use sort.