Cannot draw basic triangle with vbos opengl in lwjgl

Question: I tried to draw a simple triangle using lwjgl
Here is my 3D Object class:
public class ThreeDObject {

    float[] vertices;
    float[] color;

    int vao;
    int vvbo; //vertex vbo
    int cvbo; //color vbo
    int vtexNumber;
    boolean isSetUp = false;

    String fragmentShader;
    String vertexShader;
    int frag;
    int vert;
    int program;

    public ThreeDObject( float[] vertices, float[] color) {
        this.vertices = vertices;
        this.color = color;
        this.vtexNumber = this.vertices.length / 3;
        setupVAO();
        this.vertexShader = defaultVert;
        this.fragmentShader = defaultFrag;
        setupShaders();
        System.out.println(Arrays.toString(this.vertices));
    }

    public void setupVAO() {

        FloatBuffer vb = BufferUtils.createFloatBuffer(vertices.length);
        vb.put(vertices).flip();

        FloatBuffer cb = BufferUtils.createFloatBuffer(color.length);
        cb.put(color).flip();

        if(hasEBO()) {
            IntBuffer ob = BufferUtils.createIntBuffer(order.length);
            ob.put(order).flip();
        }

        vao = GL30.glGenVertexArrays();

        GL30.glBindVertexArray(vao);

        vvbo = GL15.glGenBuffers();
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vvbo);
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vb, GL15.GL_STATIC_DRAW);
        GL30.glVertexAttribPointer(0, 3, GL30.GL_FLOAT, false, 0, 0);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);

        GL20.glEnableVertexAttribArray(0);
        GL30.glVertexAttribPointer(0, 3, GL30.GL_FLOAT, false, 0, 0);

        cvbo = GL15.glGenBuffers();
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, cvbo);
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, cb, GL15.GL_STATIC_DRAW);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);

        GL20.glEnableVertexAttribArray(1);
        GL30.glVertexAttribPointer(1, 3, GL30.GL_FLOAT, false, 0, 0);

        GL30.glBindVertexArray(0);

        isSetUp = true;
    }

    public void setupShaders() {

        GL30.glBindVertexArray(vao);

        program = GL20.glCreateProgram();
        vert = GL20.glCreateShader(GL20.GL_VERTEX_SHADER);
        GL20.glShaderSource(vert, vertexShader);
        frag = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER);
        GL20.glShaderSource(frag, fragmentShader);
        GL20.glCompileShader(vert);
        if(GL20.glGetShaderi(vert, GL20.GL_COMPILE_STATUS) == GL20.GL_FALSE) {
            System.out.println("Couldn't comile vertex shader");
            System.out.println(GL30.glGetShaderInfoLog(vert));
        }
        GL20.glCompileShader(frag);
        if(GL20.glGetShaderi(frag, GL20.GL_COMPILE_STATUS) == GL20.GL_FALSE) {
            System.out.println("Couldn't comile fragment shader");
            System.out.println(GL30.glGetShaderInfoLog(frag));
        }

        GL20.glAttachShader(program, vert);
        GL20.glAttachShader(program, frag);;

        GL20.glValidateProgram(program);
        if(GL20.glGetProgrami(program, GL20.GL_VALIDATE_STATUS) != GL20.GL_TRUE) {
            System.out.println("Can't validate shader");
            System.out.println(GL20.glGetProgramInfoLog(program));
        }

        GL30.glBindVertexArray(0);

    }

    public void draw() {

        GL20.glUseProgram(program);
        GL30.glBindVertexArray(vao);

            GL15.glDrawArrays(GL15.GL_TRIANGLES, 0, vtexNumber);

        GL30.glBindVertexArray(0);

    }

}

And my constructor is:
t = new ThreeDObject(new float[] {
                0.0f, 0.0f, 0.0f,
                0.0f, 0.0f, 0.0f,
                -1.0f, -1.0f, 0.0f
        }, new float[] {
                1.0f, 0.0f, 0.0f,
                0.0f, 1.0f, 0.0f,
                0.0f, 0.0f, 1.0f
        });

(the constructor is wrong on purpose).
I removed some unused code, tell me if you can't find the error
All i get is an white triangle being drawn to the screen.
I tried every solution i could find if you can help me I will be greatful.
EDIT: I changed some code but still got the same result.
On the console i get this:
Can't validate shader

[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, -1.0, 0.0]

Here's the vertex shader:
#version 330
out vec4 outColor;

layout (location = 0) in vec3 inPosition;
layout (location = 1) in vec3 inColor;

void main() {

    gl_Position = vec4(inPosition,1.0);
    outColor = vec4(inColor, 1.0);

}

And here's the fragment shader:

#version 330

in vec3 outColor;

out vec4 finalColor;

void main() {

    finalColor = vec4(1.0,0.0,0.0,1.0);

}

the result is this triangle:
Image
Result when i link the shader:
Result
EDIT 2:
I changed the code
I'm linking the shader now:
        GL20.glAttachShader(program, frag);

        GL20.glLinkProgram(program);
        if(GL20.glGetProgrami(program, GL20.GL_LINK_STATUS) != GL20.GL_TRUE) {
            System.out.println("Can't link shader");
            System.out.println(GL20.glGetProgramInfoLog(program));
        }

        GL20.glValidateProgram(program);

I also changed this line:
GL15.glDrawArrays(GL15.GL_TRIANGLES, 0, vtexNumber);

        GL30.glBindVertexArray(0);
        GL20.glUseProgram(0);

and changed the vertex and fragment shaders:
Vertex:

#version 330
out vec3 vertColor;

layout (location = 0) in vec3 inPosition;
layout (location = 1) in vec3 inColor;

void main() {

    gl_Position = vec4(inPosition,1.0);
    vertColor = inColor;

}

Fragment:

#version 330

in vec3 vertColor;

out vec4 FragColor;

void main() {

    FragColor = vec4(vertColor,1.0);

}

but i still get weird results:
I get a black triangle covering half of the window, I try to move the camera but nothing changes.
Black triangle
Comment: Why do you `glEnableClientState`? If you are using a shader program, you do not need the fixed function attributes.
Comment: @Rabbid76 I edit the post and the code to add more detail but I still get the same result.
Comment: Where do you link the shader program? ([`glLinkProgram`](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glLinkProgram.xhtml)). Furthermore, the 1st and 2nd vertex coordinate are identical.
Comment: @Rabbid76 when i link the shader i get an even weirder result: the screen is all red, I programmed for the screen to change color when I press a key, when i press that key nothing happens, the 1st and 2nd are the same on purpose, even when using a wrong triangle it still shows the same thing
Comment: When i link the shader using this: `GL20.glAttachShader(program, frag);

  GL20.glLinkProgram(program);
  if(GL20.GL_LINK_STATUS != GL20.GL_TRUE) {
   System.out.println("Can't link shader");
   System.out.println(GL20.glGetProgramInfoLog(program));
  }

  GL20.glValidateProgram(program);` i get the same result in the console and get this result in the window: The result is in the post
Comment: Actually i get nothing in the console, but the same red screen
Answer: Ok, I tested your code and found 2 errors,
1. As I suspected your vertex data for the triangle is arranged incorrectly,
When I test out your vertex data I got a blank screen (idk how you managed to get a triangle).
t = new ThreeDObject(new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f }, // Your vertex data
results in
A blank screen (grey is the clear colour)
If you see, your vertex data is not arranged in counter-clockwise order (CCW); OpenGL prefers data in CCW order. It should be like this:
Sorry for the link, cannot embed photo's yet, btw look at triangle 2, for counter-clockwise vertex order
So, I went an changed the order to this:
t = new ThreeDObject(new float[] { -1.0f, 1.0f, 0f, -1.0f, -1.0f, 0f, 1.0f, -1.0f, 0f } //V1 --> V3 --> V2
which resulted in:
The triangle you hopefully wanted (with the colours)
Here's another one (with a every coordinate halved)
2. Also this code:
    cvbo = GL15.glGenBuffers();
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, cvbo);
    GL15.glBufferData(GL15.GL_ARRAY_BUFFER, cb, GL15.GL_STATIC_DRAW);
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
    GL20.glEnableVertexAttribArray(1);
    GL30.glVertexAttribPointer(1, 3, GL30.GL_FLOAT, false, 0, 0);

should be like this:
    cvbo = GL15.glGenBuffers();
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, cvbo);
    GL15.glBufferData(GL15.GL_ARRAY_BUFFER, cb, GL15.GL_STATIC_DRAW);
    GL30.glVertexAttribPointer(1, 3, GL30.GL_FLOAT, false, 0, 0);
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
    GL20.glEnableVertexAttribArray(1);

