问:
Running a React/Rails app locally
I am trying to run an application locally which has React/Redux front-end and communicates with a rails api. In my .env file I am referencing the port which is running my api (rails s has it running on port as API_URL 3000) and my react dev server is referenced in HOST running on localhost:3003.

When I go to localhost:3003 and have my react font-end up, I get the following error when i send requests to my api: Bothy me .env files are also pointing at the correct ports on localhost.

XMLHttpRequest cannot load http://localhost:3000/users_company. No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:3003' is therefore not allowed
  access. The response had HTTP status code 500.

Any ideas ?

答:
In react applications which are created using create-react-app you can add a proxy in your react application's package.json. Here is an example of this from on of my own projects.

```<code>{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:8000",
  "dependencies": {
    "@types/jest": "^19.2.3",
    "@types/node": "^7.0.18",
    "@types/react": "^15.0.24",
    "@types/react-dom": "^15.5.0",
    "@types/react-router-dom": "^4.0.4",
    "@types/socket.io": "^1.4.29",
    "@types/socket.io-client": "^1.4.29",
    "axios": "^0.16.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^4.1.1",
    "socket.io": "^2.0.1",
    "socket.io-client": "^2.0.1"
  },
  "devDependencies": {
    "react-scripts-ts": "1.4.0"
  },
  "scripts": {
    "start": "react-scripts-ts start",
    "build": "react-scripts-ts build",
    "test": "react-scripts-ts test --env=jsdom",
    "eject": "react-scripts-ts eject"
  }
}
</code>```

Webpack will take the requests and proxy them to the url specified in the package.json and CORS will be handled for you. Of course this can be done in react applications that were created manually, but this would mean configuring webpack to proxy requests manually as well.

I should also point that now in your code you do not need to write the entire url like http://localhost:8000/api/something/some rather you can just write api/something/some. This is super helpful for deployment of course because now we dont care about the first part of the url which obviously changes from dev to production.

Title: Running a React/Rails app locally

Body:
In react applications which are created using create-react-app you can add a proxy in your react application's package.json. Here is an example of this from on of my own projects.

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:8000",
  "dependencies": {
    "@types/jest": "^19.2.3",
    "@types/node": "^7.0.18",
    "@types/react": "^15.0.24",
    "@types/react-dom": "^15.5.0",
    "@types/react-router-dom": "^4.0.4",
    "@types/socket.io": "^1.4.29",
    "@types/socket.io-client": "^1.4.29",
    "axios": "^0.16.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^4.1.1",
    "socket.io": "^2.0.1",
    "socket.io-client": "^2.0.1"
  },
  "devDependencies": {
    "react-scripts-ts": "1.4.0"
  },
  "scripts": {
    "start": "react-scripts-ts start",
    "build": "react-scripts-ts build",
    "test": "react-scripts-ts test --env=jsdom",
    "eject": "react-scripts-ts eject"
  }
}

Webpack will take the requests and proxy them to the url specified in the package.json and CORS will be handled for you. Of course this can be done in react applications that were created manually, but this would mean configuring webpack to proxy requests manually as well.

I should also point that now in your code you do not need to write the entire url like http://localhost:8000/api/something/some rather you can just write api/something/some. This is super helpful for deployment of course because now we dont care about the first part of the url which obviously changes from dev to production.


来源: stackexchange

问:
Rotating CSS cube on fixed axes
I have a cube constructed using CSS. It's made of 6 faces and each face is transformed to form one face of the cube, and all the 6 faces are under one
 with the class .cube. Any rotation I do to the cube is done on this enclosing cube class.

I want the cube to rotate based on mouse drag input. So far it kinda works. I just translate x and y mouse movement into cube rotation about the x and y axes.

But there's one major problem with this. I perform the rotation as a simple

```<code>transform: rotateX(xdeg) rotateY(ydeg)
</code>```

CSS property. The issue with this is that the y axis of rotation is getting rotated with the x rotation.

Suppose I rotate the cube 90 degrees around the x axis. Now, if I try to rotate the cube 90 degrees along the y axis as well, I would expect the cube to rotate 90 degrees to the right or left (from my perspective). But instead, it's rotating about it's currently visible front face. That is, the y axis got rotated 90 degrees thanks to the x axis rotation that came first, and so now from the perspective of the user, it looks as if the cube is rotating around it's z axis.

I want to be able to rotate the cube in a way that the x y and z axes remain fixed from the perspective of the user. Also the cube needs to rotate from the current state in case the user lifts their finger off the button and clicks again and drags.

I've been finding this difficult to do. I feel this may not be possible using just the rotateX/Y/Z properties and instead I might have to use the 3d matrix or rotate3d properties?

I know this may not be the easiest thing to achieve using CSS but I still want to do it. Could someone point me in the right direction on how to solve this problem?

#cube-wrapper {
  position: absolute;
  left: 50%;
  top: 50%;
  perspective: 1500px;
}

.cube {
  position: relative;
  transform-style: preserve-3d;
}

/* Size and border color for each face */

.face {
  position: absolute;
  width: 200px;
  height: 200px;
  border: solid green 3px;
}

/* Transforming every face into their correct positions */

#front_face {
  transform: translateX(-100px) translateY(-100px) translateZ(100px);
}

#back_face {
  transform: translateX(-100px) translateY(-100px) translateZ(-100px);
}

#right_face {
  transform: translateY(-100px) rotateY(90deg);
}

#left_face {
  transform: translateY(-100px) translateX(-200px) rotateY(90deg);
}

#top_face {
  transform: translateX(-100px) translateY(-200px) rotateX(90deg);
}

#bottom_face {
  transform: translateX(-100px) rotateX(90deg);
}

