问:
Rotate a cube to be isometric
I'm following this rotating cube tutorial and I'm trying to rotate the cube to an isometric perspective (45 degrees, 30 degrees).

The problem is, I think, is that the rotateY and rotateX functions alter the original values such that the two red dots in the middle of the cube (visually) don't overlap. (If that makes any sense)

How can I rotate the cube on it's X and Y axis at the same time so the functions don't effect each other?

const canvas = document.getElementById('stage');
    canvas.width = canvas.parentElement.clientWidth
    canvas.height = canvas.parentElement.clientHeight
    const context = canvas.getContext('2d');
    context.translate(200,200)

    var node0 = [-100, -100, -100];
    var node1 = [-100, -100,  100];
    var node2 = [-100,  100, -100];
    var node3 = [-100,  100,  100];
    var node4 = [ 100, -100, -100];
    var node5 = [ 100, -100,  100];
    var node6 = [ 100,  100, -100];
    var node7 = [ 100,  100,  100];
    var nodes = [node0, node1, node2, node3, node4, node5, node6, node7];

    var edge0  = [0, 1];
    var edge1  = [1, 3];
    var edge2  = [3, 2];
    var edge3  = [2, 0];
    var edge4  = [4, 5];
    var edge5  = [5, 7];
    var edge6  = [7, 6];
    var edge7  = [6, 4];
    var edge8  = [0, 4];
    var edge9  = [1, 5];
    var edge10 = [2, 6];
    var edge11 = [3, 7];
    var edges = [edge0, edge1, edge2, edge3, edge4, edge5, edge6, edge7, edge8, edge9, edge10, edge11];

    var draw = function(){

      for (var e=0; e<edges.length; e++){
        var n0 = edges[e][0]
        var n1 = edges[e][1]
        var node0 = nodes[n0];
        var node1 = nodes[n1];

        context.beginPath();
        context.moveTo(node0[0],node0[1]);
        context.lineTo(node1[0],node1[1]);
        context.stroke();
      }

      //draw nodes
      for (var n=0; n<nodes.length; n++){
        var node = nodes[n];
        context.beginPath();
        context.arc(node[0], node[1], 3, 0, 2 * Math.PI, false);
        context.fillStyle = 'red';
        context.fill();
      }
    }

    var rotateZ3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);
      for (var n=0; n< nodes.length; n++){
        var node = nodes[n];
        var x = node[0];
        var y = node[1];
        node[0] = x * cos_t - y * sin_t;
        node[1] = y * cos_t + x * sin_t;
      };
    };

    var rotateY3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);

      for (var n=0; n<nodes.length; n++){
        var node = nodes[n];
        var x = node[0];
        var z = node[2];
        node[0] = x * cos_t - z * sin_t;
        node[2] = z * cos_t + x * sin_t;
      }
    };

    var rotateX3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);

      for (var n = 0; n< nodes.length; n++){
        var node = nodes[n];
        var y = node[1];
        var z = node[2];

        node[1] = y * cos_t - z * sin_t;
        node[2] = z * cos_t + y * sin_t;
      }
    }

    rotateY3D(Math.PI/4);
    rotateX3D(Math.PI/6);

    draw();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#stage {
  background-color: cyan;
 }</code>```

<canvas id="stage" height='500px' width='500px'></canvas>```

Edit: I should have included a picture to further explain what I'm trying to achieve.  I have a room picture that is isometric (45°,30°) and I'm overlaying it with a canvas so that I can draw the cube on it.  As you can see it's slightly off, and I think its the effect of two compounding rotations since each function alters the original node coordinates.

答:
You want projection not rotation

Your problem is that you are trying to apply a projection but using a transformation matrix to do it.

The transformation matrix will keep the box true to its original shape, with each axis at 90 deg to the others.

You want to have one axis at 45deg and the other at 30deg. You can not do that with rotations alone.

Projection matrix

The basic 3 by 4 matrix represents 4 3D vectors. These vectors are the direction and scale of the x,y,z axis in 3D space and the 4th vector is the origin.

The projection matrix removes the z part converting coordinates to 2D space. The z part of each axis is 0.

As the isometric projection is parallel we can just create a matrix that sets the 2D axis directions on the canvas.

The axis

The xAxis at 45 deg

```<code>const xAxis = Math.PI * ( 1 /  4);
iso.x.set(Math.cos(xAxis), Math.sin(xAxis), 0);
</code>```

The yAxis at 120 deg

```<code>const yAxis = Math.PI * ( 4 / 6);
iso.y.set(Math.cos(yAxis), Math.sin(yAxis), 0);
</code>```

And also the z axis which is up the page

```<code>iso.z.set(0,-1,0);
</code>```

The transformation

Then we just multiply each vertex coord by the appropriate axis

```<code>// m is the matrix (iso)
// a is vertex in
// b is vertex out
// m.o is origin (not used in this example
b.x = a.x * m.x.x + a.y * m.y.x + a.z * m.z.x + m.o.x;
b.y = a.x * m.x.y + a.y * m.y.y + a.z * m.z.y + m.o.y;
b.z = a.x * m.x.z + a.y * m.y.z + a.z * m.z.z + m.o.z;
//    ^^^^^^^^^^^   ^^^^^^^^^^^   ^^^^^^^^^^^
//    move x dist   move y dist   move z dist
//    along x axis  along y axis  along y axis
//     45deg          120deg        Up -90deg
</code>```

An example of above code

I have laid out a very basic Matrix in the snippet for reference.

The snippet creates 3D object using your approx layout.

The transform needs a second object for the result

I also added a projectIso that takes the directions of x,y,z axis and the scale of the x,y,z axis and creates a projection matrix as outlined above.

So thus the above is done with

```<code>const mat = Mat().projectIso(
    Math.PI * ( 1 / 4),
    Math.PI * ( 4 / 6),
    Math.PI * ( 3 / 2)  // up
); // scales default to 1
</code>```

const ctx = canvas.getContext('2d');

var w = canvas.width;
var h = canvas.height;
var cw = w / 2;  // center
var ch = h / 2;

const V = (x,y,z) => ({x,y,z,set(x,y,z){this.x = x;this.y = y; this.z = z}});
const Mat = () => ( {
   x : V(1,0,0),
   y : V(0,1,0),
   z : V(0,0,1),
   o : V(0,0,0), // origin
   ident(){
      const m = this;
      m.x.set(1,0,0);
      m.y.set(0,1,0);
      m.z.set(0,0,1);
      m.o.set(0,0,0);
      return m;
   },
   rotX(r) {
      const m = this.ident();
      m.y.set(0, Math.cos(r), Math.sin(r));
      m.z.set(0, -Math.sin(r), Math.cos(r));
      return m;
   },
   rotY(r) {
      const m = this.ident();
      m.x.set(Math.cos(r), 0, Math.sin(r));
      m.z.set(-Math.sin(r), 0, Math.cos(r));
      return m;
   },
   rotZ(r) {
      const m = this.ident();
      m.x.set(Math.cos(r), Math.sin(r), 0);
      m.y.set(-Math.sin(r), Math.cos(r), 0);
      return m;
   },
   projectIso(xAxis, yAxis, zAxis, xScale = 1, yScale = 1, zScale = 1) {
      const m = this.ident();
      iso.x.set(Math.cos(xAxis) * xScale, Math.sin(xAxis) * xScale, 0);
      iso.y.set(Math.cos(yAxis) * yScale, Math.sin(yAxis) * yScale, 0);
      iso.z.set(Math.cos(zAxis) * zScale, Math.sin(zAxis) * zScale, 0);
      return m;
   },
   transform(obj, result){
      const m = this;
      const na = obj.nodes;
      const nb = result.nodes;
      var i = 0;
      while(i < na.length){
         const a = na[i];
         const b = nb[i++];
         b.x = a.x * m.x.x + a.y * m.y.x + a.z * m.z.x + m.o.x;
         b.y = a.x * m.x.y + a.y * m.y.y + a.z * m.z.y + m.o.y;
         b.z = a.x * m.x.z + a.y * m.y.z + a.z * m.z.z + m.o.z;
      }
      return result;
   }
});

// create a box
const Box = (size = 35) =>( {
  nodes: [
    V(-size, -size, -size),
    V(-size, -size, size),
    V(-size, size, -size),
    V(-size, size, size),
    V(size, -size, -size),
    V(size, -size, size),
    V(size, size, -size),
    V(size, size, size),
  ],
  edges: [[0, 1],[1, 3],[3, 2],[2, 0],[4, 5],[5, 7],[7, 6],[6, 4],[0, 4],[1, 5],[2, 6],[3, 7]],
});

// draws a obj that has nodes, and edges

function draw(obj) {
    ctx.fillStyle = 'red';
  const edges =  obj.edges;
  const nodes =  obj.nodes;
  var i = 0;
  ctx.beginPath();
  while(i < edges.length){
    var edge = edges[i++];
    ctx.moveTo(nodes[edge[0]].x, nodes[edge[0]].y);
    ctx.lineTo(nodes[edge[1]].x, nodes[edge[1]].y);

  }
  ctx.stroke();
  i = 0;
  ctx.beginPath();
  while(i < nodes.length){
    const x = nodes[i].x;
    const y = nodes[i++].y;
    ctx.moveTo(x+3,y);
    ctx.arc(x,y, 3, 0, 2 * Math.PI, false);
  }
  ctx.fill();
}

// create boxes (box1 is the projected result)
var box = Box();
var box1 = Box();
var box2 = Box();

// create the projection matrix
var iso = Mat();
// angles for X, and Y axis
const xAxis = Math.PI * ( 1 / 4);
const yAxis = Math.PI * ( 4 / 6);
iso.x.set(Math.cos(xAxis), Math.sin(xAxis),0);
iso.y.set(Math.cos(yAxis), Math.sin(yAxis), 0);
// the direction of Z
iso.z.set(0, -1, 0);

// center rendering

ctx.setTransform(1,0,0,1,cw* 0.5,ch);

// transform and render
draw(iso.transform(box,box1));

iso.projectIso(Math.PI * ( 1 / 6), Math.PI * ( 5 / 6), -Math.PI * ( 1 / 2))
ctx.setTransform(1,0,0,1,cw* 1,ch);
draw(iso.transform(box,box1));