Always allocate your attribute slots while the buffer is bound, so there is minial chance of mislocation error (a reason why you might got a black triangle, because your data was mixed up).
If you need any more help or need to see my code, please pop a comment!
Comment: Thank you for this reply, it actually worked, i don't know how i didn't realize that.
Comment: I also have another problem, the camera is not moving, I am using JOML: I create a matrix use the lookAt function (similar to glut) and setting as the projection matrix using glLoadMatrix, when i use the fixed function pipeline it works but not using vaos.
Comment: Sorry for the late reply... Check to make sure your matrices do not have any errors; I tend to create the matrices myself so they can debugged easier than using OpenGL's built in functions. In a while, I will try to upload another answer on how correctly create the lookAt and projection matrix. :)
Answer: TO ANYONE ELSE: This is not a answer to the question but to the comment of the author in another answer.
ViewMatrix:
When you define a camera, your are technically / need to already define a view space (therefore called viewMatrix or lookAtMatrix). This is important as this matrix transforms your objects from world space to view space (camera space), where all object are defined in terms of the camera.
(Think about it... if your worldMatrix / modelMatrix transforms all of your objects in terms of the world origin, your viewMatrix transforms all of your objects in terms of your camera (where the camera is now the origin and whatever is not seen by camera is automatically discarded).
This is how I define my camera class in my programs (Keeping scroll all the way till the end for a complete breakdown):
public class Camera {

private Vector3f position;
private Vector3f cameraDirection;

private float pitch = 0f;
private float yaw = -90.0f;
private float roll = 0f;

private float lastMX = 0f;
private float lastMY = 0f;
private float mouseSensitivity = 0.1f;

private Vector3f front = new Vector3f(0, 0 ,-1);
private Vector3f up = new Vector3f(0, 1, 0);

private Matrix4f lookAt;

public Camera(Vector3f position) {
    this.position = position;
    lookAt = new Matrix4f().lookAt(position, position.add(front), up);
}

public void input() {

    float xOffSet = (float) (Input.getMouseX()) - lastMX;
    float yOffSet = (float) (-Input.getMouseY()) + lastMY;

    lastMX = (float) Input.getMouseX();
    lastMY = (float) Input.getMouseY();

    yaw += (xOffSet *= mouseSensitivity);
    pitch += (yOffSet *= mouseSensitivity);

    if(pitch > 89.0f) pitch = 89.0f;
    if(pitch < -89.0f) pitch = -89.0f;

    float cameraSpeed = 2.5f * Window.getDeltaTime();

    if(Input.isKeyDown(GLFW.GLFW_KEY_W)) position.add(front.mul(cameraSpeed));
    if(Input.isKeyDown(GLFW.GLFW_KEY_S)) position.sub(front.mul(cameraSpeed));
    if(Input.isKeyDown(GLFW.GLFW_KEY_A)) position.sub(new Vector3f(front.cross(up)).normalize().mul(cameraSpeed));
    if(Input.isKeyDown(GLFW.GLFW_KEY_D)) position.add(new Vector3f(front.cross(up)).normalize().mul(cameraSpeed));

    position.y = 0.0f;
}

public void update() {

    input();

    setCameraDirection(new Vector3f((float) Math.cos(Math.toRadians(yaw)),
                                    (float) Math.sin(Math.toRadians(pitch)),
                                    (float) Math.sin(Math.toRadians(yaw))));

    front = getCameraDirection().normalize();
    lookAt.identity().lookAt(position, new Vector3f(position).add(front), up);
}

public Vector3f getPosition() {
    return position;
}

public float getPitch() {
    return pitch;
}

public float getYaw() {
    return yaw;
}

public float getRoll() {
    return roll;
}

public Vector3f getCameraDirection() {
    return cameraDirection;
}

public void setCameraDirection(Vector3f cameraDirection) {
    this.cameraDirection = cameraDirection;
}

public Matrix4f getLookAtMatrix() {
    return lookAt;
}

}

So, if you have seen the lookAt matrix is defined, using JOML, by three vectors:
A Camera Position;
A Center (Front Vector + Camera Position);
And A Up vector;
The Camera Position simply defines the position of the camera in the world (obviously how else would it exist).
The Center is a little tricky to understand but all it does it defines the point to where the camera should be looking towards.

If your center does not change, then you have got what is called a Third Person Camera, where the camera rotates at a variable radius around a center point.

But if you want a First Person Camera, your center cannot stay constant, and therefore has to be recalculated every frame to be able to create a smooth, first person effect.
If see above, in the update() method, the front vector is recalculated every frame using cameraDirection(the direction to where the camera is facing).

The cameraDirection itself has to calculated every frame for the above process to work.

PITCH, YAW, ROLL:
What are they

They are simply the rotations around the three axes (x = Pitch, y = Yaw, z = Roll) (see image). Using these and bit of Trigonometry we can calculate where the camera is looking towards (cameraDirection):
    public void update() {

    input();

    setCameraDirection(new Vector3f((float) Math.cos(Math.toRadians(yaw)),
                                    (float) Math.sin(Math.toRadians(pitch)),
                                    (float) Math.sin(Math.toRadians(yaw))));

    front = getCameraDirection().normalize();
    lookAt.identity().lookAt(position, new Vector3f(position).add(front), up);
    }

We can calculate x and z components of the direction vector, using the y rotation (YAW) and some trigonometry
We also need the y direction, which can be calculate through the (PITCH)
Make sure to normalize the direction vector (as with any direction vectors) to a unit vector, otherwise the center will be messed up
So now we have got a direction / front and position vector.
The UP Vector:
To define a "space" like the view space or world space or tangent space, you need three vectors that define the three axes of that space --> x axis, y axis and the z axis
I do not know too much in depth about this (and I might be wrong):
The UP vector defines the y axis of the view space (the x axis is direction vector and z axis (right vector) is the cross product of the x and y axis).
The UP vector is just (0, 1, 0) and is never changed because the 1 represents that is point straight up (positive y-direction).
And there you have the lookAt matrix function:
                                //camPos     //center       //up
lookAt = new Matrix4f().lookAt(position, position.add(front), up);

Credits: https://learnopengl.com/Getting-started/Camera,
definitely recommend looking at this tutorials for a in depth tutorial.
Answer: Firstly, call the GL30.glVertexAttribPointer(1, 3, GL30.GL_FLOAT, false, 0, 0); (for the colour buffer) before calling GL20.glEnableVertexAttribArray(1); (you should allocate your attributes before enabling the attribute arrays).
Secondly, your draw function incorrect:
When rendering,

Bind your shader (GL20.glUseProgram(program))

Bind your VAO (GL30.glBindVertexArray(VAO))

Setup your shader uniforms (I guess your not up to this step yet, so dont worry for now)

Enable your vertex attribute arrays (GL30.glEnableVertexAttribArray(number)) - Calling this method for every buffer slot allocated and EVERY TIME YOU RENDER (not just when you set up the buffers).

Render / call the draw function

Disable your vertex attribute arrays (GL30.glDisableVertexAttribArray(number)) - Calling this method for every buffer slot allocated and again, EVERY TIME YOU RENDER

Unbind VAO (GL30.glBindVertexArray(0))

Unbind Shader (GL20.glUseProgram(0))
Comment: Actually, I have to agree with @Rabbid76 here, even though your first and second vertices are same on purpose, this just affects your first triangle of the quad, your second triangle is still being rendered correctly, because the first two vertices do not affect it. (Thats why you have 1 coloured triangle and 1 black one (in your image) because the first triangle does not exist and cannot be coloured).
Comment: @SnipingPoodle there's only one triangle the second array is the color array
Comment: Also I am already doing what you're saying in you awnser
Comment: Wait hold on, I am just quickly gonna create a test program using your vertex data.


Definition of Algebraically Independent Numbers

Question: Let $x_1,\dots,x_n$ be complex numbers. Some authors define $x_1,\dots,x_n$ to be algebraically independent numbers if $x_1,\dots,x_n$ are algebraically independent over the field $\mathbb{Q}$ of rational numbers, while others call them algebraically independent numbers if they are algebraically independent over the field $\bar{\mathbb{Q}}$ of algebraic numbers.
I am pretty sure that the two definitions are equivalent, but I have a very elementary knowledge of algebra, so I cannot prove this equivalence, nor I could find some book which includes this statement.
Could someone help me by providing me a proof or some reference?
Thank you very very ... much for your help in advance.
Comment: Assume there is a nonzero polynomial $P$ with algebraic coefficients such that $P(x_1,\ldots,x_n)$. There exists a finite Galois extension $K/\mathbb{Q}$ with group $G$ containing all the coefficients of $P$. Then $Q:=\prod_{\sigma \in G}{\sigma(P)}$ is a rational nonzero polynomial and $Q(x_1,\ldots,x_n)=0$.
Comment: Dear Mindlack, thank you very very much for having kindly replied to my question! Could you write your comment as an answer, please? Thank you very very much again!
Comment: You're welcome!
Answer: This is a retelling of my comment.
Assume there is a nonzero polynomial $P$ with algebraic coefficients such that $P(x_1,\ldots,x_n)=0$.
There exists a finite Galois extension $K/\mathbb{Q}$ (with group $G$) containing all the coefficients of $P$.
Consider the nonzero polynomial $Q=\prod_{\sigma \in G}{\sigma(P)}$. It has coefficients in $K$ and is invariant under $G$ so has rational coefficients. Moreover, it's clear $Q(x_1,\ldots,x_n)=0$.
Comment: Dear @Mindlack, thank you very very ... much for having kindly written your answer! I must admit that I am now beginning to study the theory of fields and Galois theory, so I cannot fully understand you proof, but I hope that in some weeks I will have all the notions needed to grasp it. Thank you very muc again!
Comment: I also found the following argument in the book by Murty and Rath [Transcendental Numbers](https://books.google.it/books?id=-4jkAwAAQBAJ&printsec=frontcover&dq=murty+rath+transcendental+numbers&hl=it&sa=X&ved=2ahUKEwiWwsOyybjrAhUwtYsKHan5DfYQ6AEwAHoECAQQAg#v=onepage&q=murty%20rath%20transcendental%20numbers&f=false). Let $K$ be a field, and $F$ an extension of $K$. Then the transcendence degree of $F$ over $K$ is the cardinality of a maximally algebraically independent subset of $F$ over $K$.
Comment: (continuation of the previous comment) Since the transcendence degree over $K$ or over any of the algebraic extensions of $K$ is the same, the notion of algebraic independence of complex number over $\mathbb{Q}$ or $\bar{\mathbb{Q}}$ is the same.
Comment: I know too little about the theory of fields to understand this argument. What do you think about it? Is it a straightforward one or does it involve some implicit steps?
Comment: There may be a way to do away with some of it, but I think there are implicit steps. Just the biggest one – why, with your definition, is the transcendance degree invariant when you replace the base field with an algebraic extension?
Comment: Yes, this is exactly what I was thinking about! Thank you very much again for your invaluable help!


Server became dead because of memory issue

Question: I am using cheap VDS hosting. So have a hard RAM limit. (256 Mb)
I was trying to switch from apache to a new web server cherokee. So turned off apache, and configured cherokee to work instead. But then the server was rebooted and apache automatically started (as cherokee did).
So now I have 2 servers which listen to 80 port. And no one works
Also I think that all RAM was consumed...
ssh doesn't work:

silver:~ oleg$ ssh firstname.lastname@example.com
ssh_exchange_identification: Connection closed by remote host
silver:~ oleg$

And when I call their sys admins they say me call your system administrator.
What should I do in this situation?

silver:~ oleg$ ssh -vvv email@example.com
  OpenSSH_5.1p1, OpenSSL 0.9.7l 28 Sep
  2006 debug1: Reading configuration
  data /Users/oleg/.ssh/config debug1:
  Applying options for
  oplot.vds.colocall.com debug1: Reading
  configuration data /etc/ssh_config
  debug2: ssh_connect: needpriv 0
  debug1: Connecting to
  oplot.vds.colocall.com [126.96.36.199]
  port 22. debug1: Connection
  established. debug1: identity file
  /Users/oleg/.ssh/identity type -1
  debug3: Not a RSA1 key file
  /Users/oleg/.ssh/id_rsa. debug2:
  key_type_from_name: unknown key type
  '-----BEGIN' debug3: key_read: missing
  keytype debug2: key_type_from_name:
  unknown key type 'Proc-Type:' debug3:
  key_read: missing keytype debug2:
  key_type_from_name: unknown key type
  'DEK-Info:' debug3: key_read: missing
  keytype debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug3: key_read: missing
  whitespace debug2: key_type_from_name:
  unknown key type '-----END' debug3:
  key_read: missing keytype debug1:
  identity file /Users/oleg/.ssh/id_rsa
  type 1 debug1: identity file
  /Users/oleg/.ssh/id_dsa type -1
  ssh_exchange_identification:
  Connection closed by remote host
  silver:~ oleg$
Comment: First off, use the -v flags to ssh to check exactly what the problem is.  ssh -vvv will give you many, many debugging messages which should tell you why you can't log in.
Comment: Just added comment with output
Answer: Looks to me like it's your ssh client that's the issue.  From my box:
$ ssh firstname.lastname@example.com
email@example.com's password:

Are you trying from your usual box?  Do you have a different box you can try from?
Answer: Well, apache is listening on port 80, presumably because it was started first. You can disable apache by running chkconfig --level 345 httpd off.
The behaviour of the server is consistent with hitting an enforced memory limit, as you wouldn't be able to fork any new processes. If this is the case, and you only have ssh access, then there's probably nothing you can do without some intervention by the VPS provider.
Answer: can you get remote console access to the virtual machine?
if so, you could reboot it into single-user mode (or just reboot with init=/bin/bash and remount the root fs as RW), change the config so that only one of apache or cherokee is going to start up, and then reboot again.
failing that, as theotherreceive suggested, maybe someone at your VPS provider can do that for you.


Find the quotient space of $\equiv \subseteq \mathbb R^2$ such that $x \equiv y \iff (\exists t >0)(tx=y)$

Question:
Find the quotient space of $\equiv \subseteq \mathbb R^2$ such that $x
> \equiv y \iff (\exists t >0)(tx=y)$

The quotient space is the set of all equivalence classes of given equivalence relation, and so the first thing to do is to find those classes. I can think of three classes that when combined cover the whole set of real numbers. Namely $[0]_{\equiv}, [1]_{\equiv}, [-1]_{\equiv}$ And so, the quotient space appears to be:
$$ \frac{\mathbb R}{\equiv} = \{[0]_{\equiv}, [1]_{\equiv}, [-1]_{\equiv} \}$$
Where
$[0]_{\equiv} = \{0 \}$
$[1]_{\equiv} = \{y \mid y>0 \}$
$[-1]_{\equiv} = \{y \mid y<0\}$
Is it the correct solution?
Comment: re-reading the question I think it is correct. I previously misread it assuming that the elements $x$ and $y$ belongs to $\Bbb R^2$ instead of $\Bbb R$. My bad.
Answer: The problem asks to find a nice set of representatives for each element of the quotient space, so then we can identify this set of representatives with the quotient space. Hence the quotient space is "going to be" this set of representatives.
Now it appears that you are not computing the requested quotient space but an analogous quotient for $\mathbb{R}$. Your solution for this different problem is correct though.
One answer for the original problem, as hinted by Masacroso, is giving by the set of representatives $X=\mathbb{S^1}\cup \{0\}=\{\vec x\in \mathbb{R}^2 \mid \  \|\vec x\|=1 \}\cup \{\vec 0\}$.
Indeed, any element of $\mathbb{R}^2/\equiv$ is equivalent to an element in $X$ because $[x]=[\frac x {\|x\|}]$ with $\frac x {\|x\|}\in X$. And also two different elements in $X$ are not equivalent because if $x,y\in X$ and $x\equiv y$ then we have $x=t y$ with $t>0$ and hence $1=\|x\|=\|ty\|=t\|y\|=t$ so $x=ty=y$.
Nevertheless, this is not the unique solution to the problem because there are other nice set of representatives that could be though as the solution. For example the set of representatives $$Y=\{(x,y) \mid y=-1\} \cup {(0,0)} \cup \{(1,0)\}$$
is other possible solution to the problem.
In some sense the first solution is better than the second because the "shape" of this set is compatible with the equivalence relation in some sense. (This can be made precise with the notion of Quotient topology, but probably you should not worry about this for the moment)
If you have any questions, do not hesitate to ask in the comments.
Comment: Now that I have re-read your question I think your solution is correct and I misinterpret the problem. Usually when someone describe an equivalence relation in $X$, the emphasis goes in the space $X$ and how the elements of $X$ are compared, the actual relation as a subset of $X\times X$ stay implicit. I hope my answer would be useful for you anyway.


using the "__and__" method in the abstract base int class

Question: I am trying to understand the __and__ method of the abstract base int Class. Here I have called the method two different ways. In nearly all cases, the two ways each behave as I expect, they output the second value, because both values are "truthy". But in the special case that the sum of the two numbers = -1, then the first way prints 0. Can anyone say why?
value = -4
print(value.__and__(3)) # prints 0
print(value and 3)         # prints 3

Comment: And where did you get the idea of a "Number Class"? There's no Number class.
Comment: @user2357112: It's an [abstract base class](https://docs.python.org/3/library/numbers.html).
Comment: What makes you say it's not bitwise AND?
Answer: The "problem" is not with the __and__ operator. The bitwise operator in python is not and it's &:
>>> (7).__and__(5) == (7 & 5)
True

As for how and interacts with non boolean values, you can read this answer. For your particular case:

and Returns the first Falsy value if there are any, else return the last value in the expression.

In your case, both -4 and 3 are non Falsy values, therefore the last value (3) is returned. Considering what is considered Falsy we can also understand why -4 and 0 and 3 == 0, ie., because 0 is Falsy.
Note that this behavior for the and operator makes sense. It just extends the logic of the natural boolean and operator in the most natural way (or at least one of the most natural way). For example, True and False and False and x, will return False as soon as the first False is encountered, while True and True and x will simply return x as all previous boolean values validate the global statement.
Finally, the apparently strange behavior of the bitwise operator when dealing with negative numbers comes from how negative numbers are encoded. Basically, to turn a positive number (eg, 4 = 000100) into a negative, you simply need to invert all it's bits (111011) then add 1 (111100 = -4). In the evaluating 3 & -4 is equivalent to solving the following:
  000011
& 111100
--------
= 000000

For the same reason x & -4 will evaluate to 4 for any x in 4, 5, 6, 7 (the two low digits are always canceled by the terminating zeros in the binary representation of -4 (111100).
Comment: so, you are not sure why it is returning 0?
Comment: I can add that detail if that seems important to you :)
Comment: Now that I read my answer I wonder if you weren't talking about the `0` in  `print((-4).__and__(3))`. I should probably detail that case too, but maybe that wasn't your question?
Answer: A classmate pointed out that the and() method uses "bitwise and". Not the normal AND. Also, I was using signed integers in my calculations instead of two's complement.


Computing the residues of $\dfrac{1}{\sin^2 z}$.

Question: I'm having a hard time correctly computing the residues of $\dfrac{1}{\sin^2 z}$. I
know the poles occur at $k\pi$, with order $2$.
By a Taylor expansion I can rewrite $\sin z=\cos k\pi(z-k\pi)+f_2(z)(z-k\pi)^2$, and so
$$
\sin^2 z=(z-k\pi)^2(\cos k\pi+f_2(z)(z-k\pi))^2.
$$
I want to calculate the residue with Cauchy's Integral Theorem, so
$$
\text{Res}(f,k\pi)=\frac{1}{2\pi i}\int_{|z-k\pi|=1}\frac{dz}{(z-k\pi)^2[\cos k\pi
+f_2(z)(z-k\pi)]^2}.
$$
This should equal the derivative of $(\cos k\pi+f_2(z)(z-k\pi))^{-2}$ evaluated at $k

\pi$. The derivative comes out to be
$$
-2(\cos k\pi+f_2(z)(z-k\pi))^{-3}(f'_2(z)(z-k\pi)+f_2(z))
$$
and evaluates to $\dfrac{-2f_2(k\pi)}{(\cos k\pi)^3}$. Apparently the residue should
just be $0$, but I don't see how to conclude this. What am I missing to know $f_2(k\pi)=0$?
Comment: Since $\sin^2z$ has period $\pi$ the residue at $k\pi$ is the same for all $k$. But the function is even so the residue at $z=0$ is ...
Answer: You're working too hard. Do the residue at $z=0$ first: $1/\sin^2 z$ is an even function, so its series expansion involves only even power of $z$. Or, if you wish, you can see that $$\int_C \frac1{\sin^2z}\,dz=0$$ for a small circle $C$ centered at the origin, by noticing that the integrand is the same on opposite points of the circle, while $dz$ on opposite sides are each other's negatives.
The residues at the other poles follow by periodicity.
Comment: Thanks Harald, this is indeed much easier. Is there a way to salvage the work I've done? Even if it's less elegant, that's the way I first begin to see it.
Comment: @Cowbell: if the answer is useful, which it is, upvote (+1). :-)
Comment: @Cowbell: Sure, in your calculation, you may notice that $f_2$ must be an odd function, by considering the symmetry properties of the other terms in the equation defining $f_2$. In particular, $f_(0)=0$.
Comment: From the defining equation $\sin z=\cos k\pi(z-k\pi)+f_2(z)(z-k\pi)^2$, I find that $f(z)+f(-z)=2k\pi\cos k\pi$, not zero. Is this the incorrect way to check if a complex valued function is odd?
Comment: @Cowbell: That gives you the right answer for $k=0$, anyhow. And for other values of $k$, you should consider even and odd symmetry around $z=k\pi$. So you should get $f_2(k\pi-z)=-f_2(k\pi+z)$. (But it is easier to just do it for $k=0$ and then let periodicity take care of the other cases.)
Comment: Thanks, this has been very helpful.
Answer: $\sin(z)=z-z^3/6+\dots$ so
$$
\begin{align}
\frac{1}{\sin^2(z)}
&=\frac{1}{z^2}\left(1-z^2/6+\dots\right)^{-2}\\
&=\frac{1}{z^2}\left(1+z^2/3+\dots\right)\\
&=\frac{1}{z^2}+\frac13+\dots
\end{align}
$$
Thus, the residue at $z=0$ is $0$ since there is no $\dfrac{1}{z}$ term. The others follow by periodicity.
Comment: @vladimirm: There are several ways to show that $$\left(1+x+o(x)\right)^{-2}=1-2x+o(x)$$ one of the easiest is the [generalized binomial theorem](http://en.wikipedia.org/wiki/Binomial_theorem#Newton.27s_generalised_binomial_theorem).
Comment: Thanks, this was a nice simple way to look at it.
Comment: How do you lose the exponent $-2$ in the second row?


In the Lydian Chromatic Theory, what does the "H" mean next to scale degrees?

Question: referring to "Chart A" of the Lydian Chromatic Concept Theory -

what does the "h" mean next to the Vh, IIh, and Ih scale degrees?  I understand that they are Alternate Modal Tonic Degrees, but I haven't found anywhere in the book that clearly explains it.
Comment: Are you asking what the "h" means, or are you asking what a "alternate and conceptual modal tonics" are?
Comment: I'm asking what the "h" means
Answer:
The letter "h" following these roman numerals (as in Vh, IIh, IIIh and
VIIh) indicates their status as conceptual modal tonic degrees of the Lydian
Scale.1

1 h = Horizontal state of the LC Scale: duality of non-final to final. v = Vertical state of the LC Scale: unity of chord and scale.

George Russell, The Lydian Chromatic Concept of Tonal Organization, 4th edition (Brookline, MA: Concept Publishing Company, 2001), page 116.


How do I read an image from a base64 encoded string in Objective C?

Question: I'm getting a XML containing image which is base64 encoded.I've  to decode that & need to display a image.Any suggestions.............
Answer: There's a nice post on cocoawithlove.com about decoding base64 on both Mac OS and iPhone.
Here's a Mac OS way to create an NSImage:
unsigned char* data;
int width, height;

NSBitmapImageRep* rep;
rep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&data
                                              pixelsWide:width
                                              pixelsHigh:height
                                           bitsPerSample:8
                                         samplesPerPixel:4
                                                hasAlpha:YES
                                                isPlanar:NO
                                          colorSpaceName:NSCalibratedRGBColorSpace
                                            bitmapFormat:NSAlphaNonpremultipliedBitmapFormat
                                             bytesPerRow:32
                                            bitsPerPixel:32];
NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(8, 8)];
[image addRepresentation:rep];

This works on the iPhone to create an UIImage:
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(data, width, height, 8, 32, colorspace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorspace);
CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
CGContextRelease(ctx);
UIImage* image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);