.cube {
  transform: rotateX(90deg) rotateY(90deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Wrapper for the cube -->
<div id="cube-wrapper">
  <div class="cube">
    <!-- A div for each face of the cube -->
    <div id="front_face" class="face"></div>
    <div id="right_face" class="face"></div>
    <div id="back_face" class="face"></div>
    <div id="left_face" class="face"></div>
    <div id="top_face" class="face"></div>
    <div id="bottom_face" class="face"></div>
  </div>
</div></code>```

I can't really add any javascript because I'm actually coding the logic in purescript. But the code just registers a mousedown handler that takes the current mouse x and y, compares it to the last x and y and accordingly rotates the cube around the x and y axes by changing the transform property of .cube with a value like.

```<code>  {transform: "rotateX(90deg) rotateY(90deg)"}
</code>```

答:
Note: It turns out this problem is kinda difficult to solve in CSS. If you really need a complex transformation like this where new transformations should be applied onto the previous state maybe try some other method.

Anyway, I'm first going to explain the steps I went through, the problems I faced and the steps I took to solve it. It's really convoluted and messy but it works. At the end, I've put the code I used as JavaScript.

Explanation

So I've come to understand a couple of things about transformations in CSS. One main thing is that when you pass a string of transformations to the transform property, like this

```<code>transform: "rotateX(90deg) rotateY(90deg)"
</code>```

these transformations are not combined into one single composite transformation. Instead the first one is applied, then the next one is applied on top of that and so on. So while I expected the cube to rotate diagonally by 90degrees, it didn't do that.

As @ihazkode suggested, rotate3d was the way to go. It allows rotation around any arbitrary axes instead of being limited to X, Y and Z axes. rotate3d takes 3 arguments

```<code>rotate3d(x, y, z, angle).
</code>```

x y and z specify the rotation axis. The way to look at it is like this: Imagine drawing a line from (x,y,z) to the transform-origin you specified. This line will the be axis of rotation. Now imagine you are looking towards the origin from (x,y,z). From this view, the object will rotate clockwise by angle degrees.

However, I still faced a problem. Although rotate3d let's me rotate the cube in a far more intuitive way, I still faced the problem where after rotating the cube once (with the mouse) if I again clicked and tried rotating the cube, it would snap back to its original state and rotate from there, which is not what I wanted. I wanted it to rotate from it's current state, whatever rotation state that may be.

I found a very messy way to do it using the matrix3d property. Basically I'd follow these steps every time the mousedown and mousemove events occurred

I'd calculate a vector based on the position that mousedown occured and the current mouse position from mousemove. For example, if mousedown occured at (123,145) and then a mousemove occured at (120,143), then a vector can be made from these two points as [x, y, z, m] where

x is the x component which is the new x position minus the mouse down x position = 120 - 123 = -3

y is the y component, similar to x, which = 143-145 = -2

z = 0 since the mouse cannot move in the z direction

m is the magnitude of the vector which can be calculated as squareroot(x2 + y2) =  3.606

So the mouse movement can be represented as the vector [-3, -2, 0, 3.606]

Now notice that the rotation vector of the cube should be perpendicular to the mouse movement. For example, if I move my mouse straight up by 3 pixels, the mouse movement vector is [0,-1,0,3] (y is negative because in the browser the top left corner is the origin). But if I use this vector as the rotation vector and pass it into rotate3d, that rotates the cube clockwise (when looking from above) around the y axis. But that's not right! If I swipe my mouse upwards, it should rotate around it's x axis! To solve this, just swap x and y and negate the new x. That is, the vector should be [1,0,0,3]. Therefore, the vector from step 1 should instead be [2,-3,0,3.606].

Now I just set the transform property of my cube as

```<code>transform: "rotate3d(2,-3,0,3.606)"
</code>```

So now, I figured out how to rotate the cube correctly based on mouse movement, without facing the previous problem of trying to make a rotateX and then rotateY.

Now the cube can rotate correctly. But what if I let go of the mouse and then again perform a mousedown and try rotating the cube. If I follow the same steps from above, what happens is the new vector that I pass to rotate3d will replace the old one. So the cube is reset to it's initial position and the new rotation is applied to it. But that's not right. I want the cube to remain in the state it was in previously, and then from that state it should rotate further by the new rotation vector.

To do this, I need to append the new rotation onto the previous rotation. So I could do something like this

```<code>transform: "rotate3d(previous_rotation_vector) rotate3d(new_rotation_vector)"
</code>```

After all, this would perform the first rotation and then perform the second rotation on top of that. But then imagine performing 100 rotations. The transform property would need to be fed 100 rotate3ds. That wouldn't be the best way to go about this.

Here's what I figured. At any point if you query the transform css property of a node like

```<code>$('.cube').css('transform');
</code>```

you get back one of 3 values: "none" if the object hasn't been transformed at all so far, a 2D transformation matrix (looks like matrix2d(...)) if only 2D transformations have peen performed, or a 3D transformation matrix (looks like matrix3d(...) otherwise.

So what I can do is, immediately after performing a rotate operation, query and get the transformation matrix of the cube and save it. Next time I perform a new rotation, do this:

```<code>transform: "matrix3d(saved_matrix_from_last_rotation) rotate3d(new_rotation_vector)"
</code>```

This would first transform the cube to it's last state of rotation and then apply the new rotation on top of that. No need to pass a 100 rotate3ds.

There's one last problem I discovered. There's still the same issue of the axes of an object rotating along with the object.

Suppose I rotate the cube 90 degrees along the x axis with

```<code>transform: rotate3d(1,0,0,90deg);
</code>```

and then rotate it from there around it's the y axis by 45 degrees with

```<code>transform: matrix3d(saved values) rotate3d(0,1,0,45deg)
</code>```

I would expect the cube to rotate upwards 90 and then rotate to the right by 45. But instead it rotated up by 90 and then rotated around currently visible front face by 45 instead of rotating to the right. It's the exact same problem I mentioned in my question. The problem is, although rotate3d allows you to rotate an object around any arbitrary axis of rotation, that arbitrary axis is still with reference to the axis of the object and not by a fixed x, y and z axes with respect to the user. It's the same gosh darn problem of the axes rotating with the object.

So if the cube is currently in some rotated state and I want it to rotate further on a vector (x,y,z) obtained through the mouse as in step 1 and 2, I first need to somehow transform this vector into it's correct position based on what state the cube is in currently.

What I noticed is if you take the rotation vector as a 4x1 matrix like this

```<code>x
y
z
angle
</code>```

and took the matrix3d matrix as a 4x4 matrix, then if I multiplied the 3D transformation matrix by the rotation vector, I get the old rotation vector but transformed into it's correct position. Now I can apply this vector after the 3d matrix as in step 3 and FINALLY the cube is behaving exactly the way it should.

JavaScript code

Okay that was enough talk. Here's the code I used. Sorry if it's not very clear.

```<code>var lastX; //stores x position from mousedown
var lastY; //y position from mousedown
var matrix3d = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] //this identity matrix performs no transformation

$(document).ready(function() {
  $('body').on('mousedown', function(event) {
    $('body').on('mouseup', function() {
      $('body').off('mousemove');
      m = $('.cube').css('transform');
      //if this condition is true, transform property is either "none" in initial state or "matrix2d" which happens when the cube is at 0 rotation.
      if(m.match(/matrix3d/) == null)
        matrix3d = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]; //identity matrix for no transformaion
      else
        matrix3d = stringToMatrix(m.substring(8,m.length));
    });

    lastX=event.pageX;
    lastY=event.pageY;

    $('body').on('mousemove', function (event) {
      var x = -(event.pageY - lastY);
      var y = event.pageX - lastX;
      var angle = Math.sqrt(x*x + y*y);
      var r = [[x],[y],[0],[angle]]; //rotation vector
      rotate3d = multiply(matrix3d, r); //multiply to get correctly transformed rotation vector
      var str = 'matrix3d' + matrixToString(matrix3d)
            + ' rotate3d(' + rotate3d[0][0] + ', ' + rotate3d[1][0] + ', ' + rotate3d[2][0] + ', ' + rotate3d[3][0] + 'deg)';
      $('.cube').css('transform',str);
    });
  });
});

//converts transform matrix to a string of all elements separated by commas and enclosed in parentheses.
function matrixToString(matrix) {
  var s = "(";
  for(i=0; i<matrix.length; i++) {
    for(j=0; j<matrix[i].length; j++) {
      s+=matrix[i][j];
      if(i<matrix.length-1 || j<matrix[i].length-1) s+=", ";
    }
  }
  return s+")";
}

//converts a string of transform matrix into a matrix
function stringToMatrix(s) {
  array=s.substring(1,s.length-1).split(", ");
  return [array.slice(0,4), array.slice(4,8), array.slice(8,12), array.slice(12,16)];
}

//matrix multiplication
function multiply(a, b) {
  var aNumRows = a.length, aNumCols = a[0].length,
      bNumRows = b.length, bNumCols = b[0].length,
      m = new Array(aNumRows);  // initialize array of rows
  for (var r = 0; r < aNumRows; ++r) {
    m[r] = new Array(bNumCols); // initialize the current row
    for (var c = 0; c < bNumCols; ++c) {
      m[r][c] = 0;             // initialize the current cell
      for (var i = 0; i < aNumCols; ++i) {
        m[r][c] += a[r][i] * b[i][c];
      }
    }
  }
  return m;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rotating CSS cube on fixed axes

Body:
I have a cube constructed using CSS. It's made of 6 faces and each face is transformed to form one face of the cube, and all the 6 faces are under one
 with the class .cube. Any rotation I do to the cube is done on this enclosing cube class.

I want the cube to rotate based on mouse drag input. So far it kinda works. I just translate x and y mouse movement into cube rotation about the x and y axes.

But there's one major problem with this. I perform the rotation as a simple

transform: rotateX(xdeg) rotateY(ydeg)

CSS property. The issue with this is that the y axis of rotation is getting rotated with the x rotation.

Suppose I rotate the cube 90 degrees around the x axis. Now, if I try to rotate the cube 90 degrees along the y axis as well, I would expect the cube to rotate 90 degrees to the right or left (from my perspective). But instead, it's rotating about it's currently visible front face. That is, the y axis got rotated 90 degrees thanks to the x axis rotation that came first, and so now from the perspective of the user, it looks as if the cube is rotating around it's z axis.

I want to be able to rotate the cube in a way that the x y and z axes remain fixed from the perspective of the user. Also the cube needs to rotate from the current state in case the user lifts their finger off the button and clicks again and drags.

I've been finding this difficult to do. I feel this may not be possible using just the rotateX/Y/Z properties and instead I might have to use the 3d matrix or rotate3d properties?

I know this may not be the easiest thing to achieve using CSS but I still want to do it. Could someone point me in the right direction on how to solve this problem?

#cube-wrapper {
  position: absolute;
  left: 50%;
  top: 50%;
  perspective: 1500px;
}

.cube {
  position: relative;
  transform-style: preserve-3d;
}

/* Size and border color for each face */

.face {
  position: absolute;
  width: 200px;
  height: 200px;
  border: solid green 3px;
}

/* Transforming every face into their correct positions */

#front_face {
  transform: translateX(-100px) translateY(-100px) translateZ(100px);
}

#back_face {
  transform: translateX(-100px) translateY(-100px) translateZ(-100px);
}

#right_face {
  transform: translateY(-100px) rotateY(90deg);
}

#left_face {
  transform: translateY(-100px) translateX(-200px) rotateY(90deg);
}

#top_face {
  transform: translateX(-100px) translateY(-200px) rotateX(90deg);
}

#bottom_face {
  transform: translateX(-100px) rotateX(90deg);
}

.cube {
  transform: rotateX(90deg) rotateY(90deg);
}

I can't really add any javascript because I'm actually coding the logic in purescript. But the code just registers a mousedown handler that takes the current mouse x and y, compares it to the last x and y and accordingly rotates the cube around the x and y axes by changing the transform property of .cube with a value like.

  {transform: "rotateX(90deg) rotateY(90deg)"}

Body:
Note: It turns out this problem is kinda difficult to solve in CSS. If you really need a complex transformation like this where new transformations should be applied onto the previous state maybe try some other method.

Anyway, I'm first going to explain the steps I went through, the problems I faced and the steps I took to solve it. It's really convoluted and messy but it works. At the end, I've put the code I used as JavaScript.

Explanation

So I've come to understand a couple of things about transformations in CSS. One main thing is that when you pass a string of transformations to the transform property, like this

transform: "rotateX(90deg) rotateY(90deg)"

these transformations are not combined into one single composite transformation. Instead the first one is applied, then the next one is applied on top of that and so on. So while I expected the cube to rotate diagonally by 90degrees, it didn't do that.

As @ihazkode suggested, rotate3d was the way to go. It allows rotation around any arbitrary axes instead of being limited to X, Y and Z axes. rotate3d takes 3 arguments

rotate3d(x, y, z, angle).

x y and z specify the rotation axis. The way to look at it is like this: Imagine drawing a line from (x,y,z) to the transform-origin you specified. This line will the be axis of rotation. Now imagine you are looking towards the origin from (x,y,z). From this view, the object will rotate clockwise by angle degrees.

However, I still faced a problem. Although rotate3d let's me rotate the cube in a far more intuitive way, I still faced the problem where after rotating the cube once (with the mouse) if I again clicked and tried rotating the cube, it would snap back to its original state and rotate from there, which is not what I wanted. I wanted it to rotate from it's current state, whatever rotation state that may be.