iso.rotY(Math.PI / 4);
iso.transform(box,box1);
iso.rotX(Math.atan(1/Math.SQRT2));
iso.transform(box1,box2);
ctx.setTransform(1,0,0,1,cw* 1.5,ch);
draw(box2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" height='200' width='500'></canvas></code>```

Title: Rotate a cube to be isometric

Body:
I'm following this rotating cube tutorial and I'm trying to rotate the cube to an isometric perspective (45 degrees, 30 degrees).

The problem is, I think, is that the rotateY and rotateX functions alter the original values such that the two red dots in the middle of the cube (visually) don't overlap. (If that makes any sense)

How can I rotate the cube on it's X and Y axis at the same time so the functions don't effect each other?

const canvas = document.getElementById('stage');
    canvas.width = canvas.parentElement.clientWidth
    canvas.height = canvas.parentElement.clientHeight
    const context = canvas.getContext('2d');
    context.translate(200,200)

    var node0 = [-100, -100, -100];
    var node1 = [-100, -100,  100];
    var node2 = [-100,  100, -100];
    var node3 = [-100,  100,  100];
    var node4 = [ 100, -100, -100];
    var node5 = [ 100, -100,  100];
    var node6 = [ 100,  100, -100];
    var node7 = [ 100,  100,  100];
    var nodes = [node0, node1, node2, node3, node4, node5, node6, node7];

    var edge0  = [0, 1];
    var edge1  = [1, 3];
    var edge2  = [3, 2];
    var edge3  = [2, 0];
    var edge4  = [4, 5];
    var edge5  = [5, 7];
    var edge6  = [7, 6];
    var edge7  = [6, 4];
    var edge8  = [0, 4];
    var edge9  = [1, 5];
    var edge10 = [2, 6];
    var edge11 = [3, 7];
    var edges = [edge0, edge1, edge2, edge3, edge4, edge5, edge6, edge7, edge8, edge9, edge10, edge11];

    var draw = function(){

      for (var e=0; e<edges.length; e++){
        var n0 = edges[e][0]
        var n1 = edges[e][1]
        var node0 = nodes[n0];
        var node1 = nodes[n1];

        context.beginPath();
        context.moveTo(node0[0],node0[1]);
        context.lineTo(node1[0],node1[1]);
        context.stroke();
      }

      //draw nodes
      for (var n=0; n<nodes.length; n++){
        var node = nodes[n];
        context.beginPath();
        context.arc(node[0], node[1], 3, 0, 2 * Math.PI, false);
        context.fillStyle = 'red';
        context.fill();
      }
    }

    var rotateZ3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);
      for (var n=0; n< nodes.length; n++){
        var node = nodes[n];
        var x = node[0];
        var y = node[1];
        node[0] = x * cos_t - y * sin_t;
        node[1] = y * cos_t + x * sin_t;
      };
    };

    var rotateY3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);

      for (var n=0; n<nodes.length; n++){
        var node = nodes[n];
        var x = node[0];
        var z = node[2];
        node[0] = x * cos_t - z * sin_t;
        node[2] = z * cos_t + x * sin_t;
      }
    };

    var rotateX3D = function(theta){
      var sin_t = Math.sin(theta);
      var cos_t = Math.cos(theta);

      for (var n = 0; n< nodes.length; n++){
        var node = nodes[n];
        var y = node[1];
        var z = node[2];

        node[1] = y * cos_t - z * sin_t;
        node[2] = z * cos_t + y * sin_t;
      }
    }

    rotateY3D(Math.PI/4);
    rotateX3D(Math.PI/6);

    draw();

#stage {
  background-color: cyan;
 }

<canvas id="stage" height='500px' width='500px'></canvas>

Edit: I should have included a picture to further explain what I'm trying to achieve.  I have a room picture that is isometric (45°,30°) and I'm overlaying it with a canvas so that I can draw the cube on it.  As you can see it's slightly off, and I think its the effect of two compounding rotations since each function alters the original node coordinates.

Body:
You want projection not rotation

Your problem is that you are trying to apply a projection but using a transformation matrix to do it.

The transformation matrix will keep the box true to its original shape, with each axis at 90 deg to the others.

You want to have one axis at 45deg and the other at 30deg. You can not do that with rotations alone.

Projection matrix

The basic 3 by 4 matrix represents 4 3D vectors. These vectors are the direction and scale of the x,y,z axis in 3D space and the 4th vector is the origin.

The projection matrix removes the z part converting coordinates to 2D space. The z part of each axis is 0.

As the isometric projection is parallel we can just create a matrix that sets the 2D axis directions on the canvas.

The axis

The xAxis at 45 deg

const xAxis = Math.PI * ( 1 /  4);
iso.x.set(Math.cos(xAxis), Math.sin(xAxis), 0);

The yAxis at 120 deg

const yAxis = Math.PI * ( 4 / 6);
iso.y.set(Math.cos(yAxis), Math.sin(yAxis), 0);

And also the z axis which is up the page

iso.z.set(0,-1,0);

The transformation

Then we just multiply each vertex coord by the appropriate axis

// m is the matrix (iso)
// a is vertex in
// b is vertex out
// m.o is origin (not used in this example
b.x = a.x * m.x.x + a.y * m.y.x + a.z * m.z.x + m.o.x;
b.y = a.x * m.x.y + a.y * m.y.y + a.z * m.z.y + m.o.y;
b.z = a.x * m.x.z + a.y * m.y.z + a.z * m.z.z + m.o.z;
//    ^^^^^^^^^^^   ^^^^^^^^^^^   ^^^^^^^^^^^
//    move x dist   move y dist   move z dist
//    along x axis  along y axis  along y axis
//     45deg          120deg        Up -90deg

An example of above code

I have laid out a very basic Matrix in the snippet for reference.

The snippet creates 3D object using your approx layout.

The transform needs a second object for the result

I also added a projectIso that takes the directions of x,y,z axis and the scale of the x,y,z axis and creates a projection matrix as outlined above.

So thus the above is done with

const mat = Mat().projectIso(
    Math.PI * ( 1 / 4),
    Math.PI * ( 4 / 6),
    Math.PI * ( 3 / 2)  // up
); // scales default to 1

const ctx = canvas.getContext('2d');

var w = canvas.width;
var h = canvas.height;
var cw = w / 2;  // center
var ch = h / 2;

const V = (x,y,z) => ({x,y,z,set(x,y,z){this.x = x;this.y = y; this.z = z}});
const Mat = () => ( {
   x : V(1,0,0),
   y : V(0,1,0),
   z : V(0,0,1),
   o : V(0,0,0), // origin
   ident(){
      const m = this;
      m.x.set(1,0,0);
      m.y.set(0,1,0);
      m.z.set(0,0,1);
      m.o.set(0,0,0);
      return m;
   },
   rotX(r) {
      const m = this.ident();
      m.y.set(0, Math.cos(r), Math.sin(r));
      m.z.set(0, -Math.sin(r), Math.cos(r));
      return m;
   },
   rotY(r) {
      const m = this.ident();
      m.x.set(Math.cos(r), 0, Math.sin(r));
      m.z.set(-Math.sin(r), 0, Math.cos(r));
      return m;
   },
   rotZ(r) {
      const m = this.ident();
      m.x.set(Math.cos(r), Math.sin(r), 0);
      m.y.set(-Math.sin(r), Math.cos(r), 0);
      return m;
   },
   projectIso(xAxis, yAxis, zAxis, xScale = 1, yScale = 1, zScale = 1) {
      const m = this.ident();
      iso.x.set(Math.cos(xAxis) * xScale, Math.sin(xAxis) * xScale, 0);
      iso.y.set(Math.cos(yAxis) * yScale, Math.sin(yAxis) * yScale, 0);
      iso.z.set(Math.cos(zAxis) * zScale, Math.sin(zAxis) * zScale, 0);
      return m;
   },
   transform(obj, result){
      const m = this;
      const na = obj.nodes;
      const nb = result.nodes;
      var i = 0;
      while(i < na.length){
         const a = na[i];
         const b = nb[i++];
         b.x = a.x * m.x.x + a.y * m.y.x + a.z * m.z.x + m.o.x;
         b.y = a.x * m.x.y + a.y * m.y.y + a.z * m.z.y + m.o.y;
         b.z = a.x * m.x.z + a.y * m.y.z + a.z * m.z.z + m.o.z;
      }
      return result;
   }
});

// create a box
const Box = (size = 35) =>( {
  nodes: [
    V(-size, -size, -size),
    V(-size, -size, size),
    V(-size, size, -size),
    V(-size, size, size),
    V(size, -size, -size),
    V(size, -size, size),
    V(size, size, -size),
    V(size, size, size),
  ],
  edges: [[0, 1],[1, 3],[3, 2],[2, 0],[4, 5],[5, 7],[7, 6],[6, 4],[0, 4],[1, 5],[2, 6],[3, 7]],
});

// draws a obj that has nodes, and edges

function draw(obj) {
    ctx.fillStyle = 'red';
  const edges =  obj.edges;
  const nodes =  obj.nodes;
  var i = 0;
  ctx.beginPath();
  while(i < edges.length){
    var edge = edges[i++];
    ctx.moveTo(nodes[edge[0]].x, nodes[edge[0]].y);
    ctx.lineTo(nodes[edge[1]].x, nodes[edge[1]].y);

  }
  ctx.stroke();
  i = 0;
  ctx.beginPath();
  while(i < nodes.length){
    const x = nodes[i].x;
    const y = nodes[i++].y;
    ctx.moveTo(x+3,y);
    ctx.arc(x,y, 3, 0, 2 * Math.PI, false);
  }
  ctx.fill();
}

// create boxes (box1 is the projected result)
var box = Box();
var box1 = Box();
var box2 = Box();

// create the projection matrix
var iso = Mat();
// angles for X, and Y axis
const xAxis = Math.PI * ( 1 / 4);
const yAxis = Math.PI * ( 4 / 6);
iso.x.set(Math.cos(xAxis), Math.sin(xAxis),0);
iso.y.set(Math.cos(yAxis), Math.sin(yAxis), 0);
// the direction of Z
iso.z.set(0, -1, 0);

// center rendering

ctx.setTransform(1,0,0,1,cw* 0.5,ch);

// transform and render
draw(iso.transform(box,box1));

iso.projectIso(Math.PI * ( 1 / 6), Math.PI * ( 5 / 6), -Math.PI * ( 1 / 2))
ctx.setTransform(1,0,0,1,cw* 1,ch);
draw(iso.transform(box,box1));

