text:
Q: Filter multi-indexed dataframe based on lower dimensional values I would like to filter a multi-indexed DataFrame based on another DataFrame with a lower dimensional index, like in the following example:
import io
import pandas as pd

df1 = io.StringIO('''\
ID1        ID2       ID3    Value
1          1001      1        1
1          1001      2        2
1          1002      1        9
2          1001      1        3
2          1002      2        4
''')

df2 = io.StringIO('''\
ID1        ID2      Value
1          1001    2
2          1002    3
''')

expected_result = io.StringIO('''\
ID1        ID2       ID3    Value
1          1001      1        1
1          1001      2        2
2          1002      2        4
''')

df1 = pd.read_table(df1, sep='\s+').set_index(['ID1', 'ID2', 'ID3'])
df2 = pd.read_table(df2, sep='\s+').set_index(['ID1', 'ID2'])
expected_result = (pd.read_table(expected_result, sep='\s+')
                   .set_index(['ID1', 'ID2', 'ID3']))

assert all(df1.loc[d2.index] == expected_result) # won't work

If both dataframes have the same dimension one can simply:
df1.loc[df2.index]

which is equivalent to a list of same dimension indices, e.g.
df1.loc[(1, 1001, 1), (1, 1001, 2)]

It is also possible to select single elements based on a lower dimensional index like so:
d1.loc[(1, 1001)]

But how can I filter based on a list (or other index) with lower dimension?

A: It seems a bit tricky to get your desired result. As with pandas 0.19.2, the multi index label locater loc seems to be buggy when supplying an iterable of exactly defined rows:
# this should give the correct result
desired_rows = ((1, 1001, 1), (1, 1001, 2), (2, 1002, 2))

# messes up with varying levels
print(df1.loc[desired_rows, :])

                    Value
ID1     ID2     ID3
1       1001    2   2

# when reducing the index to the first two same levels, it works
print(df1.loc[desired_rows[:2], :])

                    Value
ID1     ID2     ID3
1       1001    1   1
2                   2

Therefore, we can't rely on loc for your given example. In contrast, the multiindex index locator iloc still works as expected. However, it requires you to get the corresponding index locations which is shown below:
df2_indices = set(df2.index.get_values())
df2_levels = len(df2.index.levels)

indices = [idx for idx, index in enumerate(df1.index)
           if index[:df2_levels] in df2_indices]

print(df1.iloc[indices, :])

                    Value
ID1     ID2     ID3
1       1001    1   1
2                   2
2       1002    2   4

Update 15.07.2017
An easier solution is to simply convert the desired_rows tuples to a list because the loc works more consistently with lists as a row locator:
df1.loc[list(desired_rows), :]

                        Value
ID1     ID2     ID3
1       1001    1           1
                2           2
2       1002    2           4

A: You can do this by passing the individual index level values and then slice(None) for the non-existent 3rd index level:
In [107]:
df1.loc[df2.index.get_level_values(0), df2.index.get_level_values(1),slice(None)]

Out[107]:
              Value
ID1 ID2  ID3
1   1001 1        1
         2        2
2   1001 1        3
         2        4

Then we can see that all values match:
In [111]:
all(df1.loc[df2.index.get_level_values(0), df2.index.get_level_values(1),slice(None)] == expected_result)

Out[111]:
True

The problem is that because the indices are not the same dimensions you need to specify what to pass for the non-existent 3rd level, here passing slice(None) will select all rows for that level so the masking will work

A: One way is to temporarily reduce the dimension of the higher dimensional index to then do a same-dimension filtering:
 result = (df1.reset_index().set_index(['ID1', 'ID2']).loc[df2.index]
           .reset_index().set_index(['ID1', 'ID2', 'ID3']))
 assert all(result == expected_result) # will pass

It's quite involved though.

A: The list comparison can be done with isin: first drop the additional dimensions from the index of the higher dimensional dataframe and then compare the remains with the index of the lower dimensional one. In this case:
 mask = df1.index.droplevel(2).isin(df2.index)
 assert all(df1[mask] == expected_result) # passes


text:
Q: How can I resolve a value when returning promise all? I am calling a promise function in a loop and I want to be able to return all of its promises and return a value (assetIds) as well. However I am after calling the function (addToCollectionMap) obj.assetIds is undefined.
function addToCollectionMap(client, json, collectionId) {
  var promises = [];
  var assetIds = [];
  return new Promise(function (resolve) {
      var list = JSON.parse(json)["list"];
      list.forEach(function (asset) {
          var assetId = asset["id"];
          assetIds.push(assetId);
          promises.push(setToCache(client, PREFIX + assetId, collectionId));
      });
      promises.push(resolve({assetIds: assetIds}));
  }).then(function () {
      return Promise.all(promises);
  });
}

Calling code:
   return addToCollectionMap(client, jsonString, collectionId)
        .then(function (obj) {
            return setToCache(client, ASSET_MAP_PREFIX + collectionId, obj.assetIds);
        });