I found a very messy way to do it using the matrix3d property. Basically I'd follow these steps every time the mousedown and mousemove events occurred

I'd calculate a vector based on the position that mousedown occured and the current mouse position from mousemove. For example, if mousedown occured at (123,145) and then a mousemove occured at (120,143), then a vector can be made from these two points as [x, y, z, m] where

x is the x component which is the new x position minus the mouse down x position = 120 - 123 = -3

y is the y component, similar to x, which = 143-145 = -2

z = 0 since the mouse cannot move in the z direction

m is the magnitude of the vector which can be calculated as squareroot(x2 + y2) =  3.606

So the mouse movement can be represented as the vector [-3, -2, 0, 3.606]

Now notice that the rotation vector of the cube should be perpendicular to the mouse movement. For example, if I move my mouse straight up by 3 pixels, the mouse movement vector is [0,-1,0,3] (y is negative because in the browser the top left corner is the origin). But if I use this vector as the rotation vector and pass it into rotate3d, that rotates the cube clockwise (when looking from above) around the y axis. But that's not right! If I swipe my mouse upwards, it should rotate around it's x axis! To solve this, just swap x and y and negate the new x. That is, the vector should be [1,0,0,3]. Therefore, the vector from step 1 should instead be [2,-3,0,3.606].

Now I just set the transform property of my cube as

transform: "rotate3d(2,-3,0,3.606)"

So now, I figured out how to rotate the cube correctly based on mouse movement, without facing the previous problem of trying to make a rotateX and then rotateY.

Now the cube can rotate correctly. But what if I let go of the mouse and then again perform a mousedown and try rotating the cube. If I follow the same steps from above, what happens is the new vector that I pass to rotate3d will replace the old one. So the cube is reset to it's initial position and the new rotation is applied to it. But that's not right. I want the cube to remain in the state it was in previously, and then from that state it should rotate further by the new rotation vector.

To do this, I need to append the new rotation onto the previous rotation. So I could do something like this

transform: "rotate3d(previous_rotation_vector) rotate3d(new_rotation_vector)"

After all, this would perform the first rotation and then perform the second rotation on top of that. But then imagine performing 100 rotations. The transform property would need to be fed 100 rotate3ds. That wouldn't be the best way to go about this.

Here's what I figured. At any point if you query the transform css property of a node like

$('.cube').css('transform');

you get back one of 3 values: "none" if the object hasn't been transformed at all so far, a 2D transformation matrix (looks like matrix2d(...)) if only 2D transformations have peen performed, or a 3D transformation matrix (looks like matrix3d(...) otherwise.

So what I can do is, immediately after performing a rotate operation, query and get the transformation matrix of the cube and save it. Next time I perform a new rotation, do this:

transform: "matrix3d(saved_matrix_from_last_rotation) rotate3d(new_rotation_vector)"

This would first transform the cube to it's last state of rotation and then apply the new rotation on top of that. No need to pass a 100 rotate3ds.

There's one last problem I discovered. There's still the same issue of the axes of an object rotating along with the object.

Suppose I rotate the cube 90 degrees along the x axis with

transform: rotate3d(1,0,0,90deg);

and then rotate it from there around it's the y axis by 45 degrees with

transform: matrix3d(saved values) rotate3d(0,1,0,45deg)

I would expect the cube to rotate upwards 90 and then rotate to the right by 45. But instead it rotated up by 90 and then rotated around currently visible front face by 45 instead of rotating to the right. It's the exact same problem I mentioned in my question. The problem is, although rotate3d allows you to rotate an object around any arbitrary axis of rotation, that arbitrary axis is still with reference to the axis of the object and not by a fixed x, y and z axes with respect to the user. It's the same gosh darn problem of the axes rotating with the object.

So if the cube is currently in some rotated state and I want it to rotate further on a vector (x,y,z) obtained through the mouse as in step 1 and 2, I first need to somehow transform this vector into it's correct position based on what state the cube is in currently.

What I noticed is if you take the rotation vector as a 4x1 matrix like this

x
y
z
angle

and took the matrix3d matrix as a 4x4 matrix, then if I multiplied the 3D transformation matrix by the rotation vector, I get the old rotation vector but transformed into it's correct position. Now I can apply this vector after the 3d matrix as in step 3 and FINALLY the cube is behaving exactly the way it should.

JavaScript code

Okay that was enough talk. Here's the code I used. Sorry if it's not very clear.

var lastX; //stores x position from mousedown
var lastY; //y position from mousedown
var matrix3d = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] //this identity matrix performs no transformation

$(document).ready(function() {
  $('body').on('mousedown', function(event) {
    $('body').on('mouseup', function() {
      $('body').off('mousemove');
      m = $('.cube').css('transform');
      //if this condition is true, transform property is either "none" in initial state or "matrix2d" which happens when the cube is at 0 rotation.
      if(m.match(/matrix3d/) == null)
        matrix3d = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]; //identity matrix for no transformaion
      else
        matrix3d = stringToMatrix(m.substring(8,m.length));
    });

    lastX=event.pageX;
    lastY=event.pageY;

    $('body').on('mousemove', function (event) {
      var x = -(event.pageY - lastY);
      var y = event.pageX - lastX;
      var angle = Math.sqrt(x*x + y*y);
      var r = [[x],[y],[0],[angle]]; //rotation vector
      rotate3d = multiply(matrix3d, r); //multiply to get correctly transformed rotation vector
      var str = 'matrix3d' + matrixToString(matrix3d)
            + ' rotate3d(' + rotate3d[0][0] + ', ' + rotate3d[1][0] + ', ' + rotate3d[2][0] + ', ' + rotate3d[3][0] + 'deg)';
      $('.cube').css('transform',str);
    });
  });
});

//converts transform matrix to a string of all elements separated by commas and enclosed in parentheses.
function matrixToString(matrix) {
  var s = "(";
  for(i=0; i<matrix.length; i++) {
    for(j=0; j<matrix[i].length; j++) {
      s+=matrix[i][j];
      if(i<matrix.length-1 || j<matrix[i].length-1) s+=", ";
    }
  }
  return s+")";
}

//converts a string of transform matrix into a matrix
function stringToMatrix(s) {
  array=s.substring(1,s.length-1).split(", ");
  return [array.slice(0,4), array.slice(4,8), array.slice(8,12), array.slice(12,16)];
}

//matrix multiplication
function multiply(a, b) {
  var aNumRows = a.length, aNumCols = a[0].length,
      bNumRows = b.length, bNumCols = b[0].length,
      m = new Array(aNumRows);  // initialize array of rows
  for (var r = 0; r < aNumRows; ++r) {
    m[r] = new Array(bNumCols); // initialize the current row
    for (var c = 0; c < bNumCols; ++c) {
      m[r][c] = 0;             // initialize the current cell
      for (var i = 0; i < aNumCols; ++i) {
        m[r][c] += a[r][i] * b[i][c];
      }
    }
  }
  return m;
}


问:
UIBarButtonItem not shown in View
I'm trying to add two items to my navigation controller in a view. Before I always used to select the view and than click product -> Embed in -> Navigation Controller.

I noticed this suddenly wasn't working anymore in xCode 7.1. I updated Xcode to version 7.2 and was hoping this would solve my problem, but it didn't.

I tried to add the UIBarButtonItems using code, but this is also not working. But, when I change the color of the navigation controller, I can see the result of the color.

This is the code that I tried to add the items to my navigation bar:

```<code>    let left = UIBarButtonItem(image: UIImage(named: "hammer"), style: UIBarButtonItemStyle.Plain, target: self, action: "expandButtonPressed")
    let right = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "buildButtonPressed")

    navigationController?.navigationItem.rightBarButtonItem = right
    navigationController?.navigationItem.leftBarButtonItem = left
</code>```

The methods expandButtonPressed and buildButtonPressed have been added to my view controller.

Below are several screenshots explaining what controls I have in my view, and how the different view are setup.

Here is a screenshot running the app: https://drive.google.com/open?id=0B_FbD3kpEuvXYS1QYks0YTBVNmc

I hope somebody can help me.

答: You have to put each child ViewControllers inside a UINavigationBarController. Something like this:

Title: UIBarButtonItem not shown in View

Body:
I'm trying to add two items to my navigation controller in a view. Before I always used to select the view and than click product -> Embed in -> Navigation Controller.

I noticed this suddenly wasn't working anymore in xCode 7.1. I updated Xcode to version 7.2 and was hoping this would solve my problem, but it didn't.

I tried to add the UIBarButtonItems using code, but this is also not working. But, when I change the color of the navigation controller, I can see the result of the color.

This is the code that I tried to add the items to my navigation bar:

    let left = UIBarButtonItem(image: UIImage(named: "hammer"), style: UIBarButtonItemStyle.Plain, target: self, action: "expandButtonPressed")
    let right = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "buildButtonPressed")

    navigationController?.navigationItem.rightBarButtonItem = right
    navigationController?.navigationItem.leftBarButtonItem = left

The methods expandButtonPressed and buildButtonPressed have been added to my view controller.

Below are several screenshots explaining what controls I have in my view, and how the different view are setup.

Here is a screenshot running the app: https://drive.google.com/open?id=0B_FbD3kpEuvXYS1QYks0YTBVNmc

I hope somebody can help me.


问:
Show the complete description of an example
In RSpec, how can we generate a string from an example, representing the current meta description of the current example?

Example:

```<code>RSpec.describe Api::V1::Public::Signin::ByEmailController, type: :controller do
  describe 'POST #create' do
    context 'when the provider is "email"' do
      context 'when there is a saved email' do
        context 'when the password is good' do
          it 'signs in' do
            expect(current_metadata_description).to eq 'Api::V1::Public::Signin::ByEmailController POST #create when the provider is "email" when there is a saved email when the password is good signs in'
          end
        end
      end
    end
  end
end
</code>```

As we can see, the current meta description of the given example is:

Api::V1::Public::Signin::ByEmailController POST #create when the provider is "email" when there is a saved email when the password is good signs in

Thanks.

Edit:

The current_metadata_description is not provided by RSpec. I just invented it to give an example of what I would like to have.

答:
While I am unsure what your overall intentions are for doing this.

Rspec::Core::ExampleGroup.it yields a RSpec::Core::Example to the block. As with all yielding methods one can capture the yielded Object in a block local variable. RSpec::Core::Example has a full_description method which appears to be what you are looking for. RSpec Source.

For Example (no pun intended):

```<code>describe String do
  context 'Down' do
    context 'Deeper' do
      it 'can describe itself' do |ex|
        # ex is the specific RSpec::Core::Example for this it block
        expect(ex.full_description).to eq('String Down Deeper can describe itself')
      end
    end
  end
end
</code>```

running this will return

```<code>.
Finished in 0.003 seconds (files took 0.21998 seconds to load)
1 example, 0 failures
</code>```

It is imperative that you capture the yielded value if you want the desired output as the block itself is executed in the context of an instance of RSpec::Core::ExampleGroup so calling self.class.metadata[:full_description] will contain the description of the RSpec::Core::ExampleGroup but not the RSpec::Core::Example itself (e.g. "String Down Deeper")

As described in the docs if this is for logging purposes (or something similar where you would like this information for each example) you can access the RSpec::Core::Example in Hooks excerpt:

```<code># Useful for configuring logging and/or taking some action based
# on the state of an example's metadata.
#
#     RSpec.configure do |config|
#       config.before do |example|
#         log example.description
#       end
#
#       config.after do |example|
#         log example.description
#       end
#
#       config.around do |example|
#         log example.description
#         example.run
#       end
#     end
</code>```

If you really wanted to patch this in (and I am not endorsing it) You could do the following

```<code>class RSpec::Core::ExampleGroup
  def instance_exec(*args,&blk)
    if args.first.is_a?(RSpec::Core::Example)
      self.define_singleton_method(:current_metadata_description) do
        args.first.full_description
      end
    end
    super(*args,&blk)
  end
end
</code>```

Then your test would be exactly as you stated.

Body:
In RSpec, how can we generate a string from an example, representing the current meta description of the current example?

Example:

RSpec.describe Api::V1::Public::Signin::ByEmailController, type: :controller do
  describe 'POST #create' do
    context 'when the provider is "email"' do
      context 'when there is a saved email' do
        context 'when the password is good' do
          it 'signs in' do
            expect(current_metadata_description).to eq 'Api::V1::Public::Signin::ByEmailController POST #create when the provider is "email" when there is a saved email when the password is good signs in'
          end
        end
      end
    end
  end
end

As we can see, the current meta description of the given example is:

Api::V1::Public::Signin::ByEmailController POST #create when the provider is "email" when there is a saved email when the password is good signs in

Thanks.

Edit:

The current_metadata_description is not provided by RSpec. I just invented it to give an example of what I would like to have.

Body:
While I am unsure what your overall intentions are for doing this.

Rspec::Core::ExampleGroup.it yields a RSpec::Core::Example to the block. As with all yielding methods one can capture the yielded Object in a block local variable. RSpec::Core::Example has a full_description method which appears to be what you are looking for. RSpec Source.

For Example (no pun intended):

describe String do
  context 'Down' do
    context 'Deeper' do
      it 'can describe itself' do |ex|
        # ex is the specific RSpec::Core::Example for this it block
        expect(ex.full_description).to eq('String Down Deeper can describe itself')
      end
    end
  end
end

running this will return

.
Finished in 0.003 seconds (files took 0.21998 seconds to load)
1 example, 0 failures

It is imperative that you capture the yielded value if you want the desired output as the block itself is executed in the context of an instance of RSpec::Core::ExampleGroup so calling self.class.metadata[:full_description] will contain the description of the RSpec::Core::ExampleGroup but not the RSpec::Core::Example itself (e.g. "String Down Deeper")

As described in the docs if this is for logging purposes (or something similar where you would like this information for each example) you can access the RSpec::Core::Example in Hooks excerpt:

# Useful for configuring logging and/or taking some action based
# on the state of an example's metadata.
#
#     RSpec.configure do |config|
#       config.before do |example|
#         log example.description
#       end
#
#       config.after do |example|
#         log example.description
#       end
#
#       config.around do |example|
#         log example.description
#         example.run
#       end
#     end

If you really wanted to patch this in (and I am not endorsing it) You could do the following

class RSpec::Core::ExampleGroup
  def instance_exec(*args,&blk)
    if args.first.is_a?(RSpec::Core::Example)
      self.define_singleton_method(:current_metadata_description) do
        args.first.full_description
      end
    end
    super(*args,&blk)
  end
end

Then your test would be exactly as you stated.


问:
Error in string index out of range: maf file to fasta file
Context: I am trying to convert a maf file (multiple alignment file) to individual fasta file. I keep running into the same error that I'm not sure how to fix and this may be because I'm relatively new to python. My code is below:

```<code>open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')
for record in open_file:
    print(record[2:7])
    if (record[2] == 'Z'):
        new_file = open(record[2:7]+".fasta",'w')
        header = ">"+record[2:7]+"\n"
        sequence = record[46:len(record)]
        new_file.write(header)
        new_file.write(sequence)
        new_file.close()
    else:
        print("Not correct isolate.")
open_file.close()
</code>```

The error I get is:

```<code>IndexError
Traceback (most recent call last)
      2 for record in open_file:
      3     print(record[2:7])
----> 4     if (record[2] == 'Z'):
      5         new_file = open(record[2:7]+".fasta",'w')
      6         header = ">"+record[2:7]+"\n"
IndexError: string index out of range
</code>```

If I remove the if, else statement it works as I expect but I would like to filter for specific species that start with the character Z.

If anyone could help explain why I can't select for only strings that start with the character Z this way, that would be great! Thanks in advance.

答:
Its giving an error when the length of record is less than 2.

To fix this you can change your if statement to:

```<code>if (len(record) > 2 and record[2] == 'Z'):
</code>```

Ideally you should also handle such cases before separately.

Body:
Context: I am trying to convert a maf file (multiple alignment file) to individual fasta file. I keep running into the same error that I'm not sure how to fix and this may be because I'm relatively new to python. My code is below:

open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')
for record in open_file:
    print(record[2:7])
    if (record[2] == 'Z'):
        new_file = open(record[2:7]+".fasta",'w')
        header = ">"+record[2:7]+"\n"
        sequence = record[46:len(record)]
        new_file.write(header)
        new_file.write(sequence)
        new_file.close()
    else:
        print("Not correct isolate.")
open_file.close()

The error I get is:

IndexError
Traceback (most recent call last)
      2 for record in open_file:
      3     print(record[2:7])
----> 4     if (record[2] == 'Z'):
      5         new_file = open(record[2:7]+".fasta",'w')
      6         header = ">"+record[2:7]+"\n"
IndexError: string index out of range

If I remove the if, else statement it works as I expect but I would like to filter for specific species that start with the character Z.

If anyone could help explain why I can't select for only strings that start with the character Z this way, that would be great! Thanks in advance.

Body:
Its giving an error when the length of record is less than 2.

To fix this you can change your if statement to:

if (len(record) > 2 and record[2] == 'Z'):

Ideally you should also handle such cases before separately.


问:
How to deploy to Tomcat from NetBeans?
I've added Tomcat in the "Tools > Servers" menu and as you can see it appears in the list of servers:

But when I try to run my project, I cannot select Tomcat! The drop-down with servers is empty. I tried it with NetBeans 6.8 and 6.9 Beta. Any idea?

The end: I've used the wrong archetype so that NetBeans decided that Tomcat is not capable to execute it.

答:
Add this to your pom.xml
after: <repositories></repositories>

```<code><properties>
        <netbeans.hint.deploy.server>Tomcat60</netbeans.hint.deploy.server>
</properties>
</code>```

Title: How to deploy to Tomcat from NetBeans?

Body:
Add this to your pom.xml
after: <repositories></repositories>

<properties>
        <netbeans.hint.deploy.server>Tomcat60</netbeans.hint.deploy.server>
</properties>

ContentLicense: CC BY-SA 2.5


问:
NLP short text marking approach
I am working on a project to evaluate short answer questions for an educational institution.  Here is what I need to do:

Teacher has a sample answer (known to us in advance).
 Sample answer has 3-4 keywords.
 Student enters the answer.  The application should evaluate student's answer as below:

Contextual meaning of those keywords should be present in the answer with same/similar relations as in sample answer.

Students are expected to use the synonyms of the keywords.

Proper relationships of the synonyms are expected as well.

Students are not allowed to use the same        keywords (no marks if
they use the keywords in their answer).

Answers are not more that 2-3 sentences.

Can someone guide me what is a good approach for this?  Looking for some starting point to accomplish this.  I am familiar with basics of the NLP, but not worked with much tools available there.

答:
There is a sub-discipline of Applied Linguistics called "computer assisted language learning" (often CALL for short) that I'm not too familiar with, but probably has some insights you'd want to leverage. It's more about automatic grading, etc. of, for example, student essays of non-native English speakers, but I suspect you might want to get familiar with CALL research.