iso.rotY(Math.PI / 4);
iso.transform(box,box1);
iso.rotX(Math.atan(1/Math.SQRT2));
iso.transform(box1,box2);
ctx.setTransform(1,0,0,1,cw* 1.5,ch);
draw(box2);

<canvas id="canvas" height='200' width='500'></canvas>


来源: stackexchange

问:
How to increase memcached item max size in docker
When using memcached with docker, how can I set the max item size?

I know the following can be done e.g. -m 64 to set the storage limit:

```<code>docker run --name my-memcache -d memcached memcached -m 64
</code>```

I also know that in a Linux box the following can be done to set item max size limit:

```<code>MAXITEMSIZE=5m
</code>```

答:
The entry point script in the memcached image will pass on command line options

```<code>docker run --name my-memcache -d memcached -I 10m
</code>```

If you want to make the option default to something and be configured by the MAXITEMSIZE environment variable you could create an image FROM memcached and copy a new entry point script in.

```<code>FROM memcached
COPY docker-entrypoint.sh /usr/local/bin/
</code>```

The script needs to cater for when a user doesn't run memcached and when they specify the -I option manually.

```<code>#!/bin/sh
set -ue

# first arg is `-f` or `--some-option`
if [ "${1#-}" != "$1" ]; then
  set -- memcached "$@"
fi

if [ "$1" = "memcached" ]; then
  shift
  MAXITEMSIZE=${MAXITEMSIZE:-1m}
  set -- memcached -I "$MAXITEMSIZE" "$@"
fi

exec "$@"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When using memcached with docker, how can I set the max item size?

I know the following can be done e.g. -m 64 to set the storage limit:

docker run --name my-memcache -d memcached memcached -m 64

I also know that in a Linux box the following can be done to set item max size limit:

MAXITEMSIZE=5m

Body:
The entry point script in the memcached image will pass on command line options

docker run --name my-memcache -d memcached -I 10m

If you want to make the option default to something and be configured by the MAXITEMSIZE environment variable you could create an image FROM memcached and copy a new entry point script in.

FROM memcached
COPY docker-entrypoint.sh /usr/local/bin/

The script needs to cater for when a user doesn't run memcached and when they specify the -I option manually.

#!/bin/sh
set -ue

# first arg is `-f` or `--some-option`
if [ "${1#-}" != "$1" ]; then
  set -- memcached "$@"
fi

if [ "$1" = "memcached" ]; then
  shift
  MAXITEMSIZE=${MAXITEMSIZE:-1m}
  set -- memcached -I "$MAXITEMSIZE" "$@"
fi

exec "$@"


问:
Need solution for automated testing of web application
There are testing solutions like selenium and webdriver for testing web applications. However those would be sort of overkill for me as I'm looking for a simple testing solution that sends the data using get/post and analyzes the received html code. So I'm definitely not looking something that requires browser integration etc. Got some pointers?</p>

答: HtmlUnit works very well for this. It even understands complicated pages using jQuery.</p>

ContentLicense: CC BY-SA 2.5


问:
Uploading image by using Retrofit
I've been trying to upload an image from my application through API. But I keep getting this as response:

```<code>{"error":"<p>You did not select a file to upload.<\/p>"}
</code>```

This is my code:

APIService.java

```<code>@Multipart
@POST("/media/upload.html")
Call<UploadImg> uploadimage (@Part MultipartBody.Part file);
</code>```

UploadImageActivity.java

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri uri = data.getData();
        Picasso.with(this).load(uri).fit().into(btn_img_picker);

        String imagePath;

        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(uri);
        } else if (data.toString().contains("file:")) {
            imagePath = uri.getPath();
        } else {
            imagePath = null;
        }

        File file = new File(imagePath);

        System.out.println(imagePath);

        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);

        System.out.println(file.getName());

        Call<UploadImg> call = mAPIService.uploadimage(body);
        call.enqueue(new Callback<UploadImg>() {
            @Override
            public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
                System.out.println(response.raw());
            }

            @Override
            public void onFailure(Call<UploadImg> call, Throwable t) {
                System.out.println(t);
            }
        });
    }
}

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
</code>```

I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.

Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:

```<code>/storage/emulated/0/Download/download.jpg
</code>```

If this is the incorrect path to send, please tell the correct one. Thanks in advance.

答:
Try this I had another way to implement

Inside your interface

```<code>@Multipart
   @POST("edit_profile")
   Call<TokenResponse> getTokenAccess(@PartMap Map<String, RequestBody> map);
</code>```

Call in your Activity

```<code>private void getData() {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("your_base_url_here")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Click service=retrofit.create(Click.class);
          File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
          //make sure your image path is valid
        String convert_File_2String= String.valueOf(file);
        String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
        RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
        RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
        RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
        Map<String, RequestBody> map = new HashMap<>();
        map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
        map.put("firstname", name);
        map.put("user_id", id);
        map.put("lastname",lastname);

    Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
    tokenResponseCall.enqueue(new Callback<TokenResponse>() {
        @Override
        public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
            TokenResponse tokenResponse=response.body();
            Log.e("93","MA>>"+tokenResponse.getJwt());
                  }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<TokenResponse> call, Throwable throwable) {
                    Log.e("172","><<>>"+throwable);
            Log.e("TAG", "onFailure: 173"+call.toString() );
        }
    });
}
</code>```

Title: Uploading image by using Retrofit

Body:
I've been trying to upload an image from my application through API. But I keep getting this as response:

{"error":"
You did not select a file to upload.<\/p>"}

This is my code:

APIService.java

@Multipart
@POST("/media/upload.html")
Call<UploadImg> uploadimage (@Part MultipartBody.Part file);

UploadImageActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri uri = data.getData();
        Picasso.with(this).load(uri).fit().into(btn_img_picker);

        String imagePath;

        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(uri);
        } else if (data.toString().contains("file:")) {
            imagePath = uri.getPath();
        } else {
            imagePath = null;
        }

        File file = new File(imagePath);

        System.out.println(imagePath);

        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);

        System.out.println(file.getName());

        Call<UploadImg> call = mAPIService.uploadimage(body);
        call.enqueue(new Callback<UploadImg>() {
            @Override
            public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
                System.out.println(response.raw());
            }

            @Override
            public void onFailure(Call<UploadImg> call, Throwable t) {
                System.out.println(t);
            }
        });
    }
}

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.

Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:

/storage/emulated/0/Download/download.jpg

If this is the incorrect path to send, please tell the correct one. Thanks in advance.

Body:
Try this I had another way to implement

Inside your interface

@Multipart
   @POST("edit_profile")
   Call<TokenResponse> getTokenAccess(@PartMap Map<String, RequestBody> map);

Call in your Activity

private void getData() {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("your_base_url_here")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Click service=retrofit.create(Click.class);
          File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
          //make sure your image path is valid
        String convert_File_2String= String.valueOf(file);
        String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
        RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
        RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
        RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
        Map<String, RequestBody> map = new HashMap<>();
        map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
        map.put("firstname", name);
        map.put("user_id", id);
        map.put("lastname",lastname);

    Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
    tokenResponseCall.enqueue(new Callback<TokenResponse>() {
        @Override
        public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
            TokenResponse tokenResponse=response.body();
            Log.e("93","MA>>"+tokenResponse.getJwt());
                  }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<TokenResponse> call, Throwable throwable) {
                    Log.e("172","><<>>"+throwable);
            Log.e("TAG", "onFailure: 173"+call.toString() );
        }
    });
}


问:
How can I get a reference to a method?
Is it possible in Ruby to get a reference to methods of an object ( I would like to know if this can be done without procs/lambdas ) , for example , consider the following code :

```<code>
class X
  def initialize
    @map = {}
    setup_map
  end

  private
  def setup_map
    # @map["a"] = get reference to a method
    # @map["b"] = get reference to b method
    # @map["c"] = get referebce to c method
  end

  public
  def call(a)
    @map["a"](a) if a > 10
    @map["b"](a) if a > 20
    @map["c"](a) if a > 30
  end

  def a(arg)
     puts "a was called with #{arg}"
  end

  def b(arg)
     puts "b was called with #{arg}"
  end

  def c(arg)
    puts "c was called with #{arg}"
  end
end
</code>```

Is it possible to do such thing ? I would like to avoid procs/lambdas because I want to be able to change the behaviour of A,B,C by subclassing .

答:
You can get a reference to the method by object.method(:method_name).

Eg: To get a reference to system method.

```<code>m = self.method(:system)
m.call('ls')
</code>```

OwnerDisplayName: Donovan

Title: How can I get a reference to a method?

Body:
Is it possible in Ruby to get a reference to methods of an object ( I would like to know if this can be done without procs/lambdas ) , for example , consider the following code :

class X
  def initialize
    @map = {}
    setup_map
  end

  private
  def setup_map
    # @map["a"] = get reference to a method
    # @map["b"] = get reference to b method
    # @map["c"] = get referebce to c method
  end

  public
  def call(a)
    @map["a"](a) if a > 10
    @map["b"](a) if a > 20
    @map["c"](a) if a > 30
  end

  def a(arg)
     puts "a was called with #{arg}"
  end

  def b(arg)
     puts "b was called with #{arg}"
  end

  def c(arg)
    puts "c was called with #{arg}"
  end
end

Is it possible to do such thing ? I would like to avoid procs/lambdas because I want to be able to change the behaviour of A,B,C by subclassing .

LastEditorDisplayName: John Topley

Body:
You can get a reference to the method by object.method(:method_name).

Eg: To get a reference to system method.

m = self.method(:system)
m.call('ls')

ContentLicense: CC BY-SA 4.0


问:
Unable to load DLL 'Microsoft.Azure.Documents.ServiceInterop.dll' [using Microsoft.Azure.DocumentDB 1.17.0]
I am using Microsoft.Azure.DocumentDB 1.17.0 in my project and getting below error. "ServiceInterop.dll" Dll is present in the folder which has Microsoft.Azure.DocumentDB dll. But still getting below error</p>