A: Your .then is returning the promise created by Promise.all(promises), therefore it will have the results of all the promises. You simply need another .then that returns what you want instead.
}).then(function () {
  return Promise.all(promises);
}).then(function () {
  return assetIds;
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: command line byte sequence How do you express a byte sequence from the command line?
i.e like you would in PHP with the following:
<?php
echo "\xC2\xA3"

usage: for passing a Unicode string to a script or program. The above example is the UK pound sign "£"

A: echo -e "\xC2\xA3"

or
echo $'\xc2\xa3'

the latter may be bash-specific, I don't remember.

A: $ printf "\xC2\xA3"
£


text:
Q: Python PPTX Datalabel Fill Color data_labels = chart_plot.data_labels
data_labels.font.size = Pt(10)
data_labels.font.color.rgb = RGBColor(255, 255, 255)
data_labels.position = XL_LABEL_POSITION.CENTER

How can i access the datalabel's fill color to produce a similar fill as the image on the link below?
https://i.stack.imgur.com/yUI4h.png
I tried:
data_labels.format.fill.solid()
data_labels.format.fill.fore_color.rgb = RGB(0,164,251)

But not working.
Thanks.


text:
Q: Dynamical variables in pentaho for Step - Table Input In my ktr, I need to create dynamic query for Step Table Input.
like -
Select ${SelectList} from ${Table}

The value of SelectList Table is coming from Step - Set Variables.
It is not working. Am I missing something?

A: You can't assume that a Set Variables step will get its variables set at any time within the same transform. That is the nature of PDI's multi-threading. You need to be sure the variables are set before the Table input step begins. Generally this is done by putting the transform in a Job and setting the variables there, before the transform runs.
You can also pass parameters to the transform and read them into the transform with a Get System Info step referencing `Command line argument 1', etc.

A: I think the set variables step  should not in the some transformation with any step using variables.
You should notice the information when creating the set variables step.


text:
Q: How do i replicate a = b and c = d logic over multiple values of a crystal reports parameter? I'm trying to recreate a sql query into a crystal report with parameters than the user can use to specify which items should show up on a report. My current sql query is as follows:
select *
from SALES
where (customerID = '4' and date = '5/2/2019)
or    (customerID = '6' and date = '4/30/2019')
or    (customerID = '69' and date = '8/18/1984')

...etc.
I want to be able to replicate this in crystal reports and allow the user to put in customer ID and date pairs and pull any records that match. The user will not always have a set number of customer/date pairs when running the report so i am trying to keep it open as possible
ive tried to switch the parameters to allow multiple values but that produces more results than expected because it will return every row for a given customer as long as they had sales on any of the dates listed, not just the one they are paired with. i also tried creating a supressed field that is the concatenated id and date and then concatenating the parameters to see which ones match, however it gives an error when i input more than one pair regarding the array

A: Begin with a report that shows all sales regardless of customerID or date.
Create 2 parameter fields in your crystal report.  The first will be named "customerID" and the second will be named "date".
Parameter Fields can be setup to allow a single value to be entered, or they can be setup to allow multiple values to be selected from a list or a range of values to be selected by entering a min and max value.
The go into Select Expert and create 2 fields that will be filtered when records are selected by the report.  The 2 fields to be filtered will be "cusotmerID" and "date".  Each field should be setup so that the values entered in your parameter fields are compared against the values in the data set selected by your report and only the records that have the customerID and date values input into the parameters are not filtered out of the data set.
The formula in Select Expert should look similar to the following, but it can vary a little depending upon how you setup your parameter fields and select expert filters:
{SALES.cusotmerID} in {?customerID} and
{SALES.date} in {?date}


text:
Q: Can I input all the command at once? I implemented a java program with some methods. Next I created a main class which will call the related method by entering a word.
for example:
Enter {A|B|C|D|E} to call method. A=method one B = method two...etc
A<--this is the user input
Enter Number:<--the first Scanner input of method A
123<--Input 1
Enter words:<-- the second Scanner input of method A
ABC<--Input 2

123ABC<--The output method A

Enter {A|B|C|D|E} to call method. A=method one B = method two...etc
B<--this is the user input
Enter Number 1:<--the first Scanner input of method B
100<--Input 1
Enter Number 2:<-- the second Scanner input of method B
50<--Input 2

150<--The output method B

Code of Method A {
String output;
private static Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Number:");

String no = keyboard.nextLine();

System.out.println("Enter Words:");

String words = keyboard.nextLine();

//do something...
System.out.println(output);
}

Code of Main class{

private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args){
Main main = new Main();
main.run();
}
  public void run() {
    boolean running = true;

    while (running) {
        displayMenu();

        String command = keyboard.nextLine();
         String[] parts = command.split("^");

        if ("A".equalsIgnoreCase(command)) {
            //call method A
        } else if ("B".equalsIgnoreCase(command)) {
            //call method B
        } else if....etc

        System.out.println();
    }

what I want is input
A123 , ABCB100,50 at once
then the system will print the output of method A (123ABC) and B (150) for me.
What I want is input A into "keyboard", input 123 into "no" and input ABC into "words" at once
How can I do it?

A: As long as your don't close your Scanner (or its underlying input stream), the yet-to-read tokens will remain accessible for later use : read two lines (or 4 tokens - the comma is one) and "B\n100,50" will remain.
If you're asking how to provide this kind of input, it depends on your invokation method. If executed from bash, I'd use the following :
echo """A
123 , ABC
B
100,50""" | java ...

If you're asking how to dynamically invoke a method from its name, check the reflection API. Oracle's tutorial is a good resource in my opinion, here's a link to its section on retrieving and invoking methods.

A: There are 2 ways to do that.
First:
Instead of giving input directly in the console, first write all the data input somewhere and just copy it and paste it in the console.

Second:
You can use hasNexLine() and  send EOF through keyboard by pressing ctrl+d.
Code:
public static void main(String[] args)
    {

        Scanner s = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();

        while(s.hasNextLine())
        {
            sb.append(s.nextLine());

        }
        System.out.println(sb.toString());
    }

Provide all your input and press ctrl+d to stop taking input.


text:
Q: Cannot draw basic triangle with vbos opengl in lwjgl 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

A: 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!

A: 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.

A: 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))


text:
Q: Do I need to reconnect every 15 minutes with RDS IAM authentication I am using RDS postgresql with IAM authentication. In my application, it generates the token at runtime before it connects to RDS cluster. Based on AWS document,
An authentication token is a string of characters that you use instead of a password. After you generate an authentication token, it's valid for 15 minutes before it expires. If you try to connect using an expired token, the connection request is denied.,
the token is only valid for 15 minutes. My question is that do I need to reconnect every 15 minutes? If the connection is already set up, does it require token for each query/insert/update etc.? If it doesn't require the token, that means I need to keep my connection always open. Does RDS support that connection mode?

A:
My question is that do I need to reconnect every 15 minutes?

No you don't. The token is required to establish connection, and does not determine how long the existing connection can last for. The default value for connection to be alive without activity is 28800s (8 hours) as explained here.
This means that if you terminate your connection, or mysql terminates it due to not being actively used, then you need to get a new token to re-connect if the existing one already expired.

A: If your connection to the DB is interrupted (for any number of reasons) and you need to re-connect and it is greater than 15 minutes since you created the token you will need to create a new token. Otherwise if you maintain a connection to the DB your access will not be interrupted after successfully authenticating.
From AWS "The token is only used for authentication and doesn't affect the session after it is established."
There is no way to increase the Token lifespan for greater than 15 minutes. This Github issue shows where others have encountered the same issue, when using IAM for RDS via the short lived Tokens.
AWS Docs for connecting to RDS via IAM role/user.
Recommendations from AWS Docs suggest to "use IAM database authentication as a mechanism for temporary, personal access to databases."


text:
Q: Understanding MuleSoft flow transformation I am new to MuleSoft and Mule flows.
I want to concatenate the fromairport and toairport columns. The result should be in columns like:
fromairport           toairport

MUA                        LAX

MUA                        CLE

MUA                        SFO

.....

I am transforming the following json:
    [
      {
        "planeType": "Boeing 787",
        "code2": "0001",
        "takeOffDate": "2016-01-20T00:00:00",
        "code1": "rree",
        "fromAirport": "MUA",
        "price": 541,
        "seatsAvailable": 0,
        "toAirport": "LAX",
        "ID": 1,
        "airlineName": "American Airlines",
        "totalSeats": 200
      },
      {
        "planeType": "Boeing 747",
        "code2": "0123",
        "takeOffDate": "2016-01-25T00:00:00",
        "code1": "eefd",
        "fromAirport": "MUA",
        "price": 300,
        "seatsAvailable": 7,
        "toAirport": "CLE",
        "ID": 2,
        "airlineName": "American Airlines",
        "totalSeats": 345
      },
      {
        "planeType": "Boeing 777",
        "code2": "0192",
        "takeOffDate": "2016-01-20T00:00:00",
        "code1": "ffee",
        "fromAirport": "MUA",
        "price": 300,
        "seatsAvailable": 0,
        "toAirport": "LAX",
        "ID": 3,
        "airlineName": "American Airlines",
        "totalSeats": 300
      }
    ]

A: I don't think the question is correctly expressed. There is no concept of 'columns' as such in DataWeave. There are objects, arrays and attributes. The equivalent of a column is an attribute array of objects. You can see the same concept in the input JSON, where planeType, code2, etc. are the 'columns'.
I will assume you want this output not in JSON or XML, but you want to further process it, so the best match for the output should be application/java.
In Mule 4.x the DataWeave script is:
%dw 2.0
output application/java
---
payload map (
    $.fromAirport ++ " to " ++ $.toAirport
)

UPDATE: Based on the comments I have updated the script to return a list of strings. Each string is the concatenation of the fromAirport attribute, the literal string " to " and the toAirport attributes. Both attributes are expected to be strings.
Output:
["MUA to LAX", "MUA to CLE", "MUA to LAX"]

A: Try output the payload to csv format
%dw 2.0
output application/csv separator=" "
---
payload map ((item) -> {
    fromAirport: item.fromAirport,
    toairport: item.toAirport
})

Result:
fromAirport toairport
MUA LAX
MUA CLE
MUA LAX

You can try on Mulesoft Datawave playground here


text:
Q: AWS RDS MySQL remote connection extremely slow I have a site hosted on AWS EC2 (Elastic Beanstalk), with a MySQL database hosted on AWS RDS. Everything works fine on the production server, fast and all.
However when I try to connect remotely from my local machine, it sometimes gets extremely slow (like 4 minutes to load the list of tables), or simply times out.
I added my IP in the security group (which I did correctly, since it sometimes works).
When it doesn't work, I at the same time check the prod server and it still looks good.

A: As much I could understand, there is nothing wrong at the ACL or network level, as you are saying that it works sometimes.
What I can see is that you are hitting a limit on the maximum number of processes for Mysql. So, when you connect and issue any command, then if the number of processes allowed to run are saturated, then you have to wait and your request goes into queue. But if you don't get a slot then after that it timeouts.
You can check the same by looking at the graphs which are available with RDS. If the graph is going flat at some value, then my guess is very right.
The total number of connections depends on the instance type you are using. That you can check and set in the DB parameters group option. Search for max_connections.
I am not sure what are the default values for different types of instances, but I am sure this information should be somewhere over the internet.


text:
Q: Creating a footer that stays at the bottom of the page I have went through countless methods on the previously answered questions. I believe I followed this one (http://www.cssreset.com/how-to-keep-footer-at-bottom-of-page-with-css/) to the t but I still cannot get my footer to stay at the bottom of the page. I know this has been asked countless times but I don't where to adjust my code. Any help with this would be appreciated.
Here is my code:
HTML

Home

About ▾

History

Brothers

Philanthropy ▾

Kovacs Color Run

Greek God

Membership

Contact

Welcome to the official website for the New York Iota chapter of Phi Kappa Psi at Binghamton

University! Here you will be able to learn about us, and get a brief introduction to Greek Life at

Binghamton. If you have any questions or simply want to learn more information, feel free contact us at

any time.

Carl Hashem (Chapter President)

Connect

Greek God

On October 18th 2014, brother Anthony Leighton will be representing us in this years Greek God competition. All proceeds go to the Elizabeth Glazier Pediatric Aids Foundation.

Donate!

Kovacs Color Run

The 5th Annual Steve Kovacs Color Run will take place on October 19th 2014. All proceeds are split between the Fairview Recovery Center and Childhood Development Center.

Sign Up!

© Phi Kappa Psi NY Iota Chapter. All Rights Reserved.

CSS
html {
    height:100%;
    margin:0;
    padding:0;
}
#wrapper {
    min-width:1000px;
    min-height:100%;
    position:relative;
}
body {
    margin:0;
    padding:0;
    height:100%;
}

header {
    height:100px;
    width:100%;
    background:black;
    margin:0 auto;

}

.logo{
    padding-left:10px;
    float:left;
    padding-top:5px;
}

.chapter-logo {
    float:right;
    padding-top:15px;
    padding-right:10px;
}

/* Start MENU styling*/

.menu{
    margin:0 auto;
    padding:0 ;
    text-align:center;
    clear:both
}

ul.menu {
    background-image: -o-linear-gradient(bottom, #ACB5B5 0%, #E2F0EA 100%);
    background-image: -moz-linear-gradient(bottom, #ACB5B5 0%, #E2F0EA 100%);
    background-image: -webkit-linear-gradient(bottom, #ACB5B5 0%, #E2F0EA 100%);
    background-image: -ms-linear-gradient(bottom, #ACB5B5 0%, #E2F0EA 100%);
    background-image: linear-gradient(to bottom, #ACB5B5 0%, #E2F0EA 100%);
    height: 40px;
    width: 100%;
    border-left:solid 1px #22674A;
    white-space: nowrap;
    text-align:center;
}

ul.menu > li {
    position: relative;
    display:inline-block;
    list-style:none;
    text-align:center;
    width:20%;
    border-style:1px #22674A;
    font-family: "Open Sans", sans-serif;
    font-weight:700;
}

/*sub menu styling*/

ul.menu li:first-child a {
    border-left:none;
}

ul.menu ul li:first-child {
    border-bottom:solid 1px #22674A;
}

ul.menu ul li:nth-child(2) {
    border-bottom:solid 1px #22674A;
}

ul.menu ul li:last-child{
    border-bottom:none;
}

ul.menu ul li a {
    border:none;
}
ul.menu ul {
    background-image: -o-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100% );
    background-image: -moz-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100% );
    background-image: -webkit-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100%);
    background-image: -ms-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100%);
    background-image: linear-gradient(to bottom, #E2F0EA 0%, #ACB5B5 100% );
    position: absolute;
    padding:0;
    border-left:none;
    border:solid 1px #22674A;
    width:100%;
    text-align:center;
    display:none;

}
ul.menu a {
    cursor: pointer;
    display: block;
    color: #22674A;
    line-height: 40px;
    text-decoration:none;
    font-weight:bold;
    border-left:solid 1px #22674A;
}
ul.menu li {
    list-style: none;
}

/* End MENU styling */
/* Banner Styling*/
.index {
    height:400px;
    background-image: url("http://i.imgur.com/RI05og7.jpg");
    background-repeat:no-repeat;
    background-size:100% 400px;
}

.letter{
    width:460px;
    height:250px;
    margin-left:20px;
    line-height:1.75em;
    font-family:"Open Sans", sans-serif
}

h4 {
    color:#22674A;
    font-family:"Open Sans", sans-serif;
    font-weight:700;
}

/*End of Banner Styling*/

/*News Styling*/

.news {
    width:1000px;
}

.news-section {
    padding-bottom:50px;
}
.greekgod {
    width:300px;
    height:220px;
    border:solid 1px black;
    text-align:center;
    background-image: -o-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100% );
    background-image: -moz-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100% );
    background-image: -webkit-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100%);
    background-image: -ms-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100%);
    background-image: linear-gradient(to bottom, #E2F0EA 0%, #ACB5B5 100% );
    padding:5px 5px 5px 5px;
    line-height:1.5em;
    font-family:"Open Sans", sans-serif;
    float:left;
    margin-right:30px;
}

.donate-button {
    width:150px;
    height:40px;
    border:3px solid black;
    background:#22674A;
    border-radius:5px;
    color:white;
    text-align:center;
    padding-top:7px;
    text-decoration:none;
    margin-left:65px;
    margin-bottom:10px;
    font-family:"Open Sans", sans-serif
}

.kovacs {
    width:300px;
    height:220px;
    border:solid 1px black;
    float:left;
    background-image: -o-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100% );
    background-image: -moz-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100% );
    background-image: -webkit-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100%);
    background-image: -ms-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100%);
    background-image: linear-gradient(to bottom, #E2F0EA 0%, #ACB5B5 100% );
    text-align:center;
    margin: 0 auto;
    line-height:1.5em;
    padding:5px;
    padding-bottom:10px;
    font-family:"Open Sans", sans-serif
}

.sign-up {
    width:150px;
    height:40px;
    border:3px solid black;
    background:#22674A;
    border-radius:5px;
    color:white;
    text-align:center;
    padding-top:7px;
    text-decoration:none;
    margin-left:65px;
    font-family:"Open Sans", sans-serif
}

.social{
    float:left;
    border:solid 1px black;
    position:relative;
    text-align:center;
    width:300px;
    height:220px;
    margin-right:30px;
    background-image: -o-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100% );
    background-image: -moz-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100% );
    background-image: -webkit-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100%);
    background-image: -ms-linear-gradient(bottom, #E2F0EA 0%, #ACB5B5 100%);
    background-image: linear-gradient(to bottom, #E2F0EA 0%, #ACB5B5 100% );
    padding:5px;
    font-family:"Open Sans", sans-serif

}

.social a {
    padding:20px;
}

.social h4 {
    padding-bottom:20px;
    padding-top:none;

}

.footer {
height:50px;
width:100%;
position:absolute;
background-color:black;
bottom:0;
left:0;
}

.footer p {
    text-align:center;
    color:white;
    font-size:13px;
    font-family:"Open Sans", sans-serif;
    padding-top:15px;
}

FIDDLE
http://jsfiddle.net/18468f07/

A: Try changing your layout I inspected it and that might have caused it.  Try this instead,  just move the footer div outside of the wrapper div so that they would be on the same label
You can also use position: fixed to make it stick there is you want.

© Phi Kappa Psi NY Iota Chapter. All Rights     Reserved.

And in the css
Div#wrapper {
margin-bottom: 50px;
}

That should solve it.
Sorry can't format using mobile here.

A: You could add bottom padding to the #wrapper element so the padding would contain the height of the footer and some space between the upper elements.  That's if you don't want to change the current structure.


text:
Q: How to create Elastic Beanstalk instance from s3 bucket in the aws-sdk? I am trying to deploy an elastic beanstalk instance from the aws javascript sdk and want the code source to come from an s3 bucket. I can see you can do this via the web interface but can't figure it out via the sdk.
so far I have the following which creates a new environment (application already exists at this point) but the env has no source code to run.
const elasticBeanstalkClient = new ElasticBeanstalkClient({
  region: "eu-west-2",
  credentials: {
    accessKeyId: awsAccessKeyId,
    secretAccessKey: awsAccessKeySecret
  }
});

const createEnvironmentCommand = new CreateEnvironmentCommand({
  ApplicationName: applicationName,
  EnvironmentName: environmentName,
  SolutionStackName: "64bit Amazon Linux 2 v5.4.2 running Node.js 14",
  VersionLabel: versionLabel
})

return elasticBeanstalkClient.send(createEnvironmentCommand);

CreateEnvironmentCommand doesn't seem to have a source value that I can see. How am I supposed to tell the environment to be created from an s3 source?

A:
I can see you can do this via the web interface but can't figure it out via the sdk.

EB console does a lot of things in the background to make it seem you can do it. With CDK you have to do everything by yourself. This means you have to createApplicationVersion first. When you do this, you can specify S3 location.


text:
Q: An interface can only extend an identifier/qualified-name with optional type arguments. ts(2499) I am trying to create a new extended interface for express.RequestHandler but this error seems to come up. I cannot understand why.
An interface can only extend an identifier/qualified-name with optional type arguments. ts(2499)

The express.RequestHandler interface does not support async functions. It says
The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>>'?ts(1064)

Here are my interfaces
export interface IRequest extends express.Request {
    user: IUser;
}

export interface IRequestHandler extends RequestHandler = (
    req: IRequest,
    res: express.Response,
    next: express.NextFunction
) => void | Promise<void>;

A: It seems you are trying to extend the express.Request interface.
Try:
import { NextFunction, Request, Response } from 'express';

interface IUser {
  name: string;
}

declare module 'express' {
  interface Request {
    user: IUser;
  }
}

const controller = async (req: Request, res: Response, next: NextFunction) => {
  console.log(req.user);
};


text:
Q: Change Model Value of 2nd DropDown in wicket I have 2 dropdown in wicket and select any value from 1st dropdown then its changed 2nd dropdown list accordingly. Now If i am selecting any value from 2nd dropdown then data should changed, Its fine.
Now again If I selected default value/"All" value from 1st Dropdown then 2nd default value of 2nd dropdown should be "All" but instead of this its showing me selected value in dropdown.
Below is my code:
/*
countryList having -- All, India, Srilanka, US, UK
for All --> All, U.P., Delhi, colombo, England, New York, Washington
stateList for India --> All, U.P., Delhi
For Srilanka--> All,colombo, For US --> All, New York, Washington, For UK --> All, England
*/

DropDownChoice<Country> country = new DropDownChoice<Country>("country",
        new PropertyModel<Country>(params, "selectedCountry"),
        countryList, new ChoiceRenderer<Country>("countryName", "countryId"));
DropDownChoice<State> state = new DropDownChoice<State>("state",
        new PropertyModel<State>(params, "selectedState"),
        stateList, new ChoiceRenderer<State>("stateName", "stateId"));

country.add(new AjaxFormComponentUpdatingIndicatingBehavior("onchange") {
    @Override
    protected void onUpdate(AjaxRequestTarget target) {
        if (/* provide some condition*/) {
            params.setSelectedState("ALL");
        }
        target.add(state);
    }
});

But its not showing ALL for selectedstate in 2nd dropdown.

A: The problem is indeed in the usage of == where you check the selected country. It is not very clear what is the type of params but from new PropertyModel<Country>(params, "selectedCountry") it looks like it is an object that has a property selectedCountry of type Country, where Country has countryName and countryId. So if (params.getSelectedCountry() == "ALL") is either not compiling or doing something wrong.


text:
Q: Mysql select in another table when not exist I have two tables, name tbl_siswa and tbl_tentor.
Both have an uniq id, in tbl_siswa called id_siswa and in tbl_tentor called tbl_tentor.
how to check if an input ID is from tbl_tentor or tbl_siswa in one query.
i can make this with PHP and mysql, but i need this only in mysql..

A: The fastest way is by a union:
select id_siswa as id
from tbl_siswa
where id_siswa = ?
union
select id_tentor
from tbl_tentor
where id_tentor = ?

Note that you will either get one row or no rows. Even if the id appears in both tables, you will only get one row because union removes duplicate rows.


text:
Q: Updating to empty set I just created a new column for my table
alter table user add (questions set<timeuuid>);

Now the table looks like
user (
    google_id text PRIMARY KEY,
    date_of_birth timestamp,
    display_name text,
    joined timestamp,
    last_seen timestamp,
    points int,
    questions set<timeuuid>
)

Then I tried to update all those null values to empty sets, by doing
update user set questions = {} where google_id = ?;

for each google id.
However they are still null.
How can I fill that column with empty sets?

A:
A set, list, or map needs to have at least one element because an
  empty set, list, or map is stored as a null set.

source
Also, this might be helpful if you're using a client (java for instance).

A: I've learnt that there's not really such a thing as an empty set, or list, etc.
These display as null in cqlsh.
However, you can still add elements to them, e.g.
> select * from id_set;
 set_id                | set_content
-----------------------+---------------------------------
 104649882895086167215 | null
 105781005288147046623 | null

> update id_set set set_content = set_content + {'apple','orange'} where set_id = '105781005288147046623';
 set_id                | set_content
-----------------------+---------------------------------
 104649882895086167215 | null
 105781005288147046623 | { 'apple', 'orange' }

So even though it displays as null you can think of it as already containing the empty set.


text:
Q: Resources files with SignalrR I have a project mvc 4 c# I'm using resource files for localization. I have action to change the culture
public ActionResult ChangeCulture(string lang, string returnUrl)
{
    if (lang.Equals("he-IL"))
    {
        CultureInfo ci = new CultureInfo(lang);
        ci.DateTimeFormat.ShortDatePattern = "dd/MM/yy";
        ci.DateTimeFormat.LongDatePattern = "dd/MM/yy";
        ci.DateTimeFormat.LongTimePattern = "HH:mm";
        ci.DateTimeFormat.ShortTimePattern = "HH:mm";
        ci = new CultureInfo(lang);
        Thread.CurrentThread.CurrentUICulture = ci;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
    }
    else if (lang.Equals("en-US"))
    {
        CultureInfo ci = new CultureInfo(lang);
        ci = new CultureInfo(lang);
        Thread.CurrentThread.CurrentUICulture = ci;
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
    }
    else
    {
        return new HttpStatusCodeResult(404);
    }
    return Redirect(returnUrl);
}

in the view I get the text from resource and it's working good.
<div>@(ViewRes.GlobalResource.Hello)</div>

but when I return text from SignalR hub it's always the same language. why?

A: SignalR does not localize your text within it's stack, you have to select the correctly localized text and return that string yourself. This should be as easy as requesting your resource from a ResourceManager and letting it select the correctly localized text for you. A really simple example of that looks something like this:
public string YourHubMethod()
{
    ResourceManager resourceManager = new ResourceManager("YourNamespace.YourResourcesName",
                                                          typeof(YourHubType).Assembly);

    return resourceManager.GetString("SomeResourceName");
}

Update:
Now that you've provided some more information about how you remember the current culture between requests for your web application in the comments (you use a cookie) I can give you more information on how to make this transfer over to SignalR.
You'll first want to override your Hub's OnConnected property and there you can extract the cookie value and store it in SignalR connection state like so:
public override Task OnConnected()
{
    Client.Culture = Context.Request.Cookies["YourCultureCookieName"];

    return base.OnConnected();
}

Once it's stored in the client state, you can now build a HubPipelineModule that looks for that state and sets the culture for each logical SignalR request:
public class CallerCulturePipelineModule : HubPipelineModule
{
    protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context)
    {
        // Use the value we stored in the Culture property of the caller's state when they connected
        CultureInfo callerCultureInfo = new CultureInfo(context.Hub.Context.Caller.Culture);

        Thread.CurrentThread.CurrentUICulture = callerCultureInfo;
        Thread.CurrentThread.CurrentCulture = callerCultureInfo;

        return base.OnBeforeIncoming(context);
    }
}

You then need to make sure to register the pipeline module as part of your Application_Start:
GlobalHost.HubPipeline.AddModule(new CallerCulturePipelineModule());

Finally, if the user changes their culture while they're already connected you would need to update their connection state with the newly selected value (since they're not going to reconnect).There's actually no way to modify connection state outside the hub itself, so you would need to actually get the IHubContext for your hub and update the client through an explicit callback to the client inside of your existing MVC controller's ChangeCulture method. To do this I would suggest you pass the connection ID to ChangeCulture as an optional query string variable (since the user might not be connected to your hub all the time?) and then use that to call back to the client:
string connectionId = <get connectionId from request here>;

IHubContext yourHubContext GlobalHost.GetHubContext<YourHub>();

yourHubContext.Client(connectionId).UpdateCultureState(lang);

And then on the client side you just update the state in JavaScript:
yourHubProxy.client.updateCultureState = function(lang)
{
   yourHubProxy.state.culture = lang;
}


text:
Q: Build tree from slash separated data I have below data into my program.
 List<string> lstString = new List<string>();
 lstString.Add("a/b");
 lstString.Add("a/b/c");
 lstString.Add("p/a/b/c");
 lstString.Add("b/c");
 lstString.Add("a/b/c/d");
 lstString.Add("x/y");
 lstString.Add("x");

I want to build tree from above data(slash separated) like below.
a
--b
----c
------d
p
--a
----b
------c
b
--c
x
--y

then I want build one collection of class,
public class TreeNodes
{
   public int Level { get; set; }
   public int Id { get; set; }
   public int ParentId { get; set; }
   public string RootText { get; set; }
}

After filling the class collection, I want to generate a JSON string which represents the collection class "TreeNodes".
Can anyone help me out on this problem?


text:
Q: iPhone 5 Delete Unread Mail Even though my inbox shows no mail, there is a note at the bottom of the screen that shows "787 Unread".   How can I clear or delete that note?

A: There is an Unread smart tab on the main screen of the Mail app (if you can not see this, try going into edit and adding it). This will show you any downloaded emails that have not been read. From here you can mark all as read.


text:
Q: Binding ComboBox and ObservableCollection in wpf in My OpenViewModel i collect data:
private ObservableCollection<KeyValue> availableData;

public ObservableCollection<KeyValue> AvailableDatas
{
    get { return availableData; }
    set
    {
        if (value != availableData)
        {
            availableData= value;
            NotifyOfPropertyChange("AvailableDatas");
        }
    }
}

method for collecting data:
public ObservableCollection<KeyValue> CollectData()
{
    ConnectorClient client = null;
    try
    {
        client = webservice.GetClient();
        AvailableDatas = client.GetDatas();

        client.Close();
    }
    catch (Exception ex)
    {
        webservice.HandleException(ex, client);
    }
    return AvailableDatas;
}

How to call the method CollectData in wpf and fill my COmboBox?
thx

A: You might simply call the method the first time the AvailableDatas property is accessed (e.g. from a binding in XAML):
private ObservableCollection<KeyValue> availableData;

public ObservableCollection<KeyValue> AvailableDatas
{
    get
    {
        if (availableData == null)
        {
            availableData = CollectData();
        }

        return availableData;
    }

    set
    {
        if (value != availableData)
        {
            availableData = value;
            NotifyOfPropertyChange("AvailableDatas");
        }
    }
}

Then you should change the CollectData method in a way that is does not also set the property:
public ObservableCollection<KeyValue> CollectData()
{
    ConnectorClient client = null;
    ObservableCollection<KeyValue> data = null;

    try
    {
        client = webservice.GetClient();
        data = client.GetDatas();
        client.Close();
    }
    catch (Exception ex)
    {
        webservice.HandleException(ex, client);
    }

    return data;
}

A: You could override the OnActivated() event assuming you are using an IScreen implementation and load data in there, or just do it in the constructor or a custom Initialise method if you want to roll your own (or in the property accessor as someone has already said).
You can also use coroutines if you want some visual context for the user and a better tie in with CM actions
There is a nice simple implementation of a Loader class here which helps provide visual context to the user:
https://caliburnmicro.codeplex.com/wikipage?title=IResult%20and%20Coroutines&referringTitle=Documentation
This searches the visual tree for a BusyIndicator control and activates it whilst the content is loading e.g. ...
public class SomeViewModel : Screen
{
    protected override void OnActivate()
    {
        RefreshData();
    }

    public void RefreshData()
    {
        Coroutine.BeginExecute(LoadData(), new ActionExecutionContext() { Target = this });
    }

    public IEnumerable<IResult> LoadData()
    {
        yield return Loader.Show("Loading Data...");
        yield return new LoadSomeDataRoutine(client.GetDatas);
        yield return Loader.Hide();
    }
}

The reason to have a RefreshData method is that this also allows you to bind CM actions and allows the coroutine can grab more contextual information.
Obviously you have less need to worry about the async->sync benefits this gives in Silverlight because you are using WPF (but it still applies to async web service calls), however it still has many benefits and it also helps you to write reusable routines which become part of your application framework (e.g. some level of error handling/logging encapsulated in the IResult implementation etc)
You also mentioned filling the combobox... all you would need to do in CM is place a combobox on your control, and set it's Name property to the name of the property on your VM:
public class SomeViewModel : Screen
{
    public ObservableCollection<MyObject> MyProperty { //blah blah...  }
}

<UserControl .... blah>
    <ComboBox x:Name="MyProperty" />
</UserControl>

This will fill the combobox with the items. You will still need to set the binding for SelectedItem/SelectedValue
I assume you know this already though - if not CM has some decent documentation:
https://caliburnmicro.codeplex.com/wikipage?title=Basic%20Configuration%2c%20Actions%20and%20Conventions&referringTitle=Documentation


text:
Q: Service Stack enable compression globally WE used the following post to enable compression on our Service Stack API.
Enable gzip/deflate compression.
We have the following code in my AppHost file:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
    return new ApiServiceRunner<TRequest>(this, actionContext);
}

And In my ApiServiceRunner I have the following:
public override object OnAfterExecute(IRequestContext requestContext, object response)
{
    // if it's not null and not already compressed
    if ((response != null) && !(response is CompressedResult))

    // ToOptimizedResult already picks the most optimal compression (hence the name)
    response = requestContext.ToOptimizedResult(response);

    return base.OnAfterExecute(requestContext, response);
}

The problem is that this code now runs on EVERY response and we have one endpoint that just calls a json file from the server file system. When the code runs on this json file it totally kills the app pool on the server and I see a stack overflow exception when debugging an integration test that calls this json file.
So we have had to add in the following code into our AppHost file:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
    bool useCustomRunner = actionContext.RequestType.Name != "HomepageLayoutConfigRequest";

    return useCustomRunner
        ? new ApiServiceRunner<TRequest>(this, actionContext)
        : base.CreateServiceRunner<TRequest>(actionContext);
}

As you can see we don't use our custom ApiServiceRunner when the request type name is HomepageLayoutConfigRequest. This is ugly and we want a better way of doing this.
Any ideas?
thanks
RuSs
ps. here is my latest AppHost CreateServiceRunner override:
    public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
    {
        var requestType = actionContext.RequestType;
        string message  = "The [EnableCompression] attribute exists: {0}";

        Debug.WriteLine(string.Format("The requestType was {0}", requestType));

        var useCustomRunner = requestType.HasAttribute<EnableCompression>();
        Debug.WriteLine(string.Format(message, requestType.HasAttribute<EnableCompression>()));

        #region for serviceType if we ever need it. Currently it doesnt work as the guys at SS say it should
        // https://stackoverflow.com/questions/19127522/service-stack-enable-compression-globally
        // Commented out at there is nothing in the EndpointHost.Metadata so getting a null exception - we only need to use the attribute on the request DTO anyway.

        // @Mythz - the following code is the code that doesnt work as per my comments
        //var serviceType = EndpointHost.Metadata.GetServiceTypeByRequest(requestType);

        // @Mythz- this (serviceType) is always null. It is available in next iteration of debugging (1 iteration behind)
        //if (serviceType != null && !useCustomRunner)
        //{
        //    Debug.WriteLine(string.Format("The serviceType was {0}", serviceType));
        //    useCustomRunner = serviceType.HasAttribute<EnableCompression>();
        //    Debug.WriteLine(string.Format(message, serviceType.HasAttribute<EnableCompression>()));
        //}
        #endregion

        return useCustomRunner
            ? new ApiServiceRunner<TRequest>(this, actionContext)
            : base.CreateServiceRunner<TRequest>(actionContext);
    }

A: I think you're on the right track, tho I'd prefer to use a Custom Attribute instead, e.g to only enable compression for Service classes or Request DTO's which are marked with [EnableCompression], you can do:
var serviceType = actionContext.ServiceType;
var requestType = actionContext.RequestType;

var useCustomRunner = serviceType.HasAttribute<EnableCompressionAttribute>()
                   || requestType.HasAttribute<EnableCompressionAttribute>()

return useCustomRunner
    ? new ApiServiceRunner<TRequest>(this, actionContext)
    : base.CreateServiceRunner<TRequest>(actionContext);

I personally like the declarative intent of [EnableCompression] but you can also use something like [UseCustomRunner] if your ApiServiceRunner ends up doing more than just compression.


text:
Q: Python slicing numpy array using another array as depth I have a 3 dimensional numpy array with dimensions (x = 2, y = 2, z = 3), as shown below
a = [[[0,1,2],[3,4,5]],
    [[6,7,8],[9,10,11]]]

I want to get first N elements from each (x, y) element of a, where N is defined in another array of size x,y. E.g.
b = [[1,2],
     [0,0]]

The result would should be
c = [[[0,1],[3,4,5]],
    [[6],[9]]

How can I do this without loops?

A: You can create a mask over the elements in a that are within the given ranges and use this mask whenever you need to operate on a. If you want the encapsulate the mask and array in one entity, have a look at the numpy.ma module.
a = np.array([[[0,1,2],[3,4,5]],
             [[6,7,8],[9,10,11]]])

b = np.array([[1,2],
              [0,0]])

mask = np.arange(3)[None,None,:] <= b[:,:,None]

a[mask]

Output:
array([0, 1, 3, 4, 5, 6, 9])

But if you want the output as a non-homogeneous array, I cannot think of a better way to do that than using loops.


text:
Q: Python mocking exception to method calls in a context manager I'm working on unittesting some python3 code that calls sendmail on an SMTP class via a context manager and attempts to catch exceptions to log them.  I can successfully mock the SMTP class and do some checking on it in other tests (e.g. verifying that send_message was actually called), but I can't seem to get the method call to send_message on the class to raise an exception to log the error.
Code to be tested (from siteidentity_proxy_monitoring.py):
def send_alert(message, email_address):
    with SMTP('localhost') as email:
        try:
            email.send_message(message)
        except SMTPException:
            # retry the send
            print('exception raised') # debugging statement
            try:
                email.send_message(message)
            except:
                logging.error(
                    'Could not send email alert to %s', email_address
                )

Unittest method:
@unittest.mock.patch('siteidentity_proxy_monitoring.SMTP')
@unittest.mock.patch('siteidentity_proxy_monitoring.logging')
def test_logging_when_email_fails(self, mock_logger, mock_smtp):
    """
    Test that when alert email fails to send, an error is logged
    """
    test_print('Testing logging when email send fails')
    email_instance = mock_smtp.return_value
    email_instance.send_message.side_effect = SMTPException
    siteidentity_proxy_monitoring.send_alert(
        'test message',
        'email@example.com'
    )
    mock_logger.error.assert_called_with(
        'Could not send email alert to %s', 'email@example.com'
    )

Output from the test result:
[TEST] ==> Testing logging when email send fails
F
======================================================================
FAIL: test_logging_when_email_fails (__main__.TestSiteidentityMonitors)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/lib/python3.6/unittest/mock.py",line 1179, in patched
    return func(*args, **keywargs)
  File "tests/siteidentity_monitor_tests.py", line 108, in
test_logging_when_email_fails
    'Could not send email alert to %s', 'email@example.com'
  File "/lib/python3.6/unittest/mock.py", line 805, in assert_called_with
     raise AssertionError('Expected call: %s\nNot called' % (expected,))
AssertionError: Expected call: error('Could not send email alert to %s', 'email@example.com')
Not called

----------------------------------------------------------------------
Ran 4 tests in 0.955s

FAILED (failures=1)

I feel like I'm missing something related to the calls to __enter__ and __exit__, but I can't quite seem to tease out why my patching doesn't seem to trigger the side effect where I expect it to.  Unfortunately, most of the examples and documentation I've come across don't quite go that in depth with mocking method calls within contexts (as far as I've understood them, anyway).

A: Got stuck on similar issue just now, this is how get around it:

*

*Put a import pdb;pdb.set_trace() before line email.send_message(message)

*Run your test.

*When you get dropped into the PDB session, type email.send_message and you'll see something like <Mock name='mock_smtp().__enter__().send_message' id='...'>.

*In your test case, replace all ()s with return_value. In your case: mock_smtp.return_value.enter.return_value.send_message.side_effect = SMTPException.

A: Here is the same test, using pytest and mocker fixture:
def test_logging_when_email_fails(mocker):
    mock_logging = mocker.MagicMock(name='logging')
    mocker.patch('siteidentity_proxy_monitoring.logging', new=mock_logging)
    mock_SMTP = mocker.MagicMock(name='SMTP',
                                 spec=siteidentity_proxy_monitoring.SMTP)
    mocker.patch('siteidentity_proxy_monitoring.SMTP', new=mock_SMTP)
    mock_SMTP.return_value.__enter__.return_value.send_message.side_effect = SMTPException

    siteidentity_proxy_monitoring.send_alert(
        'test message',
        'email@example.com'
    )

    mock_logging.error.assert_called_once_with(
        'Could not send email alert to %s', 'email@example.com')

You may find the way I wrote the test more interesting than the test itself - I have created a python library to help me with the syntax.
Here is how I approached your problem in a systematic way:
We start with the test call you want and my helper library to generate the mocks to the referenced modules and classes, while also preparing the asserts:
from mock_autogen.pytest_mocker import PytestMocker

import siteidentity_proxy_monitoring

def test_logging_when_email_fails(mocker):
    print(PytestMocker(siteidentity_proxy_monitoring).mock_referenced_classes().mock_modules().prepare_asserts_calls().generate())
    siteidentity_proxy_monitoring.send_alert(
        'test message',
        'email@example.com'
    )

Now the test obviously fails due to the fact we haven't mocked SMTP yet, but the print output is useful:
# mocked modules
mock_logging = mocker.MagicMock(name='logging')
mocker.patch('siteidentity_proxy_monitoring.logging', new=mock_logging)
# mocked classes
mock_SMTP = mocker.MagicMock(name='SMTP', spec=siteidentity_proxy_monitoring.SMTP)
mocker.patch('siteidentity_proxy_monitoring.SMTP', new=mock_SMTP)
mock_SMTPException = mocker.MagicMock(name='SMTPException', spec=siteidentity_proxy_monitoring.SMTPException)
mocker.patch('siteidentity_proxy_monitoring.SMTPException', new=mock_SMTPException)
# calls to generate_asserts, put this after the 'act'
import mock_autogen
print(mock_autogen.generator.generate_asserts(mock_logging, name='mock_logging'))
print(mock_autogen.generator.generate_asserts(mock_SMTP, name='mock_SMTP'))
print(mock_autogen.generator.generate_asserts(mock_SMTPException, name='mock_SMTPException'))

I've placed the relevant mocks before the test call and added the generate asserts call afterwards:
def test_logging_when_email_fails(mocker):
    mock_logging = mocker.MagicMock(name='logging')
    mocker.patch('siteidentity_proxy_monitoring.logging', new=mock_logging)
    mock_SMTP = mocker.MagicMock(name='SMTP',
                                 spec=siteidentity_proxy_monitoring.SMTP)
    mocker.patch('siteidentity_proxy_monitoring.SMTP', new=mock_SMTP)

    siteidentity_proxy_monitoring.send_alert(
        'test message',
        'email@example.com'
    )

    import mock_autogen
    print(mock_autogen.generator.generate_asserts(mock_logging,
                                                  name='mock_logging'))
    print(mock_autogen.generator.generate_asserts(mock_SMTP, name='mock_SMTP'))

This time, the test execution gave me some useful asserts:
mock_logging.assert_not_called()
assert 1 == mock_SMTP.call_count
mock_SMTP.assert_called_once_with('localhost')
mock_SMTP.return_value.__enter__.assert_called_once_with()
mock_SMTP.return_value.__enter__.return_value.send_message.assert_called_once_with('test message')
mock_SMTP.return_value.__exit__.assert_called_once_with(None, None, None)

We never got to the logging part, since we threw no SMTPException! Luckily we can alter one of the asserts in a minor way to create the side affect we want (this is where a lot of guessing is done normally and the tool is really helpful):
def test_logging_when_email_fails(mocker):
    mock_logging = mocker.MagicMock(name='logging')
    mocker.patch('siteidentity_proxy_monitoring.logging', new=mock_logging)
    mock_SMTP = mocker.MagicMock(name='SMTP',
                                 spec=siteidentity_proxy_monitoring.SMTP)
    mocker.patch('siteidentity_proxy_monitoring.SMTP', new=mock_SMTP)
    mock_SMTP.return_value.__enter__.return_value.send_message.side_effect = SMTPException

    siteidentity_proxy_monitoring.send_alert(
        'test message',
        'email@example.com'
    )

    import mock_autogen
    print(mock_autogen.generator.generate_asserts(mock_logging,
                                                  name='mock_logging'))
    print(mock_autogen.generator.generate_asserts(mock_SMTP,
                                                  name='mock_SMTP'))

The generator created the right mocks for mock_logging:
mock_logging.error.assert_called_once_with('Could not send email alert to %s', 'email@example.com')

You also got a more exact assert, which can be used to ensure your tested code does retries:
from mock import call
mock_SMTP.return_value.__enter__.return_value.send_message.assert_has_calls(
    calls=[call('test message'), call('test message'), ])

And that's how I got the code I originally placed!


text:
Q: Might this cause an infinite loop? For defining a second const version of a function, is it guaranteed safe to do this? It looks like it would have infinite recursion as I want to return const but the other function which I mean to call is non-const.
It works with g++ but I worry that this is unsafe.
#include <iostream>

using namespace std;

class test {
public:
   int* doSomething(int a) {
      int* someInt = new int(a);

      return someInt;
   }

   const int* doSomething(int a) const {
      return doSomething(a);
   }
};

int main() {
   test a;

   cout << *a.doSomething(12345) << endl;

   return 1;
}

A: Not quite: as @Pete Becker has pointed out in the comments, if you had called the const version that will recurse:
class test {
public:
   int* doSomething(int a) {
      int* someInt = new int;
      *someInt = a;
      return someInt;
   }

   const int* doSomething(int a) const {
      return doSomething(a);
   }
};

int main() {
   const test a;
   // You're not in for a good time:
   a.doSomething(12345);
   return 1;
}

When providing const and non-const versions of a function that requires duplicated code, it's best to implement the const version, then have the non-const version call it in a specific way.
From Scott Myers Effective C++ - Third Edition:

When const and non-const member functions have essentially identical implementation, code duplication can be avoided by having the non-const version call the const version

Scott Myers goes on to provide a safe means for doing this:
const int* doSomething(int a) const
{
   int* someInt = new int;
   *someInt = a;
   return someInt;
}

int* doSomething(int a)
{
   return const_cast<int*>(static_cast<const Test&>(*this).doSomething());
}

In the non-const version, there are two casts: the static_cast basically turns this into const this, where the const_cast casts away the const-ness of the return. This is safe to do, because to call the non-const version, you must've had a non-const this.
However, if you are just providing access to a member, it's simple and easier to read to just have the following:
class TestAccess;
class Test
{
    TestAccess& t;
public:
    const TestAccess& getA() const { return t; }
    TestAcess& getA() { return t; }
};

A: In this case the compiler is always going to pick the not const version of the function, is not even calling the const one.
Otherwise the compiler will not compile, you are braking the constenss.
For example I modified quickly the code:
#include <iostream>

using namespace std;

class test {
public:
    int* doSomething(int a) {
        int* someInt = new int;

        *someInt = a;
        return someInt;
    }
    int ax = 10;
    void somethingElse(int i)
    {
        ax = i;
    }
    const int* doSomething(int a) const {
        somethingElse(a);
        return 0;
    }
};

int main() {
    test a;

    cout << *a.doSomething(12345) << endl;

    return 1;
}

This example does not compile because you are calling a const function inside a const scope. The compiler won't let you do that.
Now, I know is a test but doing this way you will never get out of the recursion, it will loop forever, and also you are leaking memory at every call by allocating on the heap, those two things together can lead to a disaster.


text:
Q: How To Specify Security Principal (group or user) in X509Certificate2.Export() Instead of Password Using the Certificates.msc tool, I can run the Certificate Export Wizard to export a SSL certificate to a .pfx file. This wizard allows me to either set a password, or to select a security principal (a group or user name).  I choose the 2nd option and select a user name. Works great.
But I now want to do this same export programmatically, and I find that the X509Certificate2.Export() method only allows me to set a password. I see no way to use a security principal to protect the private key.  How can I do that?


text:
Q: Redirect becomeFirstResponder to a subview Is it possible to redirect the becomeFirstResponder from self to a subview?
Here is my scenario.
I create a new UIWindow, let's call it secWin, object with a UINavigationController, let's call it navCon, as the rootViewController.
navCon has a custom UIViewController, let's call it cusViewCon, as rootViewController which contains only a single UITextField.
Now when i press a button in my main window, i call [secWin makeKeyAndVisible], which successfully shows the new window.
But now i want the UITextField to show the keyboard any time cusViewCon gets a becomeFirstResponder call, which is e.g. done by iOS by default when calling [secWin makeKeyAndVisible].

I tried to do all this by simply overwrite becomeFirstResponder in my cusViewCon class like this:
- (BOOL)becomeFirstResponder {
    [_myTextField becomeFirstResponder];

    return NO;
}

It is working, but i don't know if it is the correct way to do so, because in the documentation it says:

You can override this method in your custom responders to update your object's state or perform some action such as highlighting the selection. If you override this method, you must call super at some point in your implementation.

A: This method actually makes more sense when you code a bit for macOS where pretty much any view may become first responder. So don't worry to much about documentation.
Your procedure is on a correct track but I would do something like:
- (BOOL)becomeFirstResponder {
    BOOL willBecomeFirstResponder = [super becomeFirstResponder];
    if(willBecomeFirstResponder) {
        return YES; // This element is taking over the first responder so do nothing
    }
    else {
        [_myTextField becomeFirstResponder]; // This element may not become first responder at the moment so forward message to text field
        return NO;
    }
}

This way we ensure the execution of the superclass method still occurs. It should return false in your case (if not then also take a look into canBecomeFirstResponder method) so the text field should receive the message. If it does become first responder by design then it is best not to call it on your text field.

A: For those who also struggle with customisation of the responder chain in Swift, here is my take at the accepted answer. Might be useful for someone.
@discardableResult
override func becomeFirstResponder() -> Bool {
    if super.becomeFirstResponder() { return true }
    someView.becomeFirstResponder()
    return false
}

@discardableResult
override func resignFirstResponder() -> Bool {
    if super.resignFirstResponder() { return true }
    someView.resignFirstResponder()
    return false
}

someView in here is just your child view you are passing the event to. It can be UITextView, UITextField or any other UIResponder.

A: If you are using Swift, try this:
override func becomeFirstResponder() -> Bool {
    return super.becomeFirstResponder() || myTextField.becomeFirstResponder()
}


text:
Q: Caused by: java.lang.NullPointerException im getting the following error log:
05-29 20:57:29.886: D/AndroidRuntime(359): Shutting down VM
05-29 20:57:29.896: W/dalvikvm(359): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
05-29 20:57:29.896: E/AndroidRuntime(359): Uncaught handler: thread main exiting due to uncaught exception
05-29 20:57:29.906: E/AndroidRuntime(359): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dd.qsg/com.dd.qsg.QSGActivity}: java.lang.NullPointerException
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.app.ActivityThread.access$2200(ActivityThread.java:119)
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.os.Looper.loop(Looper.java:123)
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.app.ActivityThread.main(ActivityThread.java:4363)
05-29 20:57:29.906: E/AndroidRuntime(359):  at java.lang.reflect.Method.invokeNative(Native Method)
05-29 20:57:29.906: E/AndroidRuntime(359):  at java.lang.reflect.Method.invoke(Method.java:521)
05-29 20:57:29.906: E/AndroidRuntime(359):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-29 20:57:29.906: E/AndroidRuntime(359):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-29 20:57:29.906: E/AndroidRuntime(359):  at dalvik.system.NativeStart.main(Native Method)
05-29 20:57:29.906: E/AndroidRuntime(359): Caused by: java.lang.NullPointerException
05-29 20:57:29.906: E/AndroidRuntime(359):  at com.dd.qsg.DatabaseHandler.getLongestSmoke(DatabaseHandler.java:85)
05-29 20:57:29.906: E/AndroidRuntime(359):  at com.dd.qsg.QSGActivity.onCreate(QSGActivity.java:40)
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-29 20:57:29.906: E/AndroidRuntime(359):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
05-29 20:57:29.906: E/AndroidRuntime(359):  ... 11 more
05-29 20:57:29.926: I/dalvikvm(359): threadid=7: reacting to signal 3
05-29 20:57:29.926: E/dalvikvm(359): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
05-29 20:57:31.206: I/Process(359): Sending signal. PID: 359 SIG: 9

i dont know how to fix this. where is it telling me i need to fix something?
heres line 85 of DatabaseHandler.java:
theCount = context.getResources().getString(R.string.na);

heres the whole function:
public String getLongestSmoke(Context context) {
    String theCount = "";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT millis FROM records ORDER BY CAST(millis as SIGNED) DESC", null);

    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        theCount = cursor.getString(0);
    }
    else {
        theCount = context.getResources().getString(R.string.na);
    }

    cursor.close();
    return humanTime(theCount);
}

heres the line in the onCreate method of the main activity that uses this function:
    longestGone.setText(getString(R.string.longest_gone) + " " +  db.getLongestSmoke(null));

it was working fine before when it was null and now stopped all of the sudden. what am i supposed to make it?
this was working fine until i made the following changes to the onCreate of my DatabaseHandler class:
    String CREATE_ACHIEVEMENTS_TABLE = "CREATE TABLE achievements ("
             + "id INTEGER PRIMARY KEY,"
             + "name VARCHAR,"
             + "type VARCHAR,"
             + "value VARCHAR,"
             + "completed VARCHAR"
             + ")";

    db.execSQL(CREATE_ACHIEVEMENTS_TABLE);

    db.execSQL("insert into achievements (name, type, value, completed) values ('30 minutes', 'time', '1800000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('1 hour', 'time', '3600000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('2 hours', 'time', '7200000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('6 hours', 'time', '21600000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('12 hours', 'time', '43200000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('1 day', 'time', '86400000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('2 days', 'time', '172800000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('1 week', 'time', '604800000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('2 weeks', 'time', '1209600000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('1 month', 'time', '2592000000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('2 months', 'time', '5184000000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('6 months', 'time', '15552000000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('1 year', 'time', '31536000000', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('Set a record', 'milestone', '', 'no')");
    db.execSQL("insert into achievements (name, type, value, completed) values ('Beat top record', 'milestone', '', 'no')");

i also added this to the onUpgrade:
    db.execSQL("DROP TABLE IF EXISTS achievements");

A: Here:
05-29 20:57:29.906: E/AndroidRuntime(359): Caused by: java.lang.NullPointerException
05-29 20:57:29.906: E/AndroidRuntime(359):  at com.dd.qsg.DatabaseHandler.getLongestSmoke(DatabaseHandler.java:85)

I tells you that on line 85 of file DatabaseHelper.java you have a null value that you can't access.
EDIT:
According to your edited post it's the line:
theCount = context.getResources().getString(R.string.na);
context is null and causes NPE.

A: 05-29 20:57:29.906: E/AndroidRuntime(359): Caused by: java.lang.NullPointerException
05-29 20:57:29.906: E/AndroidRuntime(359):  at com.dd.qsg.DatabaseHandler.getLongestSmoke(DatabaseHandler.java:85)

There's your clue. Something on line 85 of DatabaseHandler.java is trying to dereference a null reference.
In the light of your edit, I'd guess that context is null, then.
And in the light of your second edit:
db.getLongestSmoke(null)

You are passing in null as the context parameter. Pass in a valid Context instead. Try:
db.getLongestSmoke(this)

where this is the Activity whose onCreate this call is coming from.

A: It looks like DatabaseHandler is null


text:
Q: Nginx - Run command on HTTP request How can I run a command like shutdown when my Nginx receives an HTTP request?
I read about writing modules for this, but I find it overkilling, I just need to shutdown the computer when an HTTP request is answered.

A: There is an impressively creative solution to implement some kind of shell webhooks I found recently on GitHub (all credits goes to the author).
It consist of three parts.

*

*A systemd unit to run a socat utility listening the loopback network interface (don't open used TCP port to the outer world in any case!):

[Unit]
Description=socat-based cmd api
After=network.target

[Service]
User=nobody
Group=nobody
ExecStart=/usr/bin/socat UDP-LISTEN:50333,fork,bind=127.0.0.1 EXEC:/opt/bin/shell-webhook
Restart=always

[Install]
WantedBy=multi-user.target

*

*A shell script to be placed somewhere (the above unit assumes it to be the /opt/bin/shell-webhook):

#!/bin/bash

LOG=/var/log/shell-webhook.log

declare -a DATA
read -a DATA
cmd=${DATA[4]}

case ${cmd} in

  reboot)
    echo "Executing reboot" >> ${LOG}
    shutdown -r now
    ;;

  shutdown)
    echo "Executing shutdown" >> ${LOG}
    shutdown -P now
    ;;

  *)
    echo "Unknown command $cmd" >>  ${LOG}
    ;;

esac

*

*An nginx-relevant configuration part (consider preventing access to this location using some kind of access control - allow/deny rules, basic auth, etc.):

log_format shellwebhook '$cmd\n';

server {
    ...
    location ~* ^/cmd/(\w+)$ {
        set $cmd $1;
        return 200 "$cmd";
        access_log syslog:server=127.0.0.1:50333,facility=local7,tag=nginx,severity=info,nohostname shellwebhook;
    }
}


text:
Q: CORS requests with node.js/express and AngularJS I would like to implement a very simple CORS scenario. Here's my server written in node.js/express:
var express        = require('express');
var morgan         = require('morgan');
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var app            = express();
var router         = express.Router();

router.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Test-Header');
    next();
});

router.get('/', function(req, res, next) {
    console.log('Request arrived');
    res.json({data: 'hello'});
    next();
});

app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use('/', router);

app.listen(app.get('port'), function(){
  console.log('Express is up on ' + app.get('port'));
});

To complement this I have a very simple AngularJS file as well:
var app = angular.module('myapp', []);

    app.controller('MyCtrl', function($scope, $http) {
        var config = {
            headers:  {
                'X-Test-Header': 'Test Header Data'
            }
        };

        $scope.test = 'Hello World';
        $scope.getData = function () {
            console.log('clicked');
            $http.get('http://localhost:3000/', config).
            success(function (data, status) {
                console.log('Status: ', status);
                console.log('Data: ', data);
            }).
            error(function (data, status) {
                console.log('Status: ', status);
                console.log('Data: ', data || 'Request failed');
            });
        }
    });

The output in my console for the node/express app is simply:
Express server listening on port 3000
OPTIONS / 200 4.767 ms - 3
Request arrived
GET / 200 2.572 ms - 16

And in the browser's console I see: 'clicked'.
On the network tab I see that there were two request made once I have clicked the button - one OPTIONS that returned a 200 OK, and a GET method which is pending forever.

So my question is of course, why am I experiencing this behaviour? I tried digging and read quite a few articles and tried their suggestions but none of them worked.

A: Interestingly enough the following has fixed the issue:
router.all('/', function(req, res, next) {
    console.log('Request arrived');
    res.type('application/json');
    res.json({datax: 'hello'});
    next();
});

notice the diff --> router.get('/')  vs router.all('/'). I'm a bit baffled why this is happening though.
UPDATE
Here's a much better code that I put together, now that I understand this a bit more ...
app.route('/')
    .options(function (req, res, next) {
        res.status(200).end();
        next();
    })
    .get(function (req, res) {
        res.json({data: 'hello'});
    });

And here's a quick writeup about my findings: http://tamas.io/node-jsexpress-cors-implementation/


text:
Q: No value accessor for form control with name 'startTime' and 'endTime' app.module have
import { TimepickerModule, TimepickerConfig } from 'ngx-bootstrap/timepicker';
import { getTimepickerConfig  } from './TimepickerConfig';

imports: [
  BsDatepickerModule.forRoot(),
  TimepickerModule.forRoot(),
],
providers: [
 { provide: TimepickerConfig, useFactory: getTimepickerConfig }
]

HTML
<form [formGroup]="addProjectForm">

            Start Time
            <timepicker formControlName="startTime" ></timepicker>

            End Time
            <timepicker formControlName="endTime" ></timepicker>

ts
this.addProjectForm = this.formBuilder.group({
   startTime:[Date, [Validators.required]],
   endTime:["", [Validators.required]]
});

this.startTime = new Date();

A: Looks like FormsModule and ReactiveFormsModule`
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { TimepickerModule, TimepickerConfig } from 'ngx-bootstrap/timepicker';
import { getTimepickerConfig  } from './TimepickerConfig';

imports: [
  BsDatepickerModule.forRoot(),
  TimepickerModule.forRoot(),
  FormsModule,
  ReactiveFormsModule,
],

Generally the error No value accessor for form control ...  means the component which is used with the reactive form directive (eg formControlName, formControl) doesn't know how to handle the reactive form directive.


text:
Q: Confusing conditional probability problem that I can't seem to narrow down what is important In an international school, 60 students, of whom 15 are Korean, 20 are French, eight are Greek, and the rest, 17, are Chinese, are divided randomly into four classes of 15 each. If there are a total of eight French and six Korean students in classes A and B, what is the probability that class C has four of the remaining 12 French and three of the remaining nine Korean students?
This is a problem of P(12C4 and 9C3 | A or B has 20C8 and 15C6), I think. I think I keep adding too much information to my solution.

A: There are $15$ places available in Class $C$.
There are $12$ French, $9$ Korean and $30-12-9=9$ others available to fill those places (the rest are already in Classes $A$ and $B$).
This is a Multivariate Hypergeometric Distribution with $N=20$, $K_{French}=12$, $K_{Korean}=9$, $K_{Other}=9$ and we are selecting $15$. So:
$$\begin{align}P(French=4,Korean=3,Others=8)&={{12\choose4}{9\choose3}{9\choose8}\over{30\choose15}}\\
&={495\times84\times9\over155,117,520}\\
&={374,220\over155,117,520}\\
&\approx0.0024\end{align}$$


text:
Q: PHP command-line: How do I read in a typed-in password without displaying the typed chars on the console? I want to read in a password as part of a command-line script, but do not what the typed password to appear on the screen. This seems to be a fairly common feature in command-line apps, but my Google-fu has failed in identifying how this works. Is it a feature of the OS? Do you have to intercept the input stream somehow so it doesn't write out to the console? I would like to use this in a php command line script, but I cannot use what I cannot understand.
Some independent searching yielded this link, where way down at the bottom they mention that mysqladmin does not use STDIN to read in the password. How do they do it then, and how could I implement this functionality?

A: Answering in case someone finds this googling.
It isn't possible in pure PHP.  The solution is to execute a small shell script for Linux or a small program for Windows.
The shell script would look like this for the zsh shell:
/usr/bin/env zsh -c 'stty -echo; read -r mypassword; stty echo; echo $mypassword'

A full working implementation was written by Seldaek from Composer, which you can find at https://github.com/Seldaek/cli-prompt


text:
Q: How to find the difference between dates within the same column using SQL? I am trying to solve the following challenge:
1) If a patient visits the ER within 48 hours, I want to flag that as 1.
2) If the same patient visits the ER again after 48 hours, I want to flag that as 2.
3) Each subsequent visit must be flagged as 3, 4, 5 etcetera after the first 48 hours.
Here is what my table looks like:
  PATIENT_ID    ADMIT_DATE  LOCATION
  ----------    ----------  --------
  33            1/10/2014   ER
  33            1/11/2014   ER
  33            1/15/2014   ER
  33            1/17/2014   ER
  45            2/20/2014   OBS
  45            2/21/2014   OBS
  45            2/25/2014   OBS
  45            2/30/2014   OBS
  45            2/32/2014   OBS