This is a really hard problem and not one generally solved. In the end, you'll want a human in the loop---that is, the system assigns grades, and the instructor needs to check off that they agree. Both the NLP isn't good enough and the understanding of language and knowledge isn't clear enough that you can get a full and accurate picture of the meaning of text automatically.

With that caveat in mind, I'd start with getting as many actual examples of teacher answers and correct and incorrect student answers as you possibly can. You'll need to have some kind of gold standard data for two reasons: to understand how well your system is working (evaluation) and to understand what makes a right and wrong answer (insight). Without actual examples, it's unlikely you'll have a working system; with actual examples, it's still going to be hard, but now you know how well you're doing.

As a first pass, instead of doing anything fancy, do a tf.idf weighted bag-of-words model. Use the cosine distance to compare teacher/student answers, and see how well you can predict right or wrong based on the cosine distance. This won't be perfect, of course, but it will give you a good baseline to compare your other results to.

You could try replacing the tf.idf bag of words with some kind of word2vec (W2V) system next. W2V helps solve some issues of synonymy, but you'll need a lot of genre-specific text to make it work properly, and I doubt with this application you'll have enough.

From there, I'd start playing with using a parser and trying to use relationships between the words to get at the intended meaning. That's well down the road, though. Get that data first.

Title: NLP short text marking approach


问:
ng-click for a reset button only works once
I am having an issue with a reset button. It works, but only once. After that I need to reload the webpage to get the button to work again.

In JS file

```<code>var ctrl = this;
var original_device = angular.copy(device.data);
ctrl.device = device.data;

ctrl.reset = function () {
    ctrl.device = original_device;
};
</code>```

In html file

```<code><button ng-click="ctrl.reset()">Reset</button>
</code>```

答:
You are going to need to copy the copy because after you use it, device and the copy will be the same object.</p>

```<code>ctrl.reset = function () {
     ctrl.device = angular.copy(original_device);
};
</code>```

Body:
I am having an issue with a reset button. It works, but only once. After that I need to reload the webpage to get the button to work again.

In JS file

var ctrl = this;
var original_device = angular.copy(device.data);
ctrl.device = device.data;

ctrl.reset = function () {
    ctrl.device = original_device;
};

In html file

<button ng-click="ctrl.reset()">Reset</button>

Body:
You are going to need to copy the copy because after you use it, device and the copy will be the same object.

ctrl.reset = function () {
     ctrl.device = angular.copy(original_device);
};


问:
What is meant by an exe being dynamically compiled?
Came across the following paragraph from a page on the MySQL website here:

You can write plugins in C or C++ (or another language that can use C
  calling conventions). Plugins are loaded and unloaded dynamically, so
  your operating system must support dynamic loading and you must have
  compiled the calling application dynamically (not statically). For
  server plugins, this means that mysqld must be compiled
  dynamically.

What is meant by dynamical compiling? I know about dynamical linking, but I'm not sure what they meant with dynamical compiling.

Also, on Windows 10 (x64), how can I assure that an exe has been compiled dynamically? Is it possible to figure it out from the output of dumpbin? Here's the dumpbin output for mysqld.exe (version 5.7):

Note: I reviewed this old question which did not provide me with that much information.  The depends tool it suggests is no longer on Windows.

答:
Compiling dynamically simply means that you are compiling the code such that the compiled output is suitable for dynamic linking.

On Windows, the process of creating as DLL necessarily compiles it such that it's suitable for dynamic linking because DLLs are always dynamically linked.

I believe that most platforms today always compile dynamically and produce relocatable output, even if they're subsequently linked statically.


问:
PHP : Warning: oci_connect(): ORA-12154: TNS:could not resolve the connect identifier specified in
i am trying to connect Oracle and PHP, i followed PHP manual for connecting and connected success fully by this below way:

```<code> oci_connect('Username','Password', ' (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = XE)))' );
</code>```

But Whenever i am using below method

```<code>oci_connect('Username','Password', ,'MYDB');
</code>```

i'm getting this error:

Warning: oci_connect(): ORA-12154: TNS:could not resolve the connect identifier specified in

So, i have checked all the way some one said use Oracle client files i added tnsnames.ora,ORACLE_HOME,TNS_ADMIN and everything done, from the reference of previous questions but still the problem haven't resolved.

am i doing anything wrong, if please help me to get out from this problem.

Thanks in advance.

答:
You can create a page with information about your environment by example:

```<code><?php
phpinfo();
?>
</code>```

By default, create this page in /var/www/html/phpinfo.php

Look for the TNS_ADMIN entry in the Envioriment session.

Body:
i am trying to connect Oracle and PHP, i followed PHP manual for connecting and connected success fully by this below way:

 oci_connect('Username','Password', ' (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = XE)))' );

But Whenever i am using below method

oci_connect('Username','Password', ,'MYDB');

i'm getting this error:

Warning: oci_connect(): ORA-12154: TNS:could not resolve the connect identifier specified in

So, i have checked all the way some one said use Oracle client files i added tnsnames.ora,ORACLE_HOME,TNS_ADMIN and everything done, from the reference of previous questions but still the problem haven't resolved.

am i doing anything wrong, if please help me to get out from this problem.

Thanks in advance.

Body:
You can create a page with information about your environment by example:

<?php
phpinfo();
?>

By default, create this page in /var/www/html/phpinfo.php

Look for the TNS_ADMIN entry in the Envioriment session.


问:
Spark streaming - Does reduceByKeyAndWindow() use constant memory?
I'm playing with the idea of having long-running aggregations (possibly a one day window).  I realize other solutions on this site say that you should use batch processing for this.

I'm specifically interested in understanding this function though.  It sounds like it would use constant space to do an aggregation over the window, one interval at a time.  If that is true, it sounds like a day-long aggregation would be possible-viable (especially since it uses check-pointing in case of failure).

Does anyone know if this is the case?

This function is documented as: https://spark.apache.org/docs/2.1.0/streaming-programming-guide.html

A more efficient version of the above reduceByKeyAndWindow() where the reduce value of each window is calculated incrementally using the reduce values of the previous window. This is done by reducing the new data that enters the sliding window, and “inverse reducing” the old data that leaves the window. An example would be that of “adding” and “subtracting” counts of keys as the window slides. However, it is applicable only to “invertible reduce functions”, that is, those reduce functions which have a corresponding “inverse reduce” function (taken as parameter invFunc). Like in reduceByKeyAndWindow, the number of reduce tasks is configurable through an optional argument. Note that checkpointing must be enabled for using this operation.

答:
After researching this on the MapR forums, it seems that it would definitely use a constant level of memory, making a daily window possible assuming you can fit one day of data in your allocated resources.

The two downsides are that:

Doing a daily aggregation may only take 20 minutes.  Doing a window over a day means that you're using all those cluster resources permanently rather than just for 20 minutes a day.  So, stand-alone batch aggregations are far more resource efficient.

Its hard to deal with late data when you're streaming exactly over a day. If your data is tagged with dates, then you need to wait till all your data arrives.  A 1 day window in streaming would only be good if you were literally just doing an analysis of the last 24 hours of data regardless of its content.


问:
Application Insights - Undefined Cloud Role Name with 2.4.0-beta3
We're trying out the app insights multi role preview as announced here:

https://azure.microsoft.com/en-us/blog/app-insights-microservices/

https://learn.microsoft.com/en-us/azure/application-insights/app-insights-monitor-multi-role-apps#use-cloudrolename-to-separate-components

We've added the 2.4.0-beta3 packages for appinsights & appinsights.windowsserver as the app we're using is hosted on prem (IIS) currently.

Our cloud_rolename seems to be undefined in our request telemetry. Is there anything further we need to do other than updating the packages?

We also found this:

AzureRoleEnvironmentTelemetryInitializer updates the RoleName and RoleInstance properties of the Device context for all telemetry items with information extracted from the Azure runtime environment.

..though our Cloud_RoleInstance property is being properly populated.

答:
For ASP.NET apps, I had to assign Cloud.RoleName using a custom ITelemetryInitializer to assign ITelemetry.Context.Cloud.RoleName property which will assign the proper context for a given request when using multi-component apps.

Telemetry Initializer for Multi-Component Apps

  public class MultiComponentTelemetryInitializer : ITelemetryInitializer
  {
    public void Initialize(ITelemetry telemetry)
    {
        var requestTelemetry = telemetry as RequestTelemetry;
        if (requestTelemetry?.Context?.Cloud == null) return;
        requestTelemetry.Context.Cloud.RoleName = "myapp-api";
    }
  }