```<code>System.AggregateException: One or more errors occurred. ---> System.DllNotFoundException: Unable to load DLL 'Microsoft.Azure.Documents.ServiceInterop.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at Microsoft.Azure.Documents.ServiceInteropWrapper.CreateServiceProvider(String configJsonString, IntPtr& serviceProvider)
   at Microsoft.Azure.Documents.Query.QueryPartitionProvider.Initialize()
   at Microsoft.Azure.Documents.Query.QueryPartitionProvider.GetPartitionedQueryExecutionInfoInternal(SqlQuerySpec querySpec, PartitionKeyDefinition partitionKeyDefinition, Boolean requireFormattableOrderByQuery, Boolean isContinuationExpected)
    at Microsoft.Azure.Documents.Query.DocumentQueryExecutionContextBase.<GetPartitionedQueryExecutionInfoAsync>d__0.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.Azure.Documents.Query.DocumentQueryExecutionContextFactory.<CreateDocumentQueryExecutionContextAsync>d__5.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Documents.Linq.DocumentQuery`1.<CreateDocumentQueryExecutionContextAsync>d__12.MoveNext()
    --- End of inner exception stack trace ---
    at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
    at Microsoft.Azure.Documents.Linq.DocumentQuery`1.<GetEnumerator>d__b.MoveNext()
    at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
</code>```

答: Yes, this is a strange issue I also observed. For some reason CLR complains about Microsoft.Azure.Documents.ServiceInterop.dll being missing even though it's actually one of it's dependencies DocumentDB.Spatial.Sql.dll is missing. Please make sure that both these native dlls are present.</p>

Body:
I am using Microsoft.Azure.DocumentDB 1.17.0 in my project and getting below error. "ServiceInterop.dll" Dll is present in the folder which has Microsoft.Azure.DocumentDB dll. But still getting below error

System.AggregateException: One or more errors occurred. ---> System.DllNotFoundException: Unable to load DLL 'Microsoft.Azure.Documents.ServiceInterop.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at Microsoft.Azure.Documents.ServiceInteropWrapper.CreateServiceProvider(String configJsonString, IntPtr& serviceProvider)
   at Microsoft.Azure.Documents.Query.QueryPartitionProvider.Initialize()
   at Microsoft.Azure.Documents.Query.QueryPartitionProvider.GetPartitionedQueryExecutionInfoInternal(SqlQuerySpec querySpec, PartitionKeyDefinition partitionKeyDefinition, Boolean requireFormattableOrderByQuery, Boolean isContinuationExpected)
    at Microsoft.Azure.Documents.Query.DocumentQueryExecutionContextBase.<GetPartitionedQueryExecutionInfoAsync>d__0.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.Azure.Documents.Query.DocumentQueryExecutionContextFactory.<CreateDocumentQueryExecutionContextAsync>d__5.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Documents.Linq.DocumentQuery`1.<CreateDocumentQueryExecutionContextAsync>d__12.MoveNext()
    --- End of inner exception stack trace ---
    at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
    at Microsoft.Azure.Documents.Linq.DocumentQuery`1.<GetEnumerator>d__b.MoveNext()
    at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)


问:
Array of hashes whose key is an array containing ranges
I need to map a number of IDs and ranges of IDs to single values. I would like to store the whole structure in one object.

Is the following a sensible way to do this? What is the best way to search the keys by a single integer value to return the corresponding value?

```<code>large array = [
   {[3110..3220, 10200, 43680] =>   'A0300'},
   {[5200, 7100..8990, 9100..9900] => 'B0400'},
   {[17110..18121, 20160, 2210..22290] => 'C0600'}
]
</code>```

答:
Reasonable format to store the data would be a plain old simple hash:

```<code>input = { [3110..3220, 10200, 43680] =>  'A0300',
          [5200, 7100..8990, 9100..9900] => 'B0400',
          [17110..18121, 20160, 2210..22290] => 'C0600' }
</code>```

To lookup the element one might use case-equal aka triple-equal. Luckily it’s implemented for integers as well:

```<code>value = 7300
result = input.detect { |k, _| k.any? { |r| r === value } }
result ? result.last : nil
#⇒ "B0400"
</code>```

Body:
I need to map a number of IDs and ranges of IDs to single values. I would like to store the whole structure in one object.

Is the following a sensible way to do this? What is the best way to search the keys by a single integer value to return the corresponding value?

large array = [
   {[3110..3220, 10200, 43680] =>   'A0300'},
   {[5200, 7100..8990, 9100..9900] => 'B0400'},
   {[17110..18121, 20160, 2210..22290] => 'C0600'}
]

Body:
Reasonable format to store the data would be a plain old simple hash:

input = { [3110..3220, 10200, 43680] =>  'A0300',
          [5200, 7100..8990, 9100..9900] => 'B0400',
          [17110..18121, 20160, 2210..22290] => 'C0600' }

To lookup the element one might use case-equal aka triple-equal. Luckily it’s implemented for integers as well:

value = 7300
result = input.detect { |k, _| k.any? { |r| r === value } }
result ? result.last : nil
#⇒ "B0400"


问:
Ionic 3: ion-img not loading in ion-list
I have a pretty basic image list using [virtualScroll] and ion-img. An array named album is used as the source of the list.

```<code><ion-list [virtualScroll]="album">
   <ion-item *virtualItem="let image">
      <ion-thumbnail item-start>
         <ion-img
         [src]="image.nativeURL"
         (click)="photoViewer.show(image.nativeURL, image.name, { share: false })">
         </ion-img>
      </ion-thumbnail>
      <p>
         <b>{{ image.name }}</b><br />
         {{ image.size | filesize }}<br />
         {{ image.modificationTime }}<br />
      </p>
      <ion-icon name="close" item-right (click)="deleteImage(i)"></ion-icon>
   </ion-item>
</ion-list>
</code>```

The list scrolls smoothly, but the images don't always load, despite all of them are local images. Some do, some don't, apparently randomly. This is what it looks like:

https://snag.gy/6BpISl.jpg

Why?

答:
All right, here's the solution. And it may sound ridiculous.

Just ditch ion-img and use img. It will scroll just as smoothly, and will not disappear.

However, I don't know how it'll work with hundreds of images.

Good thing Ionic has a half baked solution for everything, and none can be used!

Body:
I have a pretty basic image list using [virtualScroll] and ion-img. An array named album is used as the source of the list.

<ion-list [virtualScroll]="album">
   <ion-item *virtualItem="let image">
      <ion-thumbnail item-start>
         <ion-img
         [src]="image.nativeURL"
         (click)="photoViewer.show(image.nativeURL, image.name, { share: false })">
         </ion-img>
      </ion-thumbnail>

         {{ image.name }}

         {{ image.size | filesize }}

         {{ image.modificationTime }}

      <ion-icon name="close" item-right (click)="deleteImage(i)"></ion-icon>
   </ion-item>
</ion-list>

The list scrolls smoothly, but the images don't always load, despite all of them are local images. Some do, some don't, apparently randomly. This is what it looks like:

https://snag.gy/6BpISl.jpg

Why?


问:
How to recover a messed-up git submodule?
I git submodule add'ed a submodule at a wrong directory.

I git rm'ed the submodule and then git submodule summary returned fatal: Not a git repository: '<path to the deleted submodule>.git'.

I used grep -r '<path to the deleted submodule>' to remove all references to the deleted directory.

There was only one reference left to the deleted directory, which was in .git/index (binary file).

But git submodule summary still gives fatal: Not a git repository: '<path to the deleted submodule>.git'.

How should I fix it?

答:
Double-check:

the content of your .gitmodules file

the content of .git/modules subfolder

If you remove any reference of the submodule you git rm'ed, that should be better.

Also, make sure you try again a git rm mysubmodule, without any trailing slash.


问:
In this node definition, why are we using the "Node" after the structure definition?
```<code>typedef struct node
{
 int data;
 struct node *next;
}Node;  // ???
</code>```

<p>I don't understand why we use the Node after the definition. What function does is perform? Does it prevent the structure from pointing to itself infinitely?
Question might sound stupid, by i'm still learning.
Thanks. </p>

答:
There's a Node after the structure definition, because there's a typedef before it.

The structure definition by itself would be this:

```<code>struct node
{
  int data;
  struct node *next;
};
</code>```

Since this is C++, that would be enough to refer to the structure type by the name node. However it seems the person who wrote it is originally either from a C background, or aiming to provide a C compatible header. In C, you'd have to refer it as struct node, which some find verbose. So the person in question immediately provided a type alias. The code you presented is equivalent to:

```<code>struct node
{
  int data;
  struct node *next;
};

typedef struct node Node;
</code>```

And it allows us to refer to the same type by the name Node, in either C or C++.

Body:
typedef struct node
{
 int data;
 struct node *next;
}Node;  // ???

I don't understand why we use the Node after the definition. What function does is perform? Does it prevent the structure from pointing to itself infinitely?
Question might sound stupid, by i'm still learning.
Thanks.

Body:
There's a Node after the structure definition, because there's a typedef before it.

The structure definition by itself would be this:

struct node
{
  int data;
  struct node *next;
};

Since this is C++, that would be enough to refer to the structure type by the name node. However it seems the person who wrote it is originally either from a C background, or aiming to provide a C compatible header. In C, you'd have to refer it as struct node, which some find verbose. So the person in question immediately provided a type alias. The code you presented is equivalent to:

struct node
{
  int data;
  struct node *next;
};

typedef struct node Node;

And it allows us to refer to the same type by the name Node, in either C or C++.


问:
Create table in PostgresQL 9.1 from JSON
I am wanting to create a table in PostgresQL 9.1 from a JSON.

I have created a table from a CSV now trying to do it from a JSON.

Am I able to do this?

The JSON looks like this:

```<code>{
    'id': 234345346,
    'account_id': 34664,
    'address': '11 Long St, Frankston VIC 3443, Australia',
    'category_id': 125051,
    'description': None,
    'is_anonymous': False,
    'iso_created_at': '2017-05-24T10:15:48+10:00',
    'location': {
        'latitude': -31.6445645669669,
        'longitude': 152.80345668635
     },
     'report_state_id': 124566958,
     'title': 'Small stack 2012',
     'user_id': 564777,
     'shape_id': None
}
</code>```

Thanks in advance

答:
PostgreSQL only started supporting JSON in 9.2, so you'll need to update.

Source

If you're unable to upgrade, there is a backport called json91 which can be found here: https://bitbucket.org/adunstan/json_91

But you really should upgrade instead of relying on this.

Also this is not valid JSON.

JSON has no type None. A common use for a key with no value is null

In JSON, values must be one of the following data types:

a string

a number

an object (JSON object)

an array

a boolean

null

Source

Secondly, and I believe this depends on what actually receives your data, JSON doesn't allow for single quoted strings.