Comment: Any recommendations on getting the width and height?


Create a polynomial with given zeros

Question: Find a polynomial $()$ of degree 5 with zeros $3i, 1+ i$ and $2$ that satisfies $(0) = −18$ . Do not need
to multiply it out
A problem like this is simple, start with $p(x)=(x-3i)(x-(1+i))(x-2)$ . Now I'm assuming these are the only zeros we're allowed to have, and we must have a degree of 5. So two of these must be squared. But there is no way to combine these to get $p(0)=-18$. I feel like there's a mistake in the problem.
Here's another approach $|-3i|=3, |-1-i|=\sqrt 2 $, and $|2|=2$. It's impossible to combine $\sqrt 2, 2,$ and $3 $to get $-18$
Comment: You can also multiply the whole thing by a constant, for instance $100(x-3i)\cdots$.
Comment: But you wouldn't get that degree of 5. Unless you randomly get a degree of 5, and then multiply by a constant fraction to reduce it to -18?
Comment: I'm just trying to extend your solution. You say you got to the point where you can obtain a polynomial of degree 5, with the correct roots, but not satisfying $p(0)=-18$. Well, then multiply it by a good constant.
Comment: If you want real coefficients, then assume you have 2 other solutions, 1 - i, and -3i. Then you will get a nice degree 5 equation with real coefficients. Multiply if necessary to get p(0)=18.
Answer: You can have $$p(x)=\frac{i}{2}(x-3i)^2(x-(1+i))^2(x-2)$$
But this is a complex polynomial. It doesn't mention that these are the only zeros you are allowed to have, so we can use the complex conjugates to obtain $$p(x)=\frac{1}{2}(x-3i)(x+3i)(x-(1+i))(x-(1-i))(x-2).$$
This gives a degree $5$ polynomial with real coefficients that satisfies $p(0)=-18.$