```

This initializer only works on the server side APIs - I have not found the equivalent hook for the client JS SDK.

Body:
For ASP.NET apps, I had to assign Cloud.RoleName using a custom ITelemetryInitializer to assign ITelemetry.Context.Cloud.RoleName property which will assign the proper context for a given request when using multi-component apps.

Telemetry Initializer for Multi-Component Apps

  public class MultiComponentTelemetryInitializer : ITelemetryInitializer
  {
    public void Initialize(ITelemetry telemetry)
    {
        var requestTelemetry = telemetry as RequestTelemetry;
        if (requestTelemetry?.Context?.Cloud == null) return;
        requestTelemetry.Context.Cloud.RoleName = "myapp-api";
    }
  }

This initializer only works on the server side APIs - I have not found the equivalent hook for the client JS SDK.


问:
Realtime conversion of ARFrame.capturedImage CVPixelBufferRef to OpenCv Mat
ARKit runs at 60 frames/sec, which equates to 16.6ms per frame.

My current code to convert the CVPixelBufferRef (kCVPixelFormatType_420YpCbCr8BiPlanarFullRange format) to a cv::Mat (YCrCb) runs in 30ms, which causes ARKit to stall and everything to lag.

Does anyone have any ideas on how to to a quicker conversion or do I need to drop the frame rate?

There is a suggestion by Apple to use Metal, but I'm not sure how to do that.

Also I could just take the grayscale plane, which is the first channel, which runs in <1ms, but ideally I need the colour information as well.

答:
In order to process an image in a pixel buffer using Metal, you need to do following.

Call CVMetalTextureCacheCreateTextureFromImage to create CVMetalTexture object on top of the pixel buffer.

Call CVMetalTextureGetTexture to create a MTLTexture object, which Metal code (GPU) can read and write.

Write some Metal code to convert the color format.

I have an open source project (https://github.com/snakajima/vs-metal), which processes pixel buffers (from camera, not ARKit) using Metal. Feel free to copy any code from this project.


问:
Node.js or Express.js is server side language like PHP or not
Sorry, My question sounds dumb but i am bit confused about Node.js .I am a PHP developer and i know that php has operations and functions that execute on server and return result to client screen.

I want to ask in clear words, Do Node.js/Express.Js does the same as PHP does?
Do Node.js is for same work as php is?

should i move to Node.js from PHP (if both are for same purpose {mean back-end purpose})?

Which one is better choice in sense of Speed and security?

Which one has better scope in future?

Please help me in sorting out this confusion.

Please donot degrade my question.I a new in programming and answer in simple words as well...please please please.

Thanks.

答:
Moiz. You are asking sort of very generic questions, but maybe they can have simple answers to help you keep studying.

Node.JS is an asynchronous Javascript runtime. Yes, it can run as back-end code. Please, read their docs: https://nodejs.org/en/about/

1) Generaly speaking, yes, Node.JS can do the same work. They have different approachs and different architectures.

2) The answer is no if you are asking just to be on the curring edge. Move to another language is something that you have to study and really know which are the reasons to switch from one to another.

3) The answer of this question is the same for all languages comparition: depends (project, architecture, needs, etc, etc, etc). Is always good to enforce that speed and security is more accountable to developers than from the language itself.

4) Both are being improved and updated.


问:
how to replace a function by it content
How can I replace all occurrences of

check_free_set_to_null(&pointer)
by

```<code>if (pointer)
{
    free(pointer)
    printf(pointer have been freed)
}
else
{
    printf(pointer couldnt had been freed)
    return (1)
}

// maybe using some sort of

{1} = check_free_set_to_null(CONTENT)

if ({1})
{
    free({1})
    printf({1} have been freed)
}
else
{
    printf({1} couldnt had been freed)
    return (1)
}
</code>```

how could I do that ? (take note thats its not exactly what that have to be replaced, its just an example) Im not looking for the compiler to interpret it as multiple line, im looking for modifying the file.

答:
Basically exactly how you said, except...

This is one of those questions where the right answer is probably "Here's how to do the stupid thing you're asking to do, but PLEASE REALLY PLEASE tell us what your real problem is, that you're trying to solve, because this almost certainly isn't the right way to do it."

First, the search string should be (this is for vim, because I see the tag vim. If you want to do it using some other replacement regex thing, let us know which. Perl, php, sed, awk, the bash commandline, something?):

```<code>:%s/\bcheck_free_set_to_null\(([^()]+)\)/ replacement text goes here /g
</code>```

That presumes (possibly incorrectly) that there are never any braces inside the function - if that might be the case, then you are venturing into recursive regular expression territory, and in that case, you are definitely, definitely doing the wrong thing.

Your replacement string should be whatever your method will contain - in your example, it'd be:

```<code>:%s/\bcheck_free_set_to_null(\([^()]+\))/if (\1)\n{\n    free(\1)\n    printf("freed")\n}\nelse\n{\n    printf("could not free")\n    return (\1)\n}/g
</code>```

Here we're using \n for line endings, because you're using vi, so you're probably on some kind of unix, and that's how they have their line endings.

Now, there's one thing we could improve here. Indentation.

```<code>:%s/\(\s+\)\(.*\)\bcheck_free_set_to_null(\([^()]+\))/\1\2if (\3)\n\1{\n\1    free(\3)\n\1    printf("freed")\n\1}\nelse\n{\n\1    printf("could not free")\n\1    return (\3)\n\1}/g
</code>```

Here I grab the indentation into \1, everything else on the line into \2, and the method parameter into \3. Which might let you make it a bit prettier.

But again: whatever you're trying to do here is probably the wrong thing to do. Tell us what the REAL problem is! Don't fix it this way! This way is BAD! THIS WAY HAS WEASELS AND ROACHES IN IT! AND THE WEASELS WON'T EVEN EAT THE ROACHES FOR YOU!

Title: how to replace a function by it content

Body:
How can I replace all occurrences of

check_free_set_to_null(&pointer)
by

if (pointer)
{
    free(pointer)
    printf(pointer have been freed)
}
else
{
    printf(pointer couldnt had been freed)
    return (1)
}

// maybe using some sort of

{1} = check_free_set_to_null(CONTENT)

if ({1})
{
    free({1})
    printf({1} have been freed)
}
else
{
    printf({1} couldnt had been freed)
    return (1)
}

how could I do that ? (take note thats its not exactly what that have to be replaced, its just an example) Im not looking for the compiler to interpret it as multiple line, im looking for modifying the file.

Body:
Basically exactly how you said, except...

This is one of those questions where the right answer is probably "Here's how to do the stupid thing you're asking to do, but PLEASE REALLY PLEASE tell us what your real problem is, that you're trying to solve, because this almost certainly isn't the right way to do it."

First, the search string should be (this is for vim, because I see the tag vim. If you want to do it using some other replacement regex thing, let us know which. Perl, php, sed, awk, the bash commandline, something?):

:%s/\bcheck_free_set_to_null\(([^()]+)\)/ replacement text goes here /g

That presumes (possibly incorrectly) that there are never any braces inside the function - if that might be the case, then you are venturing into recursive regular expression territory, and in that case, you are definitely, definitely doing the wrong thing.

Your replacement string should be whatever your method will contain - in your example, it'd be:

:%s/\bcheck_free_set_to_null(\([^()]+\))/if (\1)\n{\n    free(\1)\n    printf("freed")\n}\nelse\n{\n    printf("could not free")\n    return (\1)\n}/g

Here we're using \n for line endings, because you're using vi, so you're probably on some kind of unix, and that's how they have their line endings.

Now, there's one thing we could improve here. Indentation.

:%s/\(\s+\)\(.*\)\bcheck_free_set_to_null(\([^()]+\))/\1\2if (\3)\n\1{\n\1    free(\3)\n\1    printf("freed")\n\1}\nelse\n{\n\1    printf("could not free")\n\1    return (\3)\n\1}/g

Here I grab the indentation into \1, everything else on the line into \2, and the method parameter into \3. Which might let you make it a bit prettier.

But again: whatever you're trying to do here is probably the wrong thing to do. Tell us what the REAL problem is! Don't fix it this way! This way is BAD! THIS WAY HAS WEASELS AND ROACHES IN IT! AND THE WEASELS WON'T EVEN EAT THE ROACHES FOR YOU!


问:
Capistrano - Ruby on Rails application
I have a very simple ruby on rails application and I want to use capistrano to deploy it.

It took me some time to configure the project and deploy the application and I'm not sure I made it right.

There are multiple gems in the gemfile, ok. When I run gem list puma in the server it returns null, which means that the gem 'puma' is not installed in the server, right?

but I've just deployed the application via capistrano, shouldn't all the gems in the gemfile be properly installed?

and then I thought: is capistrano supposed to install gems in the deploy?

My application is simple and I'm spending way more time to deploy and launch it than I should. Is it so complex to deploy and ruby on rails app?

答: Go to your current directory of your application folder and try running the command with bundle exec.</p>

Title: Capistrano - Ruby on Rails application


问:
Select email that triggers script
I am working on a Outlook script that will automatically select an email, and download the attachments, from a specific sender.

Reports are generated on a database and emailed to a specified address.

The next step is to automatically download those reports to a specified folder. Currently if an email comes in from the specified sender the script downloads attachments from the currently selected email.

I need the script to run on the email that triggers the script.

Public Sub SaveAttachments(Item As Outlook.MailItem)
    Dim objOL As Outlook.Application
    Dim objMsg As Outlook.MailItem 'Object
    Dim objAttachments As Outlook.Attachments
    Dim objSelection As Outlook.Selection
    Dim i As Long
    Dim lngCount As Long
    Dim strFile As String
    Dim strFolderpath As String
    Dim strDeletedFiles As String

    'Get the path to the target folder
    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    On Error Resume Next

    'Instantiate an Outlook Application Object
    Set objOL = CreateObject("Outlook.Application")

    'Get the collection of selected objects
    Set objSelection = objOL.ActiveExplorer.Selection

    'Set the Attachment folder
    strFolderpath = strFolderpath & "\Attachments\"

    'Check each selected item for attachements. If attachments exist, save them
    'to the strFOlderPath folder and strip them from the item.
    For Each objMsg In objSelection

    'This code only strips attachments from mail items.
    'If objMsg.class=olMail Then
    'Get the Attachments collection of the item
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFile = ""

    If lngCount > 0 Then

        'A count down loop needs to be used for removing items
        'from a collection. Otherwise the loop counter gets
        'confused and only every other item is removed

        For i = lngCount To 1 Step -1

            'Save attachment before deleting from item.
            'Get the file name
            strFile = objAttachments.Item(i).FileName

            'Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            'Save the attachment as a file
            objAttachments.Item(i).SaveAsFile strFile

            'Delete the attachment
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the
            'message check from html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFile = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "
" & "" & strFile & ""
            End If

            'use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        'Adds the filename string to the message body and save it
        'Checks for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The File(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
        Else
            objMsg.HTMLBody = "
" & "The file(s) were saved to " & strDeletedFiles & "
" & objMsg.HTMLBody
        End If
        objMsg.Save
    End If
    Next

Exit Sub:

    Set objAttachments = Nothing
    Set objMsg = Nothing
    Set objSelection = Nothing
    Set objOL = Nothing
End Sub
```