You can read the spec for JSON here: http://www.json.org/

Body:
I am wanting to create a table in PostgresQL 9.1 from a JSON.

I have created a table from a CSV now trying to do it from a JSON.

Am I able to do this?

The JSON looks like this:

{
    'id': 234345346,
    'account_id': 34664,
    'address': '11 Long St, Frankston VIC 3443, Australia',
    'category_id': 125051,
    'description': None,
    'is_anonymous': False,
    'iso_created_at': '2017-05-24T10:15:48+10:00',
    'location': {
        'latitude': -31.6445645669669,
        'longitude': 152.80345668635
     },
     'report_state_id': 124566958,
     'title': 'Small stack 2012',
     'user_id': 564777,
     'shape_id': None
}

Thanks in advance


问:
How to count words in a file using python >2.0
I want to write a program that can count keywords in a file.
Example: I created a list, with the following keywords. Then I open a file with bunch of words, and I want to count how many keywords are there in the file. But no matter what I do, the count will always give me 0. What did I do wrong?

Here is my code:

```<code>Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite',
         'excites', 'exciting', 'glad', 'greatest', 'happy', 'love',
         'loves', 'loved', 'loving', 'lovin', 'prettiest']

def CountFile():
  file = open("File.txt", "r")
  Count = 0
  for i in file:
    i = i.split()
    if i in Happy:
      count = count + 1
  print("there are" count "keywords")
  return

CountFile()
</code>```

答:
When you do i = i.split()

i becomes a list. Your i variable is a line in your text file here.

You can probably do,

```<code>   ...
   words = i.split()
   for w in words:
     if w in Happy:
       count += 1
   ...
</code>```

Body:
I want to write a program that can count keywords in a file.
Example: I created a list, with the following keywords. Then I open a file with bunch of words, and I want to count how many keywords are there in the file. But no matter what I do, the count will always give me 0. What did I do wrong?

Here is my code:

Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite',
         'excites', 'exciting', 'glad', 'greatest', 'happy', 'love',
         'loves', 'loved', 'loving', 'lovin', 'prettiest']

def CountFile():
  file = open("File.txt", "r")
  Count = 0
  for i in file:
    i = i.split()
    if i in Happy:
      count = count + 1
  print("there are" count "keywords")
  return

CountFile()

Body:
When you do i = i.split()

i becomes a list. Your i variable is a line in your text file here.

You can probably do,

   ...
   words = i.split()
   for w in words:
     if w in Happy:
       count += 1
   ...


答:
No. There is no need to separate each key-value pair into a different hash as you did. Furthermore, you are using the hash in a wrong way. A hash key-value need not be one-to-one. It is better to have something like this:

```<code>{
  3110..3220 => 'A0300',
  10200 => 'A0300',
  43680 => 'A0300',
  5200 => 'B0400',
  7100..8990 => 'B0400',
  9100..9900 => 'B0400',
  17110..18121 => 'C0600',
  20160 => 'C0600',
  2210..22290 => 'C0600',
}
</code>```

But my guess is that you are actually asking a X-Y question, and my answer above is still not the best solution for you.

Title: Array of hashes whose key is an array containing ranges

Body:
No. There is no need to separate each key-value pair into a different hash as you did. Furthermore, you are using the hash in a wrong way. A hash key-value need not be one-to-one. It is better to have something like this:

{
  3110..3220 => 'A0300',
  10200 => 'A0300',
  43680 => 'A0300',
  5200 => 'B0400',
  7100..8990 => 'B0400',
  9100..9900 => 'B0400',
  17110..18121 => 'C0600',
  20160 => 'C0600',
  2210..22290 => 'C0600',
}

But my guess is that you are actually asking a X-Y question, and my answer above is still not the best solution for you.


问:
How to get the ldap url for an AWS Simple AD deployment
I have an AWS Simple AD deployment. I need the ldap_url. I have seen it represented in various forms such as simply ldap://example.com and also ldap://aws-[some-mysterious-id].whatever.com and even in some AWS documentation they simply use the LAN IP of one of the instances, which I can't find anywhere in the AWS console since the EC2 console hides your Simple AD servers just like it does not show your RDS instances either.

When using ldapsearch to query against the value represented by "Directory name" in the AWS Console for Directory Services, the result is ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1), so it does not appear to be that either.

答:
Go to the AWS Directory Service console https://console.aws.amazon.com/directoryservice/home

Select your directory.

Under DNS address will be two IP addresses.

Note that these addresses are private IP addresses in your VPC.

If you need public Internet access to your Simple AD server, then put an ELB -> HA Proxy -> Simple AD in front. Add Route53 to provide a DNS name.


问:
How to iterate a list within a list into columns?
Suppose I have a list of numbers divided into 3 lists:

```<code>numbers = [[0,1,2], [3,4,5], [6,7,8]]
</code>```

And I want to iterate through each 3 lists and divide them into columns:

```<code>0  1  2
3  4  5
6  7  8
</code>```

How would I go about doing this?
So far, I can only print out 1 column:

```<code>for column in numbers[0:3]:
    column1 = column[0]
    print( column1 )
</code>```

答:
You can just use your code and add

```<code>column1 = column[0,:]
</code>```

result: [0,1,2]
or

```<code>column1 = column[:,0]
</code>```

result: [0,3,6]

Body:
Suppose I have a list of numbers divided into 3 lists:

numbers = [[0,1,2], [3,4,5], [6,7,8]]

And I want to iterate through each 3 lists and divide them into columns:

0  1  2
3  4  5
6  7  8

How would I go about doing this?
So far, I can only print out 1 column:

for column in numbers[0:3]:
    column1 = column[0]
    print( column1 )

Body:
You can just use your code and add

column1 = column[0,:]

result: [0,1,2]
or

column1 = column[:,0]

result: [0,3,6]


问:
Push elements dynamically using javascript
I am getting the points from the multidimensional array using map, but I am getting array of array values.

I need the below format:

```<code>[36, 122, 25]
</code>```

But I'm getting the multi array of points.

Below is my code and output

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]

var result = data.map(function(arr, count) {
  return [arr.points];
});

console.log(result);```
</div>
</div>
</p>

<p>output is:</p>

```[[36], [122], [25]]
```

答:
Try below code:   </p>

```<code>var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) {  return arr.points;});
console.log(result);
</code>```

Body:
I am getting the points from the multidimensional array using map, but I am getting array of array values.

I need the below format:

[36, 122, 25]

But I'm getting the multi array of points.

Below is my code and output

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]

var result = data.map(function(arr, count) {
  return [arr.points];
});

console.log(result);

output is:

[[36], [122], [25]]

Body:
Try below code:

var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) {  return arr.points;});
console.log(result);


问:
Algorithm for detecting peaks from recorded, noisy data. Graphs inside
So I've recorded some data from an Android GPS, and I'm trying to find the peaks of these graphs, but I haven't been able to find anything specific, perhaps because I'm not too sure what I'm looking for.  I have found some MatLab functions, but I can't find the actual algorithms that do it.  I need to do this in Java, but I should be able to translate code from other languages.

As you can see, there are lots of 'mini-peaks', but I just want the main ones.

答:
I think what you want to do is run this through some sort of low-pass filter.  Depending on exactly what you want to get out of this dataset, a simple "box car" filter might be
sufficient:  at each point, take the average of the N samples centered on that point,
and take the average as the filtered value.  The larger N is, the more aggressively smoothed the filtered data will be.</p>


答:
var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
            {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
            {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) {  return arr.points;});
console.log(result);```

Remove the [] from return statement. It creates new array and push it to original.

Title: Push elements dynamically using javascript

Body:
var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
            {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
            {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) {  return arr.points;});
console.log(result);

Remove the [] from return statement. It creates new array and push it to original.


问:
Trouble with TensorFlow in Jupyter Notebook
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. The Anaconda install works, but I need to preface any call to python with "source activate tensorflow". And the pip install works nicely, if start python the standard way (in the terminal) then tensorflow loads just fine.

My question is: how can I also have it work in the Jupyter notebooks?

This leads me to a more general question: it seems that my python kernel in Jupyter/Anaconda is separate from the python kernel (or environment? not sure about the terminology here) used system wide. It would be nice if these coincided, so that if I install a new python library, it becomes accessible to all the varied ways I have of running python.

答:
i used these following which in virtualenv.

```<code>pip3 install --ignore-installed ipython
pip3 install --ignore-installed jupyter
</code>```

This re-installs both ipython and jupyter notebook in my tensorflow virtual environment. You can verify it after installation by which ipython and which jupyter. The bin will be under the virtual env.

NOTE I am using python 3.*

Body:
i used these following which in virtualenv.

pip3 install --ignore-installed ipython
pip3 install --ignore-installed jupyter

This re-installs both ipython and jupyter notebook in my tensorflow virtual environment. You can verify it after installation by which ipython and which jupyter. The bin will be under the virtual env.

NOTE I am using python 3.*


问:
How do I scrape the date links off this website: https://flight-data.adsbexchange.com/activity?inputSelect=registration&registration=N12345
I am trying to print the dates which come up as a list of links at the bottom of this website. I do not know what is going wrong as no errors flash up. I have tried simpler approaches which work for websites such as the NY times to retrieve all their hrefs. However these did not work and so I looked into User Agent.    </p>

```<code>import urllib
import lxml.html
import urllib2
from urllib import URLopener

URLopener.version
from urllib import FancyURLopener
class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
MyOpener.version
myopener = MyOpener()
page = myopener.open('https://flight-data.adsbexchange.com/activity?inputSelect=registration&registration=N12345')
page.read()
from bs4 import BeautifulSoup
soup = BeautifulSoup(page, "lxml")
for line in soup.find_all('a'):
    print(line.get('href'))
</code>```

答:
Execute the below script. It will give you all the desired links:

```<code>from bs4 import BeautifulSoup
from urllib.parse import urljoin
import requests

page_url = "https://flight-data.adsbexchange.com/activity?inputSelect=registration&registration=N12345"
page = requests.get(page_url).text
soup = BeautifulSoup(page, "lxml")
for items in soup.select(".dates"):
    print(urljoin(page_url,items['href']))
</code>```

Partial output:

```<code>https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-11-14
https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-11-09
https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-11-08
https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-11-05
https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-10-31
</code>```

Body:
I am trying to print the dates which come up as a list of links at the bottom of this website. I do not know what is going wrong as no errors flash up. I have tried simpler approaches which work for websites such as the NY times to retrieve all their hrefs. However these did not work and so I looked into User Agent.