Create a polynomial with given zeros


Jest/Enzyme with styled components

Question: I can't for the life of me get Jest/Enzyme to play nicely with styled components.
I have a component I am mounting that filters out a list of 5 of the most recent shipments.
  it("should have five shipments", () => {
    const wrapper = shallow(<LastFiveShipments shipments={dummyProps.shipments} />);
    wrapper.debug();
    const styledList = wrapper.find("styled.ul");
    expect(styledList).exists().to.equal(true);;
  })

const LastFiveShipments = ({shipments}) => {
  return (

  )
}

const StyledList = styled.ul`
  padding: 1em;
  margin: 0 10px;
  background: #f0f0f0;
  border-radius: 10px;
  border: 1px solid #14374e;
  margin: 1em 0;

  & li {
    text-align: center;
  }
`;

styled.ul is the displayName and find is having no luck selecting it.
Answer: You can also rename your styled component to make it easier to read. For example
const StyledList = styled.ul`
  padding: 1em;
  margin: 0 10px;
  background: #f0f0f0;
  border-radius: 10px;
  border: 1px solid #14374e;
  margin: 1em 0;

  & li {
    text-align: center;
  }
`;

StyledList.displayName = 'ul';

test.js
expect(wrapper.find('ul')).toHaveLength(1)

In that way, you don't need to import your styled component
Answer: You can import the component you're searching for, in this case StyledList, and use it instead of "styled.ul"
import StyledList from ''

wrapper.find(StyledList)

Comment: It's a styled ul inside of a component.
Comment: You can export the styled component so it can be imported and used to `.find` in your tests
Answer: @Donovan beat me to it.
Anyway, I was able to replicate the same problem, however, there are two workarounds:

Instead of using shallow, you can mount the component and then assert: expect(wrapper.find("StyledComponent > ul")).toHaveLength(1);.
Instead of mounting the component, you can import StyledList from 'path/to/styledList'; and then assert: expect(wrapper.find(StyledList)).toHaveLength(1)

Working example:

Jest/Enzyme with styled components


How to fix max drawn entries on Line Chart?

Question: I'm putting a lot of entries to chart. Like 100-200 of them. It's running stats at each second. So my graph looks very messy when we getting bigger and bigger reached range. So is it possible to fix X axis values that will be drawn on graph? For example if we have 200+ values of 10 km just draw 30 of them also at 10 km on even checkpoints to make graph less accurate but more understandable
Answer: MpChart draws every point which is given by programmer, it never decides which should be drawn or not, so I think the only way is to find the 30 checkpoints by some filter function and set it to MpChart, then call chart.invalidate
Comment: Looks like it's the only option. Thanks


Iterated Integral of $(8x^3-36x^2y^2)dydx$

Question: I've been struggling for a bit on this math problem from my homework.
$$
\int_{0}^{1}\int_{1}^{3}(8x^3-36x^2y^2)dydx
$$
From what I understand and have attempted, we'll integrate with respect to $x$ first, so something like:
$$
(2x^4-12x^3y^2)\vert_{1}^{3}=160-312y^2
$$
and then another integration, this time with respect to $y$:
$$
160y-104y^3\vert_{0}^{1}=(160-104)-(0-0) = \textbf{56}
$$
Yet my book says its wrong.
I could be missing something for all I know, or could it just be something simple I'm overlooking? Regardless, I'm a bit stumped and would appreciate a nudge in the right direction.
Thank you!
Answer: The order of integration is from the inside out, so $dy \, dx$ means you integrate with respect to $y$ first, then with respect to $x$.
So the first antiderivative is
$$\int 8x^3 - 36 x^2 y^2 \, dy = 8x^3 y - 12 x^2 y^3 + C$$
and you evaluate these at the endpoints $y = 3$ and $y = 1$:
$$\int_{y=1}^3 8x^3 - 36 x^2 y^2 \, dy = \left[8x^3 y - 12 x^2 y^3 \right]_{y=1}^3 = 16x^3 - 312 x^2.$$
The remainder of the computation I leave as an exercise.


C++ create temporary object to call member function

Question: What's wrong with the line of code with compile errors (in comment), in the code below?  I thought it is supposed to call the TestMe constructor with the const std::string, then call operator() on it.  But it looks like it is trying to construct TestMe with variable a.
#include <iostream>

namespace
{
class TestMe
{
public:
    TestMe() {}
    TestMe( const std::string& me ) : me_( me ) {}

    bool operator()() const
    {
        std::cout << "calling operator()" << std::endl;
        return true;
    }

private:
    const std::string me_;
};
}

int main()
{
    const std::string a("a");

    //
    // construct an instance of TestMe and call its operator()
    //

    TestMe()();         // OK
    TestMe( "abc" )();  // OK
    TestMe tm( a );     // OK
    TestMe( a )();      // compile error: what's wrong with this?
    TestMe( { a } )();  // OK

    return 0;
}

Compile error:
../src/main.cpp: In function 'int main()':
../src/main.cpp:44:14: error: '{anonymous}::TestMe a()' redeclared as different kind of symbol
  TestMe( a )();   // compile error
              ^
../src/main.cpp:35:20: note: previous declaration 'const string a'
  const std::string a("a");

Answer: "Most vexing parse": https://www.fluentcpp.com/2018/01/30/most-vexing-parse/
TestMe( a )() is being treated as a declaration of a function named a that takes no arguments and returns a TestMe object.
Change your program slightly so that the line in question doesn't conflict with the name a:
#include <iostream>

namespace
{
class TestMe
{
public:
    TestMe() {}
    TestMe( const std::string& me ) : me_( me ) {}

    bool operator()() const
    {
        std::cout << "calling operator()" << std::endl;
        return true;
    }

private:
    const std::string me_;
};
}

int main()
{
    const std::string a("a");

    //
    // construct an instance of TestMe and call its operator()
    //

    TestMe()();         // OK
    TestMe( "abc" )();  // OK
    TestMe tm( a );     // OK
    std::cout << "before most vexing parse\n";
    TestMe( b )();      // compiles, but has no effect
    std::cout << "after most vexing parse\n";
    TestMe( { a } )();  // OK

    return 0;
}