And here is what the desired result should look like:
 PATIENT_ID  ADMIT_DATE  LOCATION   FLAG
 ----------  ----------  --------   ----
 33          1/10/2014     ER        1
 33          1/15/2014     ER        2
 33          1/17/2014     ER        3
 45          2/20/2014     OBS       1
 45          2/25/2014     OBS       2
 45          2/30/2014     OBS       3
 45          2/32/2014     OBS       4

I have started something like this but could not complete it:
SELECT PATIENT_ID, ADMIT_DATE, LOCATION,
CASE WHEN MIN(ADMIT_DATE)-MAX(ADMIT_DATE)<48 THEN 1 ELSE 0 AS FLAG
FROM MYTABLE
GROUP BY PATIENT_ID, ADMIT_DATE, LOCATION

Can someone please help?

A: You can achieve this easy using LAG, DATEDIFF and ROWNUMBER functions. The LAG function helps you to get the previous ADMIT_DATE value. Then you can calculate the difference in hours using the DATEDIFF function. Finally, using ROWNUMBER you can simple rank your results.
This is full working example:
SET NOCOUNT ON
GO

    DECLARE @DataSource TABLE
    (
         [ATIENT_ID] TINYINT
        ,[ADMIT_DATE] DATE
        ,[LOCATION] VARCHAR(3)
    )

    INSERT INTO @DataSource ([ATIENT_ID], [ADMIT_DATE], [LOCATION])
    VALUES (33, '1-10-2014', 'ER')
          ,(33, '1-11-2014', 'ER')
          ,(33, '1-15-2014', 'ER')
          ,(33, '1-17-2014', 'ER')
          ,(45, '2-15-2014', 'OBS')
          ,(45, '2-16-2014', 'OBS')
          ,(45, '2-20-2014', 'OBS')
          ,(45, '2-25-2014', 'OBS')
          ,(45, '2-27-2014', 'OBS')

    ;WITH DataSource ([ATIENT_ID], [ADMIT_DATE], [LOCATION], [DIFF_IN_HOURS])  AS
    (
        SELECT [ATIENT_ID]
              ,[ADMIT_DATE]
              ,[LOCATION]
              ,DATEDIFF(
                            HOUR
                           ,LAG([ADMIT_DATE], 1, NULL) OVER (PARTITION BY [ATIENT_ID], [LOCATION] ORDER BY [ADMIT_DATE] ASC)
                           ,[ADMIT_DATE]
                        )
        FROM @DataSource
    )
    SELECT [ATIENT_ID]
          ,[ADMIT_DATE]
          ,[LOCATION]
          ,ROW_NUMBER() OVER (PARTITION BY [ATIENT_ID], [LOCATION] ORDER BY [ADMIT_DATE] ASC)
    FROM DataSource
    WHERE [DIFF_IN_HOURS] >= 48
        OR [DIFF_IN_HOURS] IS NULL -- these are first records