import urllib
import lxml.html
import urllib2
from urllib import URLopener

URLopener.version
from urllib import FancyURLopener
class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
MyOpener.version
myopener = MyOpener()
page = myopener.open('https://flight-data.adsbexchange.com/activity?inputSelect=registration&registration=N12345')
page.read()
from bs4 import BeautifulSoup
soup = BeautifulSoup(page, "lxml")
for line in soup.find_all('a'):
    print(line.get('href'))

Body:
Execute the below script. It will give you all the desired links:

from bs4 import BeautifulSoup
from urllib.parse import urljoin
import requests

page_url = "https://flight-data.adsbexchange.com/activity?inputSelect=registration&registration=N12345"
page = requests.get(page_url).text
soup = BeautifulSoup(page, "lxml")
for items in soup.select(".dates"):
    print(urljoin(page_url,items['href']))

Partial output:

https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-11-14
https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-11-09
https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-11-08
https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-11-05
https://flight-data.adsbexchange.com/map?icao=A061D9&date=2017-10-31


问:
Exception in thread "main" java.util.scanner
```<code>What is the result?
10 - 7 =
3
Congratulations, you got it correct!
Exception in thread "main" What is the result?
9 + 8 =
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at proj3.Project4App.main(Project4App.java:28)
</code>```

When I run my code I'm getting the first loop to go through with my scanner, but then I run into an error. I'm not sure what I'm doing wrong? I need to have the loop go until 10 questions are answered correctly, 20 are answered overall, or the average of correct answers is over 85%.

```<code>package proj3;
import java.util.Scanner;
import java.util.Random;

/**
 * <p> Title: Project 4: The Project4App Class </p>
 * <p> Description: Creates an math game for children </p>
 * @author Justin Abeles
 */

public class Project4App {
    /**
     * <p> Name: main method </p>
     *
     * @param args values to be sent to the method
     */
public static void main(String args[]){

    int addCorrect = 0;
    int addWrong = 0;
    int subCorrect = 0;
    int subWrong = 0;

    while(true){
        Question quiz = new Question();
        Scanner scan = new Scanner(System.in);
        System.out.println("What is the result?\n" + quiz.toString());
        int age = scan.nextInt();
        int answer = quiz.determineAnswer();
        char operator = quiz.getOperator();
        if(age == answer && operator == '+')
            System.out.println("Congratulations, you got it correct!");
        if((age == answer) && (operator == '-'))
            System.out.println("Congratulations, you got it correct!");
        if((age != answer) && (operator == '+'))
            System.out.println("The correct answer for " + quiz.toString() + " is " + quiz.determineAnswer());
        if((age != answer) && (operator == '-'))
            System.out.println("The correct answer for " + quiz.toString() + " is " + quiz.determineAnswer());

        if(age == answer && operator == '+')
            addCorrect = addCorrect + 1;
        else if(age == answer && operator == '-')
            subCorrect = subCorrect + 1;
        else if(age != answer && operator == '+')
            addWrong = addWrong + 1;
        else
            subWrong = subWrong + 1;
        scan.close();
    }
}
</code>```

}

答: Take Scanner scan = new Scanner(System.in); out of your cycle. Do the same to scan.close;, put it right before exiting your main function. When you close your Scanner, it also closes its source. It maybe the reason of your exception.

Body:
What is the result?
10 - 7 =
3
Congratulations, you got it correct!
Exception in thread "main" What is the result?
9 + 8 =
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at proj3.Project4App.main(Project4App.java:28)

When I run my code I'm getting the first loop to go through with my scanner, but then I run into an error. I'm not sure what I'm doing wrong? I need to have the loop go until 10 questions are answered correctly, 20 are answered overall, or the average of correct answers is over 85%.

package proj3;
import java.util.Scanner;
import java.util.Random;

/**
 *
 Title: Project 4: The Project4App Class

 *
 Description: Creates an math game for children

 * @author Justin Abeles
 */

public class Project4App {
    /**
     *
 Name: main method

     *
     * @param args values to be sent to the method
     */
public static void main(String args[]){

    int addCorrect = 0;
    int addWrong = 0;
    int subCorrect = 0;
    int subWrong = 0;

    while(true){
        Question quiz = new Question();
        Scanner scan = new Scanner(System.in);
        System.out.println("What is the result?\n" + quiz.toString());
        int age = scan.nextInt();
        int answer = quiz.determineAnswer();
        char operator = quiz.getOperator();
        if(age == answer && operator == '+')
            System.out.println("Congratulations, you got it correct!");
        if((age == answer) && (operator == '-'))
            System.out.println("Congratulations, you got it correct!");
        if((age != answer) && (operator == '+'))
            System.out.println("The correct answer for " + quiz.toString() + " is " + quiz.determineAnswer());
        if((age != answer) && (operator == '-'))
            System.out.println("The correct answer for " + quiz.toString() + " is " + quiz.determineAnswer());

        if(age == answer && operator == '+')
            addCorrect = addCorrect + 1;
        else if(age == answer && operator == '-')
            subCorrect = subCorrect + 1;
        else if(age != answer && operator == '+')
            addWrong = addWrong + 1;
        else
            subWrong = subWrong + 1;
        scan.close();
    }
}

}


答:
The function is returning an array of single-element arrays because .map() returns an array, and within each iteration of .map() your function is returning [arr.points] (an element in an array). Change this to return arr.points and you're set.

Also, since you're merely returning a value in the .map() we can simplify the callback function to:

```<code>var result = data.map(arr => arr.points);
</code>```

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]
var result = data.map(arr => arr.points);
console.log(result);```

Body:
The function is returning an array of single-element arrays because .map() returns an array, and within each iteration of .map() your function is returning [arr.points] (an element in an array). Change this to return arr.points and you're set.

Also, since you're merely returning a value in the .map() we can simplify the callback function to:

var result = data.map(arr => arr.points);

var data = [{
    "name": "ramu",
    "id": "719",
    "gmail": "ramu@gmail.com",
    "ph": 988989898,
    "points": 36
  },
  {
    "name": "ravi",
    "id": "445",
    "gmail": "ravi@gmail.com",
    "ph": 4554545454,
    "points": 122
  },
  {
    "name": "karthik",
    "id": "866",
    "gmail": "karthik@gmail.com",
    "ph": 2332233232,
    "points": 25
  }
]
var result = data.map(arr => arr.points);
console.log(result);


问:
How do I find the number of common numbers occurring in 2nd array?
commonCount(ar1, ar2)

if arr1 = [1,1,2,3,3] and arr2 = [1,4,3,1,1], the answer is 3

My thought process:

initialize accumulator

iterate through arr1

if arr1[i] is in the arr2, add 1 to the accumulator

remove the arr1[i] from arr2 (because don't want to have duplicate if the number already exist)

return accumulator

1) How do I check if arr1[i] is in the arr2?

2) How do I remove arr1[i] from arr2?

答:
console.log([1,2,3,4,5].filter((n) => [1,1,2,10,11].includes(n)))```
</div>
</div>
</p>

<p>This is the code to calculate the intersection.</p>

<p>to filter them out you will do this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log([1,1,2,10,11].filter((n) => ![1,2,3,4,5].includes(n)))</code>```

To remove an element x from an array arr we can do this

    var array = [1,2,3];
    var index = array.indexOf(3);
    if( index >= 0)
       array.splice(index,1);```

Removing an element also answers your question on how to check if the elements exist in the array.

Body:
console.log([1,2,3,4,5].filter((n) => [1,1,2,10,11].includes(n)))

This is the code to calculate the intersection.

to filter them out you will do this

console.log([1,1,2,10,11].filter((n) => ![1,2,3,4,5].includes(n)))

To remove an element x from an array arr we can do this

    var array = [1,2,3];
    var index = array.indexOf(3);
    if( index >= 0)
       array.splice(index,1);

Removing an element also answers your question on how to check if the elements exist in the array.


问:
How to group subarray data using multiple column values and individually sum the remaining column values?
How can I group by Source and date then SUM Pageviews and revenue this array below

```<code>Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6000
            [Pageviews] => 12,214
            [Revenue] => 25
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1015
            [Revenue] => 10
        )
    [2] => Array
          (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )

    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )

    [4] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 1600
            [Pageviews] => 11,445
            [Revenue] => 5
        )
     [5] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 700
            [Pageviews] => 7,445
            [Revenue] => 8
        )
)
</code>```

Expected Result

```<code>Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6600
            [Pageviews] => 13,229
            [Revenue] => 35
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )
    [2] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )
    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 2,300
            [Pageviews] => 18,890
            [Revenue] => 35
        )
)
</code>```

答:
Assuming there is only one Source index.

Try this:

```<code>array_multisort(array_column($arr, 'Date'), SORT_DESC,array_column($arr, 'Source'), SORT_DESC, $arr);

$new_arr = [];
$temp = ["Date"=>""];
$ctr = 0;
foreach($arr as $val) {
    if($val["Date"] == $temp["Date"] && $val["Source"] == $temp["Source"]) {
        $ctr2 = $ctr - 1;
        $new_arr[$ctr2]["visits"] += $val["visits"];
        $new_arr[$ctr2]["Pageviews"] += $val["Pageviews"];
        $new_arr[$ctr2]["Revenue"] += $val["Revenue"];
    } else {
        $new_arr[$ctr++] = $val;
    }
    $temp = $val;
}

print_r($new_arr);
</code>```

Body:
How can I group by Source and date then SUM Pageviews and revenue this array below

Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6000
            [Pageviews] => 12,214
            [Revenue] => 25
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1015
            [Revenue] => 10
        )
    [2] => Array
          (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )

    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )

    [4] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 1600
            [Pageviews] => 11,445
            [Revenue] => 5
        )
     [5] => Array
         (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 700
            [Pageviews] => 7,445
            [Revenue] => 8
        )
)

Expected Result

Array
(
    [0] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Google
            [visits] => 6600
            [Pageviews] => 13,229
            [Revenue] => 35
        )
    [1] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-31
            [Source] => Facebook
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 40
        )
    [2] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Google
            [visits] => 600
            [Pageviews] => 1144
            [Revenue] => 10
        )
    [3] => Array
        (
            [Source] => Analytics
            [Date] => 2017-10-30
            [Source] => Facebook
            [visits] => 2,300
            [Pageviews] => 18,890
            [Revenue] => 35
        )
)