You will see that the line TestMe( b )(); produces no output because it's just a declaration:
calling operator()
calling operator()
before most vexing parse
after most vexing parse
calling operator()


1d cnn for frequency domain data

Question: I am trying to use 1D CNN for frequency domain data, where each data point is a vector of length 300. How should I mention the input shape in Keras conv1D. How should my training data be reshaped?
Answer: you want to check the following link for 1D conv example.
https://statcompute.wordpress.com/2017/04/02/a-simple-convolutional-neural-network-for-the-binary-outcome/
The dataset used in his example:
https://mega.nz/#!wt5UEKaZ!AY12J0-kcRE0kMsuHskupkmKa0LUYVsFjlmdq1LCkus
Answer: I will use example from the computer vision.
Lets assume your input is an image of m X n X 10 and you use 4 1D conv filters then the output would be m X n X 4. 1D convolution is used to compress (bottleneck) across depthwise.
If you are using a vector of 300 with t 1D convolution filters. You would get 300 X t output but that would be of no use.
But if the input is of the format 1X1X300 with t (t<300) 1 D convolution filters then you would get 1X1Xt output which means you had compressed or bottlenecked the information from 300 dimensions to t dimensions. That looks of some use.

1d cnn for frequency domain data


Angular 2 Get width of a div

Question: I've looked at numerous posts but none quite do what I want it to do.
I have a table which goes outside the width of the page and for various reasons I need to get it's width.
I used:
@ViewChild('tableToMeasure') elementView: ElementRef;

And then put #tableToMeasure on the table. However this seems to error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined

Even though this works on and only on the parent div of the page.
Any ideas? I need to get it's width on both page load and page resize and change another divs width to be the same value.
Answer: @Component({
    selector: 'selector',
    template: `<button #tableToMeasure>Click me</button>`
})
export class FeatureComponent implements AfterViewInit {

    @ViewChild('tableToMeasure') elementView;

    constructor() {
    }

    ngAfterViewInit() {
        console.log(this.elementView.nativeElement);
    }
}

Comment: Hmm sorry I tried that but still getting the same error.
Answer: elementView won't be set before ngAfterViewInit was called.
If you have your code in ngOnInit or the constructor, you'll get this error.
Comment: Either inside `ngAfterViewInit` or anything that's executed later, for example an event handler for user actions (click, scroll, ...)
Comment: So I have to use it within ngAfterViewInit()?
Comment: So he should *use* `elementView` only after the viw initialized? So, inside `ngAfterViewInit`?
Comment: Hmm I tried it on ngAfterViewInit() but still getting same error
Comment: Hard to tell from the single line of code you posted. Please provide more information than I can have another look. Ideally a Plunker that allows to reproduce. (Plunker provides an Angular template to get you started easily)
Comment: Ah it works but you have to see if theres a value first as it fires off a first time without the element actually being ready. if ((this.elementView != null)) {}
Thanks for your help :)
Comment: Perhaps your `#tableToMeasure` is within an `*ngIf`, otherwise it will have a value when `ngAfterViewInit` is called.
Answer: I had the same problem. The solution I found was actually fairly easily; it returns undefined because in your HTML file there is nothing defined as 'tableToMeasure'.
Therefore you have to add #tableToMeasure to your HTML element.
Example code HTML file:

   Some content!</span

And in your TypeScript file:
@ViewChild('tableToMeasure')elementView: ElementRef;

Make sure to import ViewChild and ElementRef from @angular/core.
Good luck!

Angular 2 Get width of a div


Is the function $f(x)=x^2$ absolutely continuous on the real line?

Question: In Wiki (Lipschitz), it says:

A Lipschitz function $g : \mathbb{R}\to \mathbb{R}$ is absolutely continuous.

According to the definition of absolute continuity, I am confused about an simple example:
$$f(x) = x^2$$
This is not a Lipschitz function since we cannot find a bounded $L$ such that
$$|f(y) - f(x)| \leq L||y-x||_2$$
But is $f(x)$ absolutely continuous? (I am confused about if $x$ approaches $\infty$)
Comment: This wiki page says $x^2$ is not absolutely continuous on all of $\mathbb{R}$:  http://en.wikipedia.org/wiki/Absolute_continuity  I look forward to seeing an explanation for it.
Comment: I see. For a fixed $|y_k-x_k|$, i.e. $\delta$ is fixed and bounded, $|f(y_k) - f(x_k)|$ is not bounded as $y_k$ and $x_k$ $\rightarrow \infty$.
Answer: For function on the real line, one has the  following chain of inclusions (adapted from Wikipedia, which considers only a compact subset):

Differentiable with a bounded derivative $\subset$ Lipschitz continuous $\subset$ absolutely continuous $\subset$ uniformly continuous  $\subset$ continuous

None of the inclusions are difficult to prove: use, left to right,

Mean Value Theorem
Triangle inequality
Definition of absolute continuity specialized to one interval
Definition of uniform continuity

All inclusions are strict, by the way.
The function $f(x)=x^2$ is not uniformly continuous on $\mathbb{R}$, and therefore is not absolutely continuous.


Testing a proportion in an online setting