答:
I made some changes and this code does the intended purpose.</p>

```<code>Public Sub SaveAttachments(Item As Outlook.MailItem)
Dim objOL As Outlook.Application
Dim objAttachments As Outlook.Attachments
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

'Get the path to the target folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

'Instantiate an Outlook Application Object
Set objOL = CreateObject("Outlook.Application")

'Set the Attachment folder
strFolderpath = strFolderpath & "\Attachments\"

'Check each selected item for attachements. If attachments exist, save them
'to the strFOlderPath folder and strip them from the item.
For Each objAttachments In Item.Attachments

    'This code only strips attachments from mail items.
    'If objMsg.class=olMail Then
    'Get the Attachments collection of the item
    Set objAttachments = Item.Attachments
    lngCount = objAttachments.Count
    strDeletedFile = ""

    If lngCount > 0 Then

        'A count down loop needs to be used for removing items
        'from a collection. Otherwise the loop counter gets
        'confused and only every other item is removed

        For i = lngCount To 1 Step -1

            'Save attachment before deleting from item.
            'Get the file name
            strFile = objAttachments.Item(i).FileName

            'Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            'Save the attachment as a file
            objAttachments.Item(i).SaveAsFile strFile

            'Delete the attachment
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the
            'message check from html and use html tags in link
            If Item.BodyFormat <> olFormatHTML Then
                strDeletedFile = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        'Adds the filename string to the message body and save it
        'Checks for HTML body
        If Item.BodyFormat <> olFormatHTML Then
             Item.Body = vbCrLf & "The File(s) were saved to " & strDeletedFiles & vbCrLf & Item.Body
         Else
            Item.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & Item.HTMLBody
        End If
        Item.Save
    End If
Next objAttachments

Exit Sub:

Set objAttachments = Nothing
Set objOL = Nothing
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Select email that triggers script

Body:
I made some changes and this code does the intended purpose.

Public Sub SaveAttachments(Item As Outlook.MailItem)
Dim objOL As Outlook.Application
Dim objAttachments As Outlook.Attachments
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

'Get the path to the target folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

'Instantiate an Outlook Application Object
Set objOL = CreateObject("Outlook.Application")

'Set the Attachment folder
strFolderpath = strFolderpath & "\Attachments\"

'Check each selected item for attachements. If attachments exist, save them
'to the strFOlderPath folder and strip them from the item.
For Each objAttachments In Item.Attachments

    'This code only strips attachments from mail items.
    'If objMsg.class=olMail Then
    'Get the Attachments collection of the item
    Set objAttachments = Item.Attachments
    lngCount = objAttachments.Count
    strDeletedFile = ""

    If lngCount > 0 Then

        'A count down loop needs to be used for removing items
        'from a collection. Otherwise the loop counter gets
        'confused and only every other item is removed

        For i = lngCount To 1 Step -1

            'Save attachment before deleting from item.
            'Get the file name
            strFile = objAttachments.Item(i).FileName

            'Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            'Save the attachment as a file
            objAttachments.Item(i).SaveAsFile strFile

            'Delete the attachment
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the
            'message check from html and use html tags in link
            If Item.BodyFormat <> olFormatHTML Then
                strDeletedFile = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        'Adds the filename string to the message body and save it
        'Checks for HTML body
        If Item.BodyFormat <> olFormatHTML Then
             Item.Body = vbCrLf & "The File(s) were saved to " & strDeletedFiles & vbCrLf & Item.Body
         Else
            Item.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & Item.HTMLBody
        End If
        Item.Save
    End If
Next objAttachments

Exit Sub:

Set objAttachments = Nothing
Set objOL = Nothing
End Sub


问:
RhinoMocks use default implementation for property
I have some code that I use with Entity Framework like

```<code>class Person{
  pubic Person() {
     Address = new Address();
  }
  public virtual Address Address { get; set; }
}
</code>```

The reason I'm marking Address as virtual is for lazy loading.

Now to test, I'm stubbing the Person.  But since it's stubbed, the Address getter just returns null (even though it's set in the constructor).  If I stub out the Address property (person.Stub(x => x.Address).Return(new Address());) things work fine.  But I don't really want to have to stub out the property!  Is there any way to tell RhinoMocks not to override this getter even though it's virtual?

答:
Sure, but you have to use a partial mock:</p>

```<code>var person = MockRepository.GeneratePartialMock<Person>();
</code>```

Body:
I have some code that I use with Entity Framework like

class Person{
  pubic Person() {
     Address = new Address();
  }
  public virtual Address Address { get; set; }
}

The reason I'm marking Address as virtual is for lazy loading.

Now to test, I'm stubbing the Person.  But since it's stubbed, the Address getter just returns null (even though it's set in the constructor).  If I stub out the Address property (person.Stub(x => x.Address).Return(new Address());) things work fine.  But I don't really want to have to stub out the property!  Is there any way to tell RhinoMocks not to override this getter even though it's virtual?

Body:
Sure, but you have to use a partial mock:

var person = MockRepository.GeneratePartialMock<Person>();


问:
gridview using datatable in asp.net is not show every column
here is my aspx code:

```<code>  <div class="box-body">

        <asp:GridView ID="gvSms" runat="server" CssClass="table table-bordered table-striped">
        </asp:GridView>
    </div>
</code>```

here is my cs code:

```<code>if(!Page.IsPostBack)
        {
            Master.pageHeaderTitle = "Employee Sms";
            DataTable dt = new DataTable();
            dt.Columns.Add("Employee Code");
            dt.Columns.Add("Employee Name");
            dt.Columns.Add("Mobile No");
            dt.Columns.Add("Message");
            dt.Columns.Add("Creating Date");
            var db = new HRContext();
            var data=db.EmployeeSms.Where(d => d.HasRead == false).OrderByDescending(d => d.Id).ToList();
            if(data!=null)
            {
                foreach(var item in data)
                {
                    string mobile = item.EmployeeMobile.TrimStart('8').TrimStart('8');
                    var emp = db.Employee.Where(d => d.OfficePhone == mobile).FirstOrDefault();
                    string code = "";
                    string name = "";
                    if(emp!=null)
                    {
                        code = emp.eployeId;
                        name = emp.firstName + " " + emp.lastName;
                    }
                    dt.Rows.Add(code,name,item.EmployeeMobile,item.SMS,item.CreatedAt);
                }
            }

            gvSms.DataSource = dt;
            gvSms.DataBind();

        }