Body:
Assuming there is only one Source index.

Try this:

array_multisort(array_column($arr, 'Date'), SORT_DESC,array_column($arr, 'Source'), SORT_DESC, $arr);

$new_arr = [];
$temp = ["Date"=>""];
$ctr = 0;
foreach($arr as $val) {
    if($val["Date"] == $temp["Date"] && $val["Source"] == $temp["Source"]) {
        $ctr2 = $ctr - 1;
        $new_arr[$ctr2]["visits"] += $val["visits"];
        $new_arr[$ctr2]["Pageviews"] += $val["Pageviews"];
        $new_arr[$ctr2]["Revenue"] += $val["Revenue"];
    } else {
        $new_arr[$ctr++] = $val;
    }
    $temp = $val;
}

print_r($new_arr);


问:
Compiler error for Haskell program not understood
I'm working on a large Haskell program, so I'm only including the code that seems relevant here to make the problem clearer.  Please comment if I should include more.

When I compile, I get only one error message: "parse error (possibly incorrect indentation or mismatched brackets)"

Here is some code with no errors (printStmt) and a very similar section (VarDeclStmt) with the error directed at the line reading, "expr >>= \s ->".  I don't see why one would be fine and the other would cause a problem.  In what way are they different?

```<code>printStmt =
            keyword "print" >>
            expr >>= \e ->
            symbol ";" >>
            return (Print e)

varDeclStmt = do
              keyword "var" >>
              expr >>= \s -> --ERROR
              symbol "=" >>
              expr >>= \e ->
              return (VarDecl s e)
</code>```

答:
The indentation error has to do with the do block. Try indenting after the do. Something like:

```<code>varDeclStmt = do
                keyword "var" >>
                expr >>= \s ->
                symbol "=" >>
                expr >>= \e ->
                return (VarDecl s e)
</code>```

Let me know if that works.

Body:
I'm working on a large Haskell program, so I'm only including the code that seems relevant here to make the problem clearer.  Please comment if I should include more.

When I compile, I get only one error message: "parse error (possibly incorrect indentation or mismatched brackets)"

Here is some code with no errors (printStmt) and a very similar section (VarDeclStmt) with the error directed at the line reading, "expr >>= \s ->".  I don't see why one would be fine and the other would cause a problem.  In what way are they different?

printStmt =
            keyword "print" >>
            expr >>= \e ->
            symbol ";" >>
            return (Print e)

varDeclStmt = do
              keyword "var" >>
              expr >>= \s -> --ERROR
              symbol "=" >>
              expr >>= \e ->
              return (VarDecl s e)

Body:
The indentation error has to do with the do block. Try indenting after the do. Something like:

varDeclStmt = do
                keyword "var" >>
                expr >>= \s ->
                symbol "=" >>
                expr >>= \e ->
                return (VarDecl s e)

Let me know if that works.


问:
How can I inject dependencies into a custom ILogger in asp.net core 2.0?
In asp.net core 1.1 I could inject the IServiceProvider into the logger provider and resolve my logger when CreateLogger was called, but it all changed in asp.net core 2.0

My ILogger implementation needs dependencies injected.
How can I achieve this?

答:
ASP.NET core provides possibility to replace built-in DI container with custom one (see this article for details). You could use this possibility to obtain instance of IServiceProvider earlier for logging bootstrapping while still using standard .Net core DI container.

To do this you should change return value of Startup.ConfigureServices(IServiceCollection services) method from void to IServiceProvider. You can use this possibility to build instance of IServiceProvider in ConfigureServices, use it for logging bootstrapping and then return from the method.

Sample code:

```<code>public interface ISomeDependency
{
}

public class SomeDependency : ISomeDependency
{
}

public class CustomLogger : ILogger
{
    public CustomLogger(ISomeDependency dependency)
    {
    }

    //  ...
}

public class CustomLoggerProvider : ILoggerProvider
{
    private readonly IServiceProvider serviceProvider;

    public CustomLoggerProvider(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public ILogger CreateLogger(string categoryName)
    {
        return serviceProvider.GetRequiredService<ILogger>();
    }

    //  ...
}

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        return ConfigureLogging(services);
    }

    private IServiceProvider ConfigureLogging(IServiceCollection services)
    {
        services.AddTransient<ISomeDependency, SomeDependency>();
        services.AddSingleton<ILogger, CustomLogger>();
        IServiceProvider serviceProvider = services.BuildServiceProvider();

        var loggerFactory = new LoggerFactory();
        loggerFactory.AddProvider(new CustomLoggerProvider(serviceProvider));

        return serviceProvider;
    }

    //  ...
}
</code>```

Body:
ASP.NET core provides possibility to replace built-in DI container with custom one (see this article for details). You could use this possibility to obtain instance of IServiceProvider earlier for logging bootstrapping while still using standard .Net core DI container.

To do this you should change return value of Startup.ConfigureServices(IServiceCollection services) method from void to IServiceProvider. You can use this possibility to build instance of IServiceProvider in ConfigureServices, use it for logging bootstrapping and then return from the method.

Sample code:

public interface ISomeDependency
{
}

public class SomeDependency : ISomeDependency
{
}

public class CustomLogger : ILogger
{
    public CustomLogger(ISomeDependency dependency)
    {
    }

    //  ...
}

public class CustomLoggerProvider : ILoggerProvider
{
    private readonly IServiceProvider serviceProvider;

    public CustomLoggerProvider(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public ILogger CreateLogger(string categoryName)
    {
        return serviceProvider.GetRequiredService<ILogger>();
    }

    //  ...
}

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        return ConfigureLogging(services);
    }

    private IServiceProvider ConfigureLogging(IServiceCollection services)
    {
        services.AddTransient<ISomeDependency, SomeDependency>();
        services.AddSingleton<ILogger, CustomLogger>();
        IServiceProvider serviceProvider = services.BuildServiceProvider();

        var loggerFactory = new LoggerFactory();
        loggerFactory.AddProvider(new CustomLoggerProvider(serviceProvider));

        return serviceProvider;
    }

    //  ...
}


问:
My Work Items gone in TFS
We use VS2008 with TFS for source control at my workplace and it works fine, however today we experienced a problem when trying to associate our pending changes with a work item.
Usually when I want to associate changes with a work item I just go to the second tab from the top in the "pending changes" window, check the work item that fits the changes and check in. Today however, all my work items were gone from the list. I can select a suitable query from the drop down box and this works fine, so the projects are there.

I think the problem might have something to do with the "My Work Items" query being associated with the wrong TFS project (there are two on our TFS-server) but I don't know how to fix this. The same problem occurred for most of my colleagues with some (possible) variations.

So... how do I restore "My Work Items" to the pending changes window?

EDIT: The problem still persists in a way but I worked my way around it by removing the second project in the Team Explorer. This is acceptable (for now) since that project is not currently active. I am not content with this being a good long term solution, however...

EDIT: I know that I may not have provided enough information for anyone to understand what really is the problem, still, I'll keep it up for now in case someone has had the same problem and knows how to fix it :P

答: Close all instances of visual studio and try this in the comandline: "devenv.exe /resetuserdata"</p>

OwnerDisplayName: Sakkle

Title: My Work Items gone in TFS

LastEditorDisplayName: Sakkle

OwnerDisplayName: Orkun Balkancı

LastEditorDisplayName: Orkun Balkancı


问:
Heroku Postgres add-on connection string for Nodejs app
I have a problem deploying a Nodejs app with a Postgresql database. The database comes from Heroku itself (Heroku Postgres add-on, hobby-dev). My app refused to connect to the database.

I found where the problem came from but I can't find a clean solution. And I think I could have misunderstood something (I'm new to Node and Heroku).

Heroku automatically gives me an environment variable DATABASE_CONFIG that includes the port:

```<code>postgres://username:password@hostname:port/databasename
</code>```

Then, to connect with pg in my app, I use process.env.DATABASE_CONFIG as a connection string. I do something like:

```<code>const client = new Client({
    connectionString: connectionString,
})
client.connect()
</code>```

This fails to connect.

But if instead of using this environment variable, I cheat and change it, removing the port number from this connection string, it works.

I don't know why but the problem is that Heroku gives you this DATABASE_URL with the port included and you can't change it.

Did I do something wrong? Is there a clean solution to avoid that?

(because what I did is ugly as I hard-coded the DATABASE_CONFIG without the port directly in my code)

Thanks for your help!

答:
First off, I would avoid using new Client() as this can lead to your connection being bottlenecked. Instead, use connection pooling. You can read a more indepth answer into why you want to do that here.

As for you direct issue, personally I have had trouble connecting to heroku postgres databases in the past, but here is a (basic) typical setup that works for me 99% of the time:

```<code>let pg = require('pg');
if (process.env.DATABASE_URL) {
  pg.defaults.ssl = true;
}

// include an OR statement if you switch between a local dev db and
// a remote heroku environment

let connString = process.env.DATABASE_URL || 'postgresql://postgres:password@localhost:localpostgresport/yourlocaldbname';
const { Pool } = require('pg');

const pool = new Pool({
  connectionString : connString
});
</code>```

My first guess would be that it may have to do with ssl not being enabled. I know that has cause me problems in the past. Secondly, you want to make sure that you uses the process.env.DATABASE_URL, as environment variable should be set as the postgres connection string by Heroku.

Body:
I have a problem deploying a Nodejs app with a Postgresql database. The database comes from Heroku itself (Heroku Postgres add-on, hobby-dev). My app refused to connect to the database.

I found where the problem came from but I can't find a clean solution. And I think I could have misunderstood something (I'm new to Node and Heroku).

Heroku automatically gives me an environment variable DATABASE_CONFIG that includes the port:

postgres://username:password@hostname:port/databasename

Then, to connect with pg in my app, I use process.env.DATABASE_CONFIG as a connection string. I do something like:

const client = new Client({
    connectionString: connectionString,
})
client.connect()

This fails to connect.

But if instead of using this environment variable, I cheat and change it, removing the port number from this connection string, it works.

I don't know why but the problem is that Heroku gives you this DATABASE_URL with the port included and you can't change it.

Did I do something wrong? Is there a clean solution to avoid that?

(because what I did is ugly as I hard-coded the DATABASE_CONFIG without the port directly in my code)

Thanks for your help!

Body:
First off, I would avoid using new Client() as this can lead to your connection being bottlenecked. Instead, use connection pooling. You can read a more indepth answer into why you want to do that here.