Question: I work in an online security setting. My goal is to detect if the number of locked accounts per time unit is stable or not. I've tried several approaches, detailed below, but I am not satisfied yet. One of the challenges is to deal with fluctuating amounts of traffic.
If total traffic would be constant over time, then a Poisson distribution could help out. The locked accounts can be seen as arrivals. Since traffic fluctuates heavily over a day, it is difficult to test per minute or hour. Testing per day could be an option. Holiday periods and weekends could show too low observed numbers, but I am mostly interested in increases.
A change detection algorithm like ADWIN could also help out. If applied on day totals, the assumption would be that the per day the number locked accounts should be stable. Days with lower traffic could be a problem like weekends or holidays; or rather the day after the weekend that show an increase. A proportion seems more to the point.
To keep track of the sample size, a chi-square test could help out. One could test proportions independent of sample size as long as cells are filled with more than 5 observations. The observations of the last hour could easily be compared to the observations of the last week since the chi-square test takes the proportions into account. Some bonferroni stuff should be in place.
I've tested a neural network for baseline traffic prediction, but this method seems unstable. It basically uses a predictor, the error variance and an error outlier rule. This should be state of art. The reason why it not so stable is that the traffic varies wildly per minute, increases and decreases of 4 times seems normal. Could averaging over hours instead of minutes make this model work better?
Would anyone have further suggestions?
Comment: Sure, see: http://pastebin.com/yguE6J7K The second column is the frequency (now of total request, not locks), the last column the minute. The first column is an id 1,2,3, the other columns refer to day of week or hours. Notice a lot of 0ś at night. I get the fealing that size of the fluctuation compared to the size of the frequencies is to high.
Comment: I think statistical quality control tools, which are aimed at monitoring a manufacturing process and checking whether the process output is within the specified specification or stochastic bounds, may be of help, so I added the tag.
Comment: Would you mind posting a small part of data, say data per minute for 23 hours?
Answer: Having a look at the data, only the freq variable (second column). Since it is a count, analyzing its square root.  The autocorrelation function decays almost linearly to about zero at about lag 400, but that must be an artefact of all the nightly zeros. So, analysing only the block of data up to the first block of zeros, freq[1:934], the autocorrelation function is more sensible, nonzero only at the first  lag, with value there about 0.3.  Plotting that part of the series, it is strange, almost constant with values about 20,  with a few values much larger than that, coming in bursts.  So describing the series with an autocorrelation function is not a very good description, maybe some kind of hidden Markov process would give a better model, with one almost constant regime, and another bursting regime, and then the zero-regime. You could try that!
<code>EDIT
</code>
Answering question in comments: count data are often poisson-distributed, at least, that is the simplest model for counts. And, the square root is the variance-stabilizing transformation for the Poisson distribution family. That is, while we have that, for $X\sim \text{Po}(\lambda)$, that $\text{Var}(X)=\lambda$, we have that $\text{Var}(\sqrt{X})\approx \frac14$, approximately independent of $\lambda$. And, many statistical methods, like least squares and most time-series models like ARIMA, works best for data which have a variance independent of its mean.
Comment: Kjetil, thanks for the autocorrelation verification. Your observations support my own; that there are actually three regimes going on, of which the bursts are the most unreliable. This is also why the neural net approach did not work out (Taken from Ellis' Real Time analytics). Analysing the square root of counts is new to me, could you elaborate on that?


Yahoo OAuth question

Question: I'm keep getting oauth_problem=consumer_key_unknown error when trying oauth https://api.login.yahoo.com/oauth/v2/get_request_token
I'm pretty sure my consumer key is correct because it works locally (Runs via 127.0.0.1). Just keep giving me oauth_problem=consumer_key_unknown when I try it on my server. Any ideas?
Answer: is it sending the right domain in requireSession (4th argument should be something like 'http://mydomain.com/' which should match exactly what you used to sign up...
Comment: Are you referring to oauth_callback? I'm just following their guide here: http://developer.yahoo.com/oauth/guide/oauth-auth-flow.html#oauth-requesttoken. Currently at step 2 which is where I encounter the error. The callback is within the same domain i sign up with.

Yahoo OAuth question


How can I accomplish this using Views?

Question: I'm using Drupal 7.28 and Views 7.x-3.7.
I've created a vocabulary called Products and listed terms under this including Living, Dining, Storage, Office, Outdoor.
I've also created a content type called Products with an auto term reference for users adding content to select one of the terms.
What I want to do is create a view that will automatically create a page for each of the terms, so in the menu it will have for example Living, Dining, Storage, Office, Outdoor etc. I don't want to have to create a new view each time a term is added.
Then, if a term has been added but there is no content that has selected a term the page will just say 'No products' (which i know this bit can be done by setting a No Results behaviour.)
Thanks very much for reading.
Answer: For anyone else looking for help with this in the future, here's how I did it:
I used the default pages that are generated for each term - I didnt realse that all terms generate a page that displays all of the content associated with them.
I then enabled and used the default Taxonomy view to edit the output of the term pages.
I also used the Taxonomy Menu module to create a menu of each taxonomy,
Answer: i am not sure whether this is exactly what you are looking for or not, but i would do it this way..
Override the taxonomy view (or clone it) from the views list. (this will override the view for all the taxonomy terms in your website.
After this install and enable the taxonomy Menu module. With this you can create a menu of the taxonomy terms for the specific content type.
For Showing the no items in the display add a "No results behavior" - under this select "Global: Unfiltered text "- click on Apply button- when the form appears put this " 'No products'" text in the text area and click on the apply button. You can also add markup for this text.
 save all the settings and check it. hope this helps
Comment: Perfect, exactly what I was looking for. And there was me thinking no one would understand my question, thanks :)
Comment: Actually I had same needs and solved it in this way with some extra features

How can I accomplish this using Views?


Projection of a $L^2$ function over a set of constant functions

Question: I don't know how to solve the following exercise:

Let $X$ be the subspace of $L^{2}(0,1)$ of a.e. constant functions. What is the projection over $X$ of a function $u \in L^2(0,1)$?

First of all, $X$ is convex, and this is trivial to prove. It's also closed. So, by the characterization of projections onto closed and convex subspace I have to find a $v \in X$ s.t.
(*) $\langle u-v,f \rangle=0$ for every $f \in X$, i.e. $\int_0^1 (u(x)-v(x))f(x)dx=0$, but $u$ and $f$ are constants, so I can't see any way to set that integral equals to $0$.
Maybe I could start by thinking about $\Vert u - v \Vert_{L^2}^2=\int_0^1|u(x)-v(x)|^2dx $ and how to minimize this integral with $v \in X$. The best I can do, I guess, is to set $v(x)=v=\max \{|u(x)|: x \in [0,1] \}$, but I still can't understand how to find a $u$ such that (*) holds.
EDIT:
I need also to prove that $X$ is closed.To this aim, I take a sequence $\{ f_n \}$ in $X$ s.t. $f_n \rightarrow^{L^2} f$. I want to show that $f$ is a.e. constant. By Riesz-Fisher there exists a subsequence $\{f_{n_k} \} \in X$ such that $f_{n_k} \rightarrow f$ a.e. in $X$. How can I conclude?
Comment: (*) is the characterization of a projection if $X$ is a linear subspace. (Which here luckily is the case.)
Answer: The space $X$ is spanned by the constant function $1$, whose norm is $1$. Therefore, the orthogonal projection of $f$ on $X$ is $\langle u,1\rangle1$. That is, it's the constant function $\int_0^1u$.
Comment: Okay, now that makes sense. Actually, I didn't prove it's closed, and now I see that it's not so easy. I edited my original post
Comment: In any Banach space, a subspace spanned by a single vector (or, more generally, any finite-dimensional subspace) is closed.
Comment: Yes, I know this. But I want to show it by using the classical definition of closed set.
Comment: Use the fact that any convergent sequence of elements of $\mathbb{R}v$ is of the form $(\lambda_nv)_{n\in\mathbb N}$, where each $\lambda_n$ is a real number. But then the sequence $(\lambda_n)_{n\in\mathbb N}$ converges to some $\lambda\in\mathbb R$ and therefore $\lim_{n\to\infty}\lambda_nv=\lambda v\in\mathbb{R}v$.
Comment: With $\mathbb{R}v$ you mean real multiples of a constant $v$, right? So you say: assume that $\{ f_n \} \in X$ converges. By definitions, each $f_n$ is of the form $f_n=\lambda_n v$, where $v$ is a constant. But then, since the sequence converges, $\lambda_n \rightarrow \lambda$, and then $f_n=\lambda_n v \rightarrow \lambda v \in \mathbb{R}$, so $X$ is closed
Comment: Yes, that's it.
Comment: Thanks for your help!


É aceitável usar tags , , ,  dentro de links/âncoras ()?

Question: É aceitável em questão SEO e semântica usar tags como
,
,
 e
 dentro de ?
Notei que para tornar itens em uma página as pessoas costumam usar uma estrutura semelhante a esta:

Produto

R$ 1000

Eu sei que a tag  é inline e necessita do display: block para que funcione, mas a questão realmente é sobre SEO e semântica.
Comment: Apenas para incrementar as respostas, deixarei [essa resposta no webmasters](http://webmasters.stackexchange.com/a/20469).
Comment: No HTML5  a tag `` pode ser inseridas parágrafos inteiros, listas, tabelas,e assim por diante, até mesmo seções inteiras, contanto que não há conteúdo interativo dentro do mesmo, acredito que só iria perder a semântica se houvesse algo do `` que altera-se o seu comportamento natural.
Comment: Guilherme, sei que a sua pergunta é quanto a CEO, mas no HTML5 o conceito de `inline` x `block` sofreu um amadurecimento, agora os elementos estão organizados por categorias, sendo que um elemento pode receber uma classificação diferente dependendo de algumas condições... para entender melhor, leia: [Content categories](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories)... no caso do [](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) ele tanto pode ser um `conteúdo de texto` quanto um `conteúdo de fluxo`.
Comment: @TobyMosque só um detalhe CEO != SEO.
Comment: ops, digitei CEO por engano, era SEO mesmo.
Answer:
É aceitável usar tags
,
,
,
 dentro de links/âncoras ()?

Sim. Isto é um recurso do HTML5. Outras versões não permitiam este uso.
Já o contrário (colocar  dentro de
,
, etc.) é o mais utilizado até hoje. Há vários exemplos. um dos mais notáveis, a meu ver, é o de documentações do GitHub. Passando o mouse por cima de um título, aparece uma imagem de uma âncora contendo o link completo até aquela âncora.
Comment: Tinha me esquecido de marcar como correta :) Obrigado!
Comment: Sim é o mais usado por ecommerces como o Ebay, no entanto eu digo isto de usar dentro do `` na intenção de tornar tudo clicável. Se bem que acho que vou passar a usar clicável apenas o título e a foto.
Comment: Aí vai do seu objetivo. Eu manteria a abordagem clássica, que funciona pra tudo.
Comment: Não me expressei direito, acho que a abordagem me parece a classica, o que pretendo é fazer algo como (resumido) ``... Seria isto o classico não?
Comment: Isso mesmo. É o que usaria.
Answer: Na especificação da tag  em Permitted elements do HTML5 os seguintes elementos são suportados e por serem suportados são semanticamente corretos se não alterarem o comportamento original do :
>  , , <address>,
,
> , <audio>, ,<bdo>, <bdi>,
,
, <button>,
> <canvas>, , , <command>, <data>, <datalist>, ,
> , <dfn>,
,
, , <embed>, <fieldset>,
,
> , <form>,
,
,
,
,
,
, ,
> <hgroup>,
, , , , <input>, , , <keygen>,
> , , <map>, , <math>, <menu>, <meter>, ,
> , <object>,
, <output>,
,
, <progress>, <q>,
> <ruby>, <s>, <samp>,


The lower end of my vocal range tails off really suddenly, is this normal?

Question: I can sing C3 and B2 very easily, and A2 quite clearly and strongly. But I can not really hit G2 at all, just barely in a really horrible way. So within a single tone, my lower range dies completely.
Is that normal? By contrast my high range degrades over a few notes from "that's OK" to "it's in tune but it's horrible".
Comment: Is G2 the lowest note you can sing comfortably?  Also, could we call A2 the bottom of your range instead of G2?  //  My impression is this is common.
Comment: I would say my range is A2, though if I were singing bass in a choir I'd try a G2 since it probably wouldn't sound too bad, just quiet.
Comment: I'm somewhat similar but about a tone lower. I can usually manage a decent G, but the F is usually absent, or extremely weak. It varies a bit -- it's usually a bit lower in the morning, or if I'm sick (I've managed an Eb on rare occasions), but there have also been times I've struggled with A. But yes, usually my voice goes from there to gone over the course of about a whole tone.
Answer: Yes, that's pretty normal.  Lower range limits tend to be pretty hard and not impressible much by warmup or similar.  However, they may vary with the time of day and other external circumstances (exerting one's voice over an evening tends to take quite more from the top than it may add at the bottom, but the morning after may show non-permanent extensions on both ends of the range).
Answer: This is entirely normal and makes sense when you look at how the voice works.
The vocal folds, commonly referred to as vocal cords vibrate to create the sound. Similar to a guitar string, the more tension on them the higher the pitch. The muscles primarily involved in this are the cricothyroid (CT) and thyroarytenoid (TA) muscles. As these muscles contract the pitch increases.
To obtain the lowest note you can sing you relax both of these muscles completely. Since they are relaxed completely the anatomy of your throat determines the lowest pitch.
At the other end, to produce your highest note you contract your CT and TA muscles as much as you can. The conditioning of the muscles and the flexibility of your vocal folds is what determines your highest pitch. These are things that can vary a lot more than the lower end so the high end is going to be a more gradual change.

Note: I found one paper (.pdf) from 1972 that makes the assertion that contraction of the sternohyoid muscles causes the pitch to lower, but I can't find any other source to support this hypothesis.
Comment: This makes sense from a physics perspective, but there's conversely quite a lot of effort achieving your lowest note (for me anyway) so I wondered if "relaxing the muscles completely" is actually something one needs to train to do. This could be a whole other question though.
Answer: Yes, it's normal.  Although it's often possible to squeeze out an extra high note or two, the lower cut-off is generally non-negotiable.   Practice scales and other exercises, you might find a little extra low range.  But don't be disappointed if you don't.


Transaction rollback in Spring MVC controller

Question: I have a Spring MVC controller annotated with @Transaction, and under certain inputs I need to rollback the transaction.
As I understand, the proper way to trigger a rollback is to throw an exception from the controller.
But if I throw an exception from the controller, I won't get a chance to return a ModelAndView object from the controller.
How can I trigger a rollback in the controller, while still providing a ModelAndView to be rendered?
Answer: Exceptions are the appropriate route to follow. Spring can map exceptions to views as well. This is probably what you want to do.
Comment: I was afraid this was the answer.  Since I want my ModelAndView construction logic to live in the controller, I think I need to define a custom exception class that can store the ModelAndView, and a custom `HandlerExceptionResolver` to render it.  Seems like something that belongs in Spring itself.
Comment: Turns out there is something like that in Spring itself: [ModelAndViewDefiningException](http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/ModelAndViewDefiningException.html)
Answer: First, I don't think that using @Transaction on controller methods is a good thing.  It's better to keep transactional logic in a 'service tier' and use the @Transaction annotation there.
But if you still want to use @Transaction on the controller, take a look at org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
Comment: Welcome to StackOverflow! Sometimes controllers need to make multiple calls atomically—for instance, `User user = userService.getByUsername(...)`; `user.updateEmailAddr(...)`; `user.updateTelephone(...)`; `user.subscribeToMailingList(...)`. It seems silly to have to make a service method like `UserService.updateEmailAddrAndTelephoneAndSubscribeToMailingListByUsername` just so the controller doesn't have to be transactional.
Comment: I don't think it's silly at all.  If you have to write the code anyway why not encapsulate it in the service instead of in the controller?  Another benefit is then you can easily test it in your service test instead of worrying about the controller.