</code>```

using this code creating date column is not shown because of  long message in one line. if message column make comment out then it shown. So how can i fixed this? is it make message column multiline or make gridview scrollable. i tried but can't.
Any kind of help is appreciable and thanks in advance.

答:
First of all you should have set the data type of Date column to DateTime or varchar in Database and then use:

```<code>string date = DateTime.Now.ToString("d/MM/yyyy");
dt.Rows.Add(code,name,item.EmployeeMobile,item.SMS,date);
</code>```

Body:
here is my aspx code:

        <asp:GridView ID="gvSms" runat="server" CssClass="table table-bordered table-striped">
        </asp:GridView>

here is my cs code:

if(!Page.IsPostBack)
        {
            Master.pageHeaderTitle = "Employee Sms";
            DataTable dt = new DataTable();
            dt.Columns.Add("Employee Code");
            dt.Columns.Add("Employee Name");
            dt.Columns.Add("Mobile No");
            dt.Columns.Add("Message");
            dt.Columns.Add("Creating Date");
            var db = new HRContext();
            var data=db.EmployeeSms.Where(d => d.HasRead == false).OrderByDescending(d => d.Id).ToList();
            if(data!=null)
            {
                foreach(var item in data)
                {
                    string mobile = item.EmployeeMobile.TrimStart('8').TrimStart('8');
                    var emp = db.Employee.Where(d => d.OfficePhone == mobile).FirstOrDefault();
                    string code = "";
                    string name = "";
                    if(emp!=null)
                    {
                        code = emp.eployeId;
                        name = emp.firstName + " " + emp.lastName;
                    }
                    dt.Rows.Add(code,name,item.EmployeeMobile,item.SMS,item.CreatedAt);
                }
            }

            gvSms.DataSource = dt;
            gvSms.DataBind();

        }

using this code creating date column is not shown because of  long message in one line. if message column make comment out then it shown. So how can i fixed this? is it make message column multiline or make gridview scrollable. i tried but can't.
Any kind of help is appreciable and thanks in advance.

Body:
First of all you should have set the data type of Date column to DateTime or varchar in Database and then use:

string date = DateTime.Now.ToString("d/MM/yyyy");
dt.Rows.Add(code,name,item.EmployeeMobile,item.SMS,date);


问:
Django project can't be deployed to Heroku
I am trying to deploy Django project.
Firstly, I get this error:

```<code>Counting objects: 74, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (65/65), done.
Writing objects: 100% (74/74), 25.74 KiB | 0 bytes/s, done.
Total 74 (delta 24), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Failed to detect app matching https://codon-
buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz buildpack
remote:        More info:
https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to nicoplus.
remote:
To https://git.heroku.com/nicoplus.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/nicoplus.git'
</code>```

Then, I set the buildpack:
    ```heroku buildpacks:set heroku/python```
But, it still throw an error:
    ```remote: -----> Failed to detect app matching <a href="https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz" rel="nofollow noreferrer">https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz</a> buildpack```
So, any solution to this problem?

PS: python is 2.7.12

答:
Looking through the Heroku docs I came across this:

"A number of additional, unsupported runtimes are available. However, we only endorse and support the use of Python 3.6.1 and 2.7.13."

My guess is that using 2.7.12 is throwing it off.

Body:
I am trying to deploy Django project.
Firstly, I get this error:

Counting objects: 74, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (65/65), done.
Writing objects: 100% (74/74), 25.74 KiB | 0 bytes/s, done.
Total 74 (delta 24), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Failed to detect app matching https://codon-
buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz buildpack
remote:        More info:
https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to nicoplus.
remote:
To https://git.heroku.com/nicoplus.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/nicoplus.git'

Then, I set the buildpack:

heroku buildpacks:set heroku/python

But, it still throw an error:

remote: -----> Failed to detect app matching https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz buildpack

So, any solution to this problem?

PS: python is 2.7.12


问:
How to access Android activity class instance fields?
Suppose I have 2 classes that extends Activity; ActivityA and ActivityB, and they are declared properly in the manifest XML.

Now, what I want to do is call ActivityB from ActivityA and access ActivityB's fields.

```<code>Intent myIntent = new Intent(MyApplication.getInstance().getApplicationContext(), ActivityB.getClass());
startActivityForResult(myIntent,0);
</code>```

This code does not return an object of ActivityB, I have tried instantiation manually such that:

```<code>ActivityB actB=new ActivityB();
</code>```

That's ok, but how to pass that to an intent?

Is that possible?

答:
Now, what I want to do is call ActivityB from ActivityA and access ActivityB's fields.

Please don't.

First, short of passing activities around via static data members or via a service, it is impossible.

Second, you will create garbage collection issues, as Android will want to destroy old activities to free up memory, but after it does, you will still be holding references to those activities from other activities, negating the work.

Third, you will sometimes be holding destroyed instances of the other activities, for the same reason as in the previous point -- Android will go on destroying activities whether you like it or not.

I am fairly confident that whatever problem you think you are solving this way can be solved in some other way.

EDIT

Normally, you pass data from ActivityA to ActivityB via Intent extras on the Intent passed to startActivity(). It is ActivityB's responsibility to extract those extras and do something with them.

Body:
Suppose I have 2 classes that extends Activity; ActivityA and ActivityB, and they are declared properly in the manifest XML.

Now, what I want to do is call ActivityB from ActivityA and access ActivityB's fields.

Intent myIntent = new Intent(MyApplication.getInstance().getApplicationContext(), ActivityB.getClass());
startActivityForResult(myIntent,0);

This code does not return an object of ActivityB, I have tried instantiation manually such that:

ActivityB actB=new ActivityB();

That's ok, but how to pass that to an intent?

Is that possible?


问:
Spring-Boot ignores @Qualifier annotation
I am migrating an active Spring web app to spring boot(1.4.2).

The beans are defined in an XML as it is being loaded with @ImportResource.

4 of the beans that I am starting are an instance of the same object BasicDataSource.

To tell spring which one to load I have set an ID for each one and using @Qualifier to bind the correct bean to the variable.

But it seems to be that Spring ignores my @Qualifier and throwing "No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 4: DataSource1, DataSource2, DataSource3, DataSource4"

P.S - Note that the class that has the @Qualifier is an abstract class, and the class that is failing to instantiate is an extending class, however @Qualifier has @Inherited.

XML

```<code><beans
    xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:task="http://www.springframework.org/schema/task"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.2.xsd
   http://www.springframework.org/schema/jee
   http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
   http://www.springframework.org/schema/task
   http://www.springframework.org/schema/task/spring-task-3.2.xsd
   http://www.springframework.org/schema/cache
   http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

<context:load-time-weaver aspectj-weaving="on"/>
<cache:annotation-driven mode="aspectj"/>
<context:property-override location="file:/app/config/dataSourceOverride.cfg"/>
<context:annotation-config />

<bean id="DataSource1" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="4" />
</bean>

<bean id="DataSource2" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="3" />
</bean>

<bean id="DataSource3" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="2" />
</bean>

<bean id="DataSource4" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="1" />
</bean>
</code>```

Spring boot app main

```<code>package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan("com.app")
@ImportResource("com/app/startup/spring.xml")
public class SpringBootServer {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootServer.class, args);

    }
}
</code>```

Abstract Class

```<code>public abstract class GenericDao {

    public GenericDao() {

    }

    private Logger logger = LoggerFactory.getLogger(GenericDao.class);

    @Autowired
    @Qualifier("DataSource1")
    protected BasicDataSource dataSource1Impl;

    @Autowired
    @Qualifier("DataSource2")
    protected BasicDataSource dataSource2Impl;

    @Autowired
    @Qualifier("DataSource3")
    protected BasicDataSource dataSource3Impl;

    @Autowired
    @Qualifier("DataSource4")
    protected BasicDataSource dataSource4Impl;
}
</code>```

Solid Calss

```<code>@Component("widgetsDao")
public class WidgetsDao extends GenericDao {

##Some methods##

}
</code>```

Exception

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field dataSource1Impl in com.app.dal.GenericDao required a single bean, but 4 were found:
    - DataSource1: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource2: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource3: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource4: defined in class path resource [com/app/startup/app-spring.xml]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
</code>```

What could possibly make spring to ignore my @Qualifier annotation??

Thanks Ahead.

答:
As Jake stated, @Primary annotation should be added at least to get rid of this error. Plus:

If you are fetching your datasource properties from an external file, start your primary datasource's properties (i.e. url, user, pass etc) with spring.datasource in order to override Spring Boot's default inner datasource which is Derby, HSQL or so depending on your configuration.

Body:
I am migrating an active Spring web app to spring boot(1.4.2).

The beans are defined in an XML as it is being loaded with @ImportResource.

4 of the beans that I am starting are an instance of the same object BasicDataSource.

To tell spring which one to load I have set an ID for each one and using @Qualifier to bind the correct bean to the variable.

But it seems to be that Spring ignores my @Qualifier and throwing "No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 4: DataSource1, DataSource2, DataSource3, DataSource4"

P.S - Note that the class that has the @Qualifier is an abstract class, and the class that is failing to instantiate is an extending class, however @Qualifier has @Inherited.

XML

<beans
    xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:task="http://www.springframework.org/schema/task"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.2.xsd
   http://www.springframework.org/schema/jee
   http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
   http://www.springframework.org/schema/task
   http://www.springframework.org/schema/task/spring-task-3.2.xsd
   http://www.springframework.org/schema/cache
   http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

<context:load-time-weaver aspectj-weaving="on"/>
<cache:annotation-driven mode="aspectj"/>
<context:property-override location="file:/app/config/dataSourceOverride.cfg"/>
<context:annotation-config />

<bean id="DataSource1" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="4" />
</bean>

<bean id="DataSource2" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="3" />
</bean>

<bean id="DataSource3" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="2" />
</bean>

<bean id="DataSource4" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="1" />
</bean>

Spring boot app main

package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan("com.app")
@ImportResource("com/app/startup/spring.xml")
public class SpringBootServer {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootServer.class, args);

    }
}

Abstract Class

public abstract class GenericDao {

    public GenericDao() {

    }

    private Logger logger = LoggerFactory.getLogger(GenericDao.class);

    @Autowired
    @Qualifier("DataSource1")
    protected BasicDataSource dataSource1Impl;

    @Autowired
    @Qualifier("DataSource2")
    protected BasicDataSource dataSource2Impl;

    @Autowired
    @Qualifier("DataSource3")
    protected BasicDataSource dataSource3Impl;

    @Autowired
    @Qualifier("DataSource4")
    protected BasicDataSource dataSource4Impl;
}

Solid Calss

@Component("widgetsDao")
public class WidgetsDao extends GenericDao {

##Some methods##

}

Exception

***************************
APPLICATION FAILED TO START
***************************

Description:

Field dataSource1Impl in com.app.dal.GenericDao required a single bean, but 4 were found:
    - DataSource1: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource2: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource3: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource4: defined in class path resource [com/app/startup/app-spring.xml]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

What could possibly make spring to ignore my @Qualifier annotation??

Thanks Ahead.


问:
How do I encode HTTP GET query strings in Perl?
This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

```<code>use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);
</code>```

答:
URI::Escape is probably the most direct answer, as other have given, but I would recommend using a URI object for the entire thing.  URI automatically escapes the GET parameters for you (using URI::Escape).

```<code>my $uri = URI->new( 'http://example.com' );
$uri->query_form(foo => '1 2', bar => 2);
print $uri; ## http://example.com?foo=1+2&bar=2
</code>```

As an added bonus, LWP::Simple's get function will take a URI object as it's argument instead of a string.

OwnerDisplayName: cdleary

Body:
This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);

LastEditorDisplayName: cdleary

Body:
URI::Escape is probably the most direct answer, as other have given, but I would recommend using a URI object for the entire thing.  URI automatically escapes the GET parameters for you (using URI::Escape).

my $uri = URI->new( 'http://example.com' );
$uri->query_form(foo => '1 2', bar => 2);
print $uri; ## http://example.com?foo=1+2&bar=2

As an added bonus, LWP::Simple's get function will take a URI object as it's argument instead of a string.

OwnerDisplayName: gpojd

LastEditorDisplayName: gpojd