SET NOCOUNT OFF
GO

Note, I have fixed your sample data as it was wrong.

This is alternative solution without LAG function:
;WITH TempDataSource ([ATIENT_ID], [ADMIT_DATE], [LOCATION], [Rank])  AS
(
    SELECT [ATIENT_ID]
          ,[ADMIT_DATE]
          ,[LOCATION]
          ,ROW_NUMBER() OVER (PARTITION BY [ATIENT_ID], [LOCATION] ORDER BY [ADMIT_DATE] ASC)
    FROM @DataSource
),
DataSource ([ATIENT_ID], [ADMIT_DATE], [LOCATION], [DIFF_IN_HOURS]) AS
(
SELECT DS1.[ATIENT_ID]
      ,DS1.[ADMIT_DATE]
      ,DS1.[LOCATION]
      ,DATEDIFF(HOUR, DS2.[ADMIT_DATE], DS1.[ADMIT_DATE])
FROM TempDataSource DS1
LEFT JOIN TempDataSource DS2
    ON DS1.[Rank] - 1 = DS2.[Rank]
    AND DS1.[ATIENT_ID] = DS2.[ATIENT_ID]
    AND DS1.[LOCATION] = DS2.[LOCATION]
)
SELECT [ATIENT_ID]
      ,[ADMIT_DATE]
      ,[LOCATION]
      ,ROW_NUMBER() OVER (PARTITION BY [ATIENT_ID], [LOCATION] ORDER BY [ADMIT_DATE] ASC)
FROM DataSource
WHERE [DIFF_IN_HOURS] >= 48
    OR [DIFF_IN_HOURS] IS NULL -- these are first records

A: you can use DATEDIFF() available in sql-server like
SELECT DATEDIFF(hour,startDate,endDate) AS 'Duration'

You can visit http://msdn.microsoft.com/en-IN/library/ms189794.aspx

A: SELECT Patient_id,Admit_date, Location,
CASE WHEN DATEDIFF (HH , min(admit_date) , max(admit_date)) < 48 THEN count(flag)+1 ELSE 0  End As Flag
FROM tbl_Patient
GROUP BY PATIENT_ID, ADMIT_DATE, LOCATION