samba server configuration

Question: i m trying to configure samba server in rhel5.when i try to share some dir of my linux system on which i m configuring samba and change workgroup of one the windows clients then that windows client shows samba server icon bt on clicking that icon when i enter username and password for the registered user(means the username and password for that windows client) it does not connect to the shared dir.i changed my samba.conf file parameters several times bt even then the prob is still unsolved.what could be the other reasons for all such happenings or what shud i do with my samba.conf file.kindly help me out.
Comment: Are you trying to connect using Acitve Directory credentials?
Comment: Did you type this on your circa 1999 Nokia phone??  More people would help if your question wasn't so difficult to parse.
Answer: If it's popping up with an auth request, try
smbpasswd -a <username>

set the password to the same as on the windows side
Answer: Have you run testparm on your smb.conf to test for internal consistency?
Next, what sort of authentication are you using?
Try stripping out all the comments and whitespace and posting your smb.conf file.
Answer: There's several configuration options that effect this.
Map To Guest = [Never, Bad Password, Bad User, Bad Uid]
The way to simulate most end-user windows machine sharing behavior is to use "Bad Password".  This means that whenever you fail to authenticate, it just uses the guest account.  Best for read-only access.
Now, under the particular share you can use the public option.
[my_share]
path = /path/to/dir
public = yes
writable = no

The combination of the Map to Guest = Bad Password configuration option, and the public = yes configuration option should allow anybody access your share with read-only privileges.  Be careful because smb will actually setuid() to the user that was authenticated (in this case, nobody), so all the files have to have the correct unix permissions for nobody to read them.
If you actually want to authenticate users, you'll have to use the smbpasswd tool.  Samba maintains its own shadow-hash file for users.  If you actually want to use user authentication then you'll have to use smbpasswd -a <username>, like greeblesnort suggests.  The username is a username of a linux user.  You can maintain different passwords for Samba authentication and for the rest of the system.  Again, you'll have to doublecheck the linux file permissions to make sure that the user you want to grant access to can read/write in the directories you're sharing.

samba server configuration


A ring that is left Noetherian but not right noetherian

Question: I am studying Chapter 8 of Hungerford for my qualifying exam.
In Chapter 8.1., he gives an exercise concerning the ring that is right Noetherian (resp. Artinian) but not left Noetherian (resp. Artinian).

The ring of all $2\times 2$ matrices $\begin{pmatrix}a&b\\0&c\end{pmatrix}$ such that $a$ is an integer and $b,c$ are rational is right Noetherian but not left Noetherian.

Basically, this question has been answered several times: for example this post and this one.
Showing that the above ring, say $R$, is not left Noetherian is quite straightforward; we simply construct an infinitely ascending chain of left ideals in $R$.
Almost every sources (including this site) argue that $R$ is right Noetherian by showing that a right ideal $I$ is finitely generated. In particular, they separate cases where (i) $I$ contains an element of the form $\begin{pmatrix}a&b\\0&c\end{pmatrix}$ with $a\neq 0$, and (ii) $I$ consists of elements of the form $\begin{pmatrix}0&b\\0&c\end{pmatrix}$. But I don't see why the following (simpler) argument can be applied:

A ring $R$ is a right Noetherian if and only if for some ideal $I$ of $R$, both $I$ and $R/I$ are Noetherian. Define a map $\phi:R\rightarrow \mathbb{Z}\times\mathbb{Q}$ by $\begin{pmatrix}a&b\\ 0&c\end{pmatrix}\mapsto (a,c)$. Then $\phi$ is a surjective ring homomorphism with kernel $I=\left\{\begin{pmatrix}0&b\\0&0\end{pmatrix}:b\in\mathbb{Q}\right\}$. $R/I\cong\mathbb{Z}\times\mathbb{Q}$ is Noetherian since both $\mathbb{Z}$ and $\mathbb{Q}$ are. The only submodule contained in $I$ is $0$ and $I$ itself, since if $J\subset I$ is a nontrivial submodule of $I$, then for some nonzero $\begin{pmatrix}0&b\\0&0\end{pmatrix}\in J$ we have $\begin{pmatrix}0&1\\0&0\end{pmatrix}=\begin{pmatrix}0&b\\0&0\end{pmatrix}\begin{pmatrix}0&0\\0&1/b\end{pmatrix}\in J$. It follows that both $R/I$ and $I$ are Noetherian.

Any help is appreciated. Thanks!
Answer: I did precisely that in one of the solutions you linked, although I chose different submodules to prove it with, ones which link with the classification of right ideals of the ring.
The thing that deserves more explanation in what you said is "$\mathbb Z\times \mathbb Q$ is Noetherian."  Remember, you have to show that it's Noetherian as a right $R$ module.  It's tempting to just say "the two things are Noetherian rings so the product is a Noetherian ring" and that is true, but a third party could legitimately question why this Noetherian ring should be a Noetherian right module over $R$.
Comment: Fair point. Thanks for the explanation!


Disable gpu accelerated rendering

Question: The are some rendering issues with my website under some browsers (eg Chrome on Windows & Mac, Safari on Mac) related to gpu acceleration and I was wondering if there is a way to disable it for my website. Something like a <meta> tag I could include in my pages.
Answer: No. There is not.
You should explain what the rendering issues are, and see if we can help you work around them.

Disable gpu accelerated rendering


A fair ratio for sorting

Question: Say I own a business and people submit products to be sold on my shop. Before they can be displayed on my store, the items will need to undergo review. Over time I accumulated data which consists of each seller's total items, approved items and rejected items.
I'd like to give some reward to those that have been submitting quality items so I thought of using an approval ratio and anyone beyond a certain percentage (eg, 70%) can receive the reward. This is the ratio
<code>approval ratio = approved items / total items
</code>
Is this fair since someone who has sent only one item and it's approved will easily get 100% rating over someone who has 50 approved out of 100 items? Business-wise, the latter can give more potential sales. On the other hand, more rejected items a seller has means more loss for me due to the time spent reviewing them.
What would be a good measurement to use for this case?
Answer: You could try to achieve this using (log) odds (ratio) as opposed to proportions.
For example: a certain provider has 70 approved items and 30 non-approved items. The proportion of approved items is 0.7. The odds are $\frac{70}{30}=2.33$.
This does not completely solve the problem since someone who has 7 approved items and 3 non-approved items still has $\frac{7}{3}=2.33$.
To correct this you could multiply the whole thing by the total number of items:
$\frac{70}{30} \cdot 100=233.33$, while $\frac{7}{3} \cdot 10=23.33$.
Also, odds are in $(0,\infty)$, if you want to create a more symmetric range in $(-\infty,\infty)$ you can take the log of the odds:
$\log(\frac{70}{30} \cdot 100)=5.45$, while $\log(\frac{7}{3} \cdot 10)=3.14$

A fair ratio for sorting


which software has sorting capabilities to help mastering the fretboard?