As for you direct issue, personally I have had trouble connecting to heroku postgres databases in the past, but here is a (basic) typical setup that works for me 99% of the time:

let pg = require('pg');
if (process.env.DATABASE_URL) {
  pg.defaults.ssl = true;
}

// include an OR statement if you switch between a local dev db and
// a remote heroku environment

let connString = process.env.DATABASE_URL || 'postgresql://postgres:password@localhost:localpostgresport/yourlocaldbname';
const { Pool } = require('pg');

const pool = new Pool({
  connectionString : connString
});

My first guess would be that it may have to do with ssl not being enabled. I know that has cause me problems in the past. Secondly, you want to make sure that you uses the process.env.DATABASE_URL, as environment variable should be set as the postgres connection string by Heroku.


问:
iOS IAP receipt contains old consumable purchases
In my app I have 3 consumable purchases and when I'm buying one I receive IAP receipt which contains 4 purchases: one that I bought just now and 3 old purchases made a while ago. That 3 old purchases are always
the same. Looks like finishTransaction method was never called on them. I'm making purchases in sandbox mode. If I switch to another test user everything works fine. I receive a receipt with only one purchase. Why I keep receiving old purchases and how can I delete them from the receipt?

Here is the receipt I receive:

```<code>{
  "status" : 200,
  "exectime" : 2032,
  "response" : {
    "status" : 0,
    "receipt" : {
      "receipt_type" : "ProductionSandbox",
      "app_item_id" : 0,
      "receipt_creation_date" : "2017-04-28 04:34:20 Etc\/GMT",
      "bundle_id" : "xxxx",
      "original_purchase_date" : "2013-08-01 07:00:00 Etc\/GMT",
      "in_app" : [
        {
          "product_id" : "xxxx.50Minutes",
          "quantity" : "1",
          "transaction_id" : "xxxx",
          "purchase_date_ms" : "1493289005000",
          "original_purchase_date_pst" : "2017-04-27 03:30:05 America\/Los_Angeles",
          "purchase_date_pst" : "2017-04-27 03:30:05 America\/Los_Angeles",
          "original_purchase_date_ms" : "1493289005000",
          "is_trial_period" : "false",
          "original_purchase_date" : "2017-04-27 10:30:05 Etc\/GMT",
          "original_transaction_id" : "xxxx",
          "purchase_date" : "2017-04-27 10:30:05 Etc\/GMT"
        },
        {
          "product_id" : "xxxx.15Minutes",
          "quantity" : "1",
          "transaction_id" : "xxxx",
          "purchase_date_ms" : "1493289017000",
          "original_purchase_date_pst" : "2017-04-27 03:30:17 America\/Los_Angeles",
          "purchase_date_pst" : "2017-04-27 03:30:17 America\/Los_Angeles",
          "original_purchase_date_ms" : "1493289017000",
          "is_trial_period" : "false",
          "original_purchase_date" : "2017-04-27 10:30:17 Etc\/GMT",
          "original_transaction_id" : "xxxx",
          "purchase_date" : "2017-04-27 10:30:17 Etc\/GMT"
        },
        {
          "product_id" : "xxxx.15Minutes",
          "quantity" : "1",
          "transaction_id" : "xxxx",
          "purchase_date_ms" : "1493354060000",
          "original_purchase_date_pst" : "2017-04-27 21:34:20 America\/Los_Angeles",
          "purchase_date_pst" : "2017-04-27 21:34:20 America\/Los_Angeles",
          "original_purchase_date_ms" : "1493354060000",
          "is_trial_period" : "false",
          "original_purchase_date" : "2017-04-28 04:34:20 Etc\/GMT",
          "original_transaction_id" : "xxxx",
          "purchase_date" : "2017-04-28 04:34:20 Etc\/GMT"
        },
        {
          "product_id" : "xxxx.100Minutes",
          "quantity" : "1",
          "transaction_id" : "xxxx",
          "purchase_date_ms" : "1493289033000",
          "original_purchase_date_pst" : "2017-04-27 03:30:33 America\/Los_Angeles",
          "purchase_date_pst" : "2017-04-27 03:30:33 America\/Los_Angeles",
          "original_purchase_date_ms" : "1493289033000",
          "is_trial_period" : "false",
          "original_purchase_date" : "2017-04-27 10:30:33 Etc\/GMT",
          "original_transaction_id" : "xxxx",
          "purchase_date" : "2017-04-27 10:30:33 Etc\/GMT"
        }
      ],
      "adam_id" : 0,
      "receipt_creation_date_pst" : "2017-04-27 21:34:20 America\/Los_Angeles",
      "request_date" : "2017-04-28 04:34:34 Etc\/GMT",
      "request_date_pst" : "2017-04-27 21:34:34 America\/Los_Angeles",
      "version_external_identifier" : 0,
      "request_date_ms" : "1493354074233",
      "original_purchase_date_pst" : "2013-08-01 00:00:00 America\/Los_Angeles",
      "application_version" : "1",
      "original_purchase_date_ms" : "1375340400000",
      "receipt_creation_date_ms" : "1493354060000",
      "original_application_version" : "1.0",
      "download_id" : 0
    },
    "environment" : "Sandbox"
  },
  "memory" : 649368
}
</code>```

答:
These are pending transactions. Solution for this is to create a new sandbox user. Then add queue.finishTransaction(transaction) all transaction states

```<code>public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                 queue.finishTransaction(transaction)
                break
            case .failed:
                queue.finishTransaction(transaction)
                break
            case .restored:
                queue.finishTransaction(transaction)
                break
            case .deferred:
                break
            case .purchasing:
                break
            }
        }
    }
</code>```

Body:
In my app I have 3 consumable purchases and when I'm buying one I receive IAP receipt which contains 4 purchases: one that I bought just now and 3 old purchases made a while ago. That 3 old purchases are always
the same. Looks like finishTransaction method was never called on them. I'm making purchases in sandbox mode. If I switch to another test user everything works fine. I receive a receipt with only one purchase. Why I keep receiving old purchases and how can I delete them from the receipt?

Here is the receipt I receive:

{
  "status" : 200,
  "exectime" : 2032,
  "response" : {
    "status" : 0,
    "receipt" : {
      "receipt_type" : "ProductionSandbox",
      "app_item_id" : 0,
      "receipt_creation_date" : "2017-04-28 04:34:20 Etc\/GMT",
      "bundle_id" : "xxxx",
      "original_purchase_date" : "2013-08-01 07:00:00 Etc\/GMT",
      "in_app" : [
        {
          "product_id" : "xxxx.50Minutes",
          "quantity" : "1",
          "transaction_id" : "xxxx",
          "purchase_date_ms" : "1493289005000",
          "original_purchase_date_pst" : "2017-04-27 03:30:05 America\/Los_Angeles",
          "purchase_date_pst" : "2017-04-27 03:30:05 America\/Los_Angeles",
          "original_purchase_date_ms" : "1493289005000",
          "is_trial_period" : "false",
          "original_purchase_date" : "2017-04-27 10:30:05 Etc\/GMT",
          "original_transaction_id" : "xxxx",
          "purchase_date" : "2017-04-27 10:30:05 Etc\/GMT"
        },
        {
          "product_id" : "xxxx.15Minutes",
          "quantity" : "1",
          "transaction_id" : "xxxx",
          "purchase_date_ms" : "1493289017000",
          "original_purchase_date_pst" : "2017-04-27 03:30:17 America\/Los_Angeles",
          "purchase_date_pst" : "2017-04-27 03:30:17 America\/Los_Angeles",
          "original_purchase_date_ms" : "1493289017000",
          "is_trial_period" : "false",
          "original_purchase_date" : "2017-04-27 10:30:17 Etc\/GMT",
          "original_transaction_id" : "xxxx",
          "purchase_date" : "2017-04-27 10:30:17 Etc\/GMT"
        },
        {
          "product_id" : "xxxx.15Minutes",
          "quantity" : "1",
          "transaction_id" : "xxxx",
          "purchase_date_ms" : "1493354060000",
          "original_purchase_date_pst" : "2017-04-27 21:34:20 America\/Los_Angeles",
          "purchase_date_pst" : "2017-04-27 21:34:20 America\/Los_Angeles",
          "original_purchase_date_ms" : "1493354060000",
          "is_trial_period" : "false",
          "original_purchase_date" : "2017-04-28 04:34:20 Etc\/GMT",
          "original_transaction_id" : "xxxx",
          "purchase_date" : "2017-04-28 04:34:20 Etc\/GMT"
        },
        {
          "product_id" : "xxxx.100Minutes",
          "quantity" : "1",
          "transaction_id" : "xxxx",
          "purchase_date_ms" : "1493289033000",
          "original_purchase_date_pst" : "2017-04-27 03:30:33 America\/Los_Angeles",
          "purchase_date_pst" : "2017-04-27 03:30:33 America\/Los_Angeles",
          "original_purchase_date_ms" : "1493289033000",
          "is_trial_period" : "false",
          "original_purchase_date" : "2017-04-27 10:30:33 Etc\/GMT",
          "original_transaction_id" : "xxxx",
          "purchase_date" : "2017-04-27 10:30:33 Etc\/GMT"
        }
      ],
      "adam_id" : 0,
      "receipt_creation_date_pst" : "2017-04-27 21:34:20 America\/Los_Angeles",
      "request_date" : "2017-04-28 04:34:34 Etc\/GMT",
      "request_date_pst" : "2017-04-27 21:34:34 America\/Los_Angeles",
      "version_external_identifier" : 0,
      "request_date_ms" : "1493354074233",
      "original_purchase_date_pst" : "2013-08-01 00:00:00 America\/Los_Angeles",
      "application_version" : "1",
      "original_purchase_date_ms" : "1375340400000",
      "receipt_creation_date_ms" : "1493354060000",
      "original_application_version" : "1.0",
      "download_id" : 0
    },
    "environment" : "Sandbox"
  },
  "memory" : 649368
}

Body:
These are pending transactions. Solution for this is to create a new sandbox user. Then add queue.finishTransaction(transaction) all transaction states

public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                 queue.finishTransaction(transaction)
                break
            case .failed:
                queue.finishTransaction(transaction)
                break
            case .restored:
                queue.finishTransaction(transaction)
                break
            case .deferred:
                break
            case .purchasing:
                break
            }
        }
    }