Question: I am looking for software that sorts music elements such a note, an interval, a chord or an arpeggio randomly in a defined period of time, until I stop of the sequence. The idea is to become fluent finding these elements fast, without utilizing visual memory extensively, but knowing exactly where the notes are. I know scales fingerings and play them, but I can't percept which notes I am playing at a given time exactly because is too fast.
Here I try just enforce the knowlegde of the notes on the fretboard. In the software described I don't want to do nothing virtually expect the "randomness" part, evertyhing it would be done by paying the instrument. The idea is just take advantage of the automatic randomness of the computer to develop my fretboard skills.
Comment: Guitar Pro is the only software I use and it has standard music notation which can help you figure out what fret is what note. You can also program it to do everything you're asking. Really though, I don't think you need special software for this. Memorize a few frets at a time, 5, 7 and 12 are a good place to start. The shapes (visual memory) on the guitar are the intervals and will help you memorize chords/arpeggios, etc. Just keep practicing and dedicate your practice time to some of these ideas.
Answer: I don't think you should use a software. Learn all the natural tones on the low E string (E / F / G / A / B / C / D ). Play them, slowly, saying their names out loud, ascending and descending. Once you know them, you can learn the flats and sharps.
Then either :
- do the same on the A string, while keeping on practicing the E string, then the G etc...
- Or you use octave visual shape to know every note on the neck quite rapidly - for example, if you need to know what note is the 10 fret of the D string, visualise an octave shape (there's many of them, the most commonly known is the one you can find in a powerchord) : 8 on the low e is the octave below 10 on the D string, so it's C.


Python packages for working with Gaussian mixture models (GMMs)

Question: There seem to be several options available for working with Gaussian Mixture Models (GMMs) in Python. At first glance there are at least:

PyMix: Tools for mixture modeling
PyEM [dead link], which is part of the Scipy toolbox and seems to focus on GMMs Update: Now known as sklearn.mixture
.
PyPR: pattern recognition and related tools including GMMs

... and perhaps others. They all seem to provide the most basic needs for GMMs, including creating and sampling, parameter estimation, clustering, etc.
What's the difference between them, and how should one go about determining which is best suited for a particular need?
Ref: Topical software on SciPy.org.
Comment: Scikit-learn is a popular machine learning library that also has some GMM support. I am not sure it fits your needs but it has the benefit of having other learning algorithms and framework (e.g. cross-validation, model composition).
Comment: You could try profiling a really simple version of image compression using GMMs. Given an image use a GMM to assign the pixels different probabilities and then recreate the image by using the probabilities as indices for the particular Gaussian that a particular pixel was most likely to have come from.
Comment: @cpcloud -- Do you mean: set up a simplified experiment to execute in each of these packages, as a point of comparison? Well, okay, but that's no small amount of effort. I am hoping for some input from people who have used these packages.
Comment: PyPR and PyEM are only available for Python 2, and no longer seem to be under active development.  PyMix looks like the best choice.
Answer: I do not know how to determine in general which one is best, but if you know your application setting well enough, you can simulate data and try the packages on these simulation. Success metrics could be the time that the estimation take and the quality of recovery of your simulated ground truth.


Search by product with punctuation

Question: I'm starting to configure frontend search for user search, and I can't find a product if it has a puctuation sign. For example, a product called
The world today: a new adventure
In search box, if I enter world today:, the search doesn't find the product.
Anybody could help me with that?
Comment: 'world:' isn't in the title... so why would you expect it to find it?
Comment: Sorry, I have corrected now. In fact, it's "world today:".
Comment: and what happens if you search for 'world today' ?  I don't think I've ever used punctuation in a search, anywhere - out of curiousity why are you expecting or planing on users using punctuation?
Comment: It's a client requirement. The products are books, and there is many book titles that have colons, commas etc. He says that users frequently search titles including that punctuations.
Answer: Drupal Core Search is designed to deal with many punctuations, but not all. Take a look at either of these modules:
Punctuation Preprocessor:

This module implements a punctuation pre-processor that provides
  special handling for punctuation characters when they are encountered
  within word strings during searching and indexing.

Fuzzy Search:

This module provides drupal sites with a fuzzy search engine to allow
  for broader keyword matches including partial or misspelled keywords.

or any of the other core search alternatives - they may pick up the punctuation better.

Search by product with punctuation


When both halves of an OR regex group match, is it defined which will be chosen?

Question: I've run the following code:
public static void main(String[] args) {
    Pattern pattern = Pattern.compile("(asd|asdf).*");
    Pattern pattern2 = Pattern.compile("(asdf|asd).*");
    Matcher m = pattern.matcher("asdf");
    Matcher m2 = pattern2.matcher("asdf");
    if (m.matches()) {
        System.out.println(m.group(1));
    }
    if (m2.matches()) {
        System.out.println(m2.group(1));
    }
}

And I get the following output:
asd
asdf
It seems as though the left hand side of the OR group is chosen in cases when both match. However, I haven't been able to find this behaviour documented. Does anyone know if the behaviour is defined?
Comment: Do you have details of where that's defined? Thanks
Comment: I cannot link to any source, but since regex tries to match as less as possible, I think this observation is applicable. If you say "first" instead "left", this makes even more sense.
Answer: In non-POSIX regex flavors (as in Java, as The Pattern engine performs traditional NFA-based matching with ordered alternation as occurs in Perl 5), the first alternative is matched. In POSIX, the longest alternative is matched.
See what Perl help says about alternation:

To match dog or cat, we form the regexp dog|cat. As before, Perl will try to match the regexp at the earliest possible point in the string. At each character position, Perl will first try to match the first alternative, dog. If dog doesn't match, Perl will then try the next alternative, cat. If cat doesn't match either, then the match fails and Perl moves to the next position in the string.

See the Alternation with The Vertical Bar or Pipe Symbol at regular-expressions.info that describes NFA-compliant alternation behavior:

The order of the alternatives matters. Suppose you want to use a regex to match a list of function names in a programming language: Get, GetValue, Set or SetValue. The obvious solution is Get|GetValue|Set|SetValue.
The regex engine starts at the first token in the regex, G, and at the first character in the string, S. The match fails. However, the regex engine studied the entire regular expression before starting. So it knows that this regular expression uses alternation, and that the entire regex has not failed yet. So it continues with the second option, being the second G in the regex. The match fails again. The next token is the first S in the regex. The match succeeds, and the engine continues with the next character in the string, as well as the next token in the regex. The next token in the regex is the e after the S that just successfully matched. e matches e. The next token, t matches t.
At this point, the third option in the alternation has been successfully matched. Because the regex engine is eager, it considers the entire alternation to have been successfully matched as soon as one of the options has. In this example, there are no other tokens in the regex outside the alternation, so the entire regex has successfully matched Set in SetValue.

And then:

But the POSIX standard does mandate that the longest match be returned, even when a regex-directed engine is used. Such an engine cannot be eager. It has to continue trying all alternatives even after a match is found, in order to find the longest one.

However, the order of alternatives may be irrelevant if the context on either side is strictly defined. If you use anchors, ^(asd|asdf)$, to match the full string, you will only get the one that corresponds to the right alternative.
Comment: Not refuting this claim, but do you have a source for this?
Comment: @ohaal It's [here](http://www.regular-expressions.info/alternation.html). Scroll to **POSIX Requires The Longest Match**
Comment: .* matches any character (except newline)

    Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed
Comment: @Tushar: I was adding that to the answer.
Comment: Thanks that's a useful link. It would be reassuring to see something in java's documentation saying that this is how *their* implementation behaves though!
Comment: @user1675642: Java [regex documentation says](https://docs.oracle.com/javase/tutorial/essential/regex/intro.html) that its regex syntax is a version of a Perl regex syntax. So, it is NFA, and follows the non-POSIX rules when it comes to alternation handling.
Comment: I believe I furnished enough documentation proof of why and how regex alternation works in Java. Even if it is not stated directly that Java uses the first alternative if matched and does not check the following ones it still provides reference to those sources.


Warning: file_put_contents(temporary://): failed to open stream

Question: I get this message from Drupal:

Warning: file_put_contents(temporary://file8vyLsO): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (line 1900 of /home/donatelo/public_html/thenameofthesite.com/includes/file.inc).
The file could not be created.

I don't know what I did to cause this, can anyone help me?
Answer: Make sure your temporary folder exists and is writeable.
See the file system settings at:
admin/config/media/file-system
Comment: Thanks, already did it. Actually, I erased my old path, from WAMP, before site was uploaded, and it works ok now. Thanks anyway.
Answer: The error happens, because your temporary directory is not writable by your web server user.
Check for details in Status report at: /admin/reports/status
If you're using drush, this may fix it:
drush vset file_temporary_path /tmp


Automação em HTML [Python]

Question: Bom dia, boa tarde e boa noite amigos Devs.
Só deixando claro que sou iniciante --
Tenho duas dúvidas sobre automação dentro de Python.
1- Eu quero fazer um login automático em determinado site, com isso preciso do login e senha do usuário:
<code># Login (CPF)
pyautogui.hotkey('ctrl', 'a')
pyautogui.press('del')
print('Digite seu login (RA ou CPF): ')
login_AVA = input()
pyautogui.press('tab')

# Senha
pyautogui.hotkey('ctrl', 'a')
pyautogui.press('del')
print('Digite sua senha: ')
senha_AVA = input()
pyautogui.press('enter')
</code>
No caso, o script para de executar, justamente quando peço a interação do usuário, e em Python não há nenhuma janela (como em outras linguagens) que aparecem as entradas/saídas ?
2- Eu preciso copiar dados de um determinado site, e guardar essas informações para usar em outra página, qual o melhor jeito de fazer isso ?
Exemplificando: No caso da segunda questão, o meu projeto é fazer uma automação para um site de perguntas e respostas da minha faculdade, como base vou usar o Brainly (https://brainly.com.br/) como "Banco de dados".
A idéia é: Copiar a questão dentro do site da faculdade e jogar no Brainly (já consegui fazer isso), e com isso dentro do brainly conseguir a resposta certa, e jogar dentro do ambiente da faculdade marcando a opção correta, e seguindo para outra questão, e assim sucessivamente
Obrigado pela atenção !!
Answer: Respondendo as perguntas:

1- No caso, o script para de executar, justamente quando peço a
  interação do usuário, e em Python não há nenhuma janela (como em
  outras linguagens) que aparecem as entradas/saídas ?

R- Não há.

2- Eu preciso copiar dados de um determinado site, e guardar essas
  informações para usar em outra página, qual o melhor jeito de fazer
  isso ?

R- O melhor jeito é fazer um web scraping, recomendo estudar algumas bibliotecas como a BeautifulSoup para isso
Você pode solicitar a informação antes de interagir com a página, assim:
<code>login_AVA = input('Digite seu login (RA ou CPF): ')
senha_AVA = input('Digite sua senha: ')

pyautogui.hotkey('ctrl', 'a')
pyautogui.press('del')
pyautogui.typewrite(login_AVA)
pyautogui.press('tab')

pyautogui.hotkey('ctrl', 'a')
pyautogui.press('del')
pyautogui.typewrite(senha_AVA)
</code>
Comment: Obrigado Guilherme, mas no caso quando eu executo a aplicação com os novos inputs, o meu VSCode fica travado, e não executa nem o (webbrowser.open), a minha pergunta é: como/onde o usuário vai me informar as entradas? Preciso do Tkinter, ou tem algum outro jeito ?
Comment: Não precisa do tkinter, precisa apenas das duas primeiras linhas do código na minha resposta. O input é responsável por gravar a entrada digitada na variável. Quando você executa o script, vai solicitar no terminal as entradas e só vai rodar o resto do código depois de digitá-las.
Comment: Muito obrigado Guilherme, pelo VSCode realmente ele não abre o terminal, consegui obter as entradas pelo Python IDLE

Automação em HTML [Python]


How to set $base_url when running a site in a subdomain?

Question: I just uploaded a site to a remote server. The url is a subdomain: mySubdomain.myDomain.com.
The site just shows the front page. If I tried to navigate to other page (ex.: el-graner) I get this message:
<code>Not Found

The requested URL /ca/el-graner was not found on this server.
</code>
I set the $base_url variable in sites/default/settings.php in this way, then clear all caches...but not working at all.
<code>$base_url = 'http://mySubdomain.myDomain.com';
</code>
What are the settings I need to do when running a drupal site in a subdomain?
Comment: When you hover over the link (or view source), is it "/ca/el-graner" or "/el-graner"?
Answer: Have you tried clearing cache after uploading to remote server?
If it didn't help, you could try installing Global Redirect module. It may resolve your problem, or at least can help reduce the possibility of problems created by path aliases.
Answer: In the .htaccess file, you should also uncomment the following line. (Remove the # character.)
<code># RewriteBase /
</code>
Comment: Needing to set `RewriteBase` is not strictly true for subdomains.  It really depends on how you have Apache configured to serve up the subdomain.  I have never needed it when the subdomain in a normal `VirtualHost` situation with `ServerName` and `DocumentRoot` explicitly defined.
Comment: I was an typo error in the .htaccess file. Fixed.