问:
how to Smooth catmull rom spline curve when it is moving like amaging wire in libgdx
i have tried to move my curve but it is not moving well, when it changes its direction from left to right or right to left then the movement is quite awkward.
i want to move my curve like this video
video of curve movement what i actually want.
In this video when a it change its direction it is so graceful but in my case it change its direction and the curve gives a crazy shape at newly added point.
Experts please solve this problem.
here is my code </p>

```<code>//create paths
private Bezier<Vector2> path1;
private CatmullRomSpline<Vector2> path2;
private ShapeRenderer sr;
int height,width;
Vector2 starting,ending,endingControl;
ArrayList<Vector2> listOfPoints;
Vector3 touchPos;
float timeDifference;
Boolean leftPos=false,rightPos=false;
Boolean isTouch=false,isTouchUp=false;
Vector2 mVector2;
private OrthographicCamera cam;
Vector2[] controlPoints;

@Override
public void create () {

     width = Gdx.graphics.getWidth();
     height = Gdx.graphics.getHeight();
     ending=new Vector2(width/2,height/2);
     endingControl=new Vector2(ending.x,ending.y+10);
     starting=new Vector2(width/2,0);

    controlPoints = new Vector2[]{starting,starting,ending,ending};

    // set up the curves

    path2 = new CatmullRomSpline<Vector2>(controlPoints, false);
    listOfPoints=new ArrayList<Vector2>();
    // setup ShapeRenderer
    sr = new ShapeRenderer();
    sr.setAutoShapeType(true);
    sr.setColor(Color.BLACK);
    cam=new OrthographicCamera();
    cam.setToOrtho(false);
    listOfPoints.add(new Vector2(width/2,0)); //starting
    listOfPoints.add(new Vector2(width/2,0)); //starting

}

@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub
    super.resize(width, height);

    cam.update();
}

@Override
public void render () {
    cam.update();
    Gdx.gl.glClearColor(1f, 1f, 1f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    sr.begin();
    sr.set(ShapeType.Filled);

    if(Gdx.input.isTouched())
    {

        if(!isTouch){
            listOfPoints.add(new Vector2(ending.x+2, ending.y-4));

            int s=listOfPoints.size();
            controlPoints=new Vector2[s+2];
            listOfPoints.toArray(controlPoints);

            controlPoints[s]=ending;
            //endingControl.x=ending.y;
            controlPoints[s+1]=ending;
            path2 = new CatmullRomSpline<Vector2>(controlPoints, false);

        }

        isTouch=true;
        ending.x+=3;

    }
    else {

        if(isTouch){
            listOfPoints.add(new Vector2(ending.x-2, ending.y-4));
           int s=listOfPoints.size();
            controlPoints=new Vector2[s+2];
            listOfPoints.toArray(controlPoints);

            controlPoints[s]=ending;

            controlPoints[s+1]=ending;

            path2 = new CatmullRomSpline<Vector2>(controlPoints, false);

        }
        isTouch=false;
        ending.x-=3;

    }

    moveAndReduce();

    for(int i = 0; i < 100; ++i){
        float t = i /100f;
        Vector2 st = new Vector2();
        Vector2 end = new Vector2();
        path2.valueAt(st,t);
        path2.valueAt(end, t-0.01f);
        sr.rectLine(st.x, st.y, end.x, end.y,3);

    }

    sr.end();

}

@Override
public void dispose () {
    sr.dispose();
}

public void moveAndReduce()
{
    for(Vector2 vector2:listOfPoints)
    {
        vector2.y-=3 ;

    }
    if(listOfPoints.size()>3 && listOfPoints.get(3).y<-1)
    {

        listOfPoints.remove(0);
        listOfPoints.set(0, listOfPoints.get(1));
        int s=listOfPoints.size();
        controlPoints=new Vector2[s+2];
        listOfPoints.toArray(controlPoints);
        controlPoints[s]=ending;
        controlPoints[s+1]=ending;
        path2 = new CatmullRomSpline<Vector2>(controlPoints, false);
    }
}
</code>```

答:
Going by the video the curve does not look like it is constrained by control points but just a simple trace of and accelerating point.

You create an array of floats the length in pixels matching the length of the line in the x direction. For example if screen is 200 pixels wide the line can be 100 so the array is 100 in length. Set each float in the array to the start value half the screen height. I call the array line in this answer. You call it what you like.

The you assign a head index that is the index of the rightmost point. Each frame you move the head index up by one. If it is over the array length-1 you set it to zero (beginning of array)

Rendering the Path

When you draw the line you draw all the points from head + 1

```<code>Path p = new Path();
for(int i = 0; i < 100; ++i){
   p.lineTo(i, line[(i + head + 1) % 100]); // add path points
}
// draw the path;
</code>```

Moving up and down

To make it move you have a movement float move that is 0 for no movement or positive and negative values the move up or down.

When you want it to move increase the move amount by a fixed value.

```<code>// moving down
if(move < maxMove){  // set a max move amount eg 10
    move += moveAmount;  // moveAmount 0.2 just as an example
}
</code>```

Same for moving up, but subtract

When there is no input you move the move amount back to zero by a fixed rate

```<code>// assume this is code run when no input
if(move != 0){
    if(Math.abs(move) < moveAmount){ // if close to zero set to zero
       move = 0;
    }else{
       move -= Math.sign(move) * moveAmount; // else move towards zero at
                                             // fixed rate
    }
}
</code>```

Moving forward

The line does not move forward, just appears to do so as we move the head position up the array each frame.

Back to moving the line's head the following move the line head position up or down (but is not complete the last line is modified to create a smoother curve)

```<code>float pos = line[head]; // get the pos of line at head
head += 1; // move the head forward 1
head %= 100; // if past end of array move to 0
line[head] = pos + move; // set the new head position
</code>```

A better curve

This will move the head of the line up or down depending on move. The curve we get is not that nice so to make it a little smoother you need to change the rate the move value changes the head position.

```<code>// an sCurve for any value of move the result is  from -1 to 1
// the greater or smaller move the closer to 1 or -1 the value gets
// the value -1.2 controls the rate at which the value moves to 1 or -1
// the closer to -1 the value is the slower the value moves to 1 or -1
float res =  (2 / (1 + Math.pow(move,-1.2))) -1;
</code>```

This in effect changes the shape of the lines curve to a almost sine wave when moving up and down

```<code>// so instead of
//line[head] = pos + move; // set the new head position
line[head] = pos + ( (2 / (1 + Math.pow(move,-1.2))) -1 ) * maxSpeed;
// max speed is the max speed the line head can move up or down
// per frame in pixels.
</code>```

Example to show the curve

Below is a Javascript implementation that does it as outlined above (is not intended as answer code). Use the keyboard Arrow Up and Arrow down to move the line

If you are using a tablet or phone then the following image is what you will see as way to late for me to add and test touch for the example

const doFor = (count, callback) => {var i = 0; while (i < count) { callback(i ++) } };
const keys = {
    ArrowUp : false,
    ArrowDown : false,
};
function keyEvents(e){
    if(keys[e.code] !== undefined){
        keys[e.code] = event.type === "keydown";
        e.preventDefault();
    }
}
addEventListener("keyup", keyEvents);
addEventListener("keydown", keyEvents);
focus();
var gameOver = 0;
var gameOverWait = 100;
var score = 0;
var nextWallIn = 500
var nextWallCount = nextWallIn;
var wallHole = 50;
const wallWidth = 5;
const walls = [];
function addWall(){
  var y = (Math.random() * (H - wallHole  * 2)) + wallHole *0.5;
  walls.push({
      x : W,
      top : y,
      bottom : y + wallHole,
      point : 1, // score point
  });
}
function updateWalls(){
   nextWallCount += 1;
   if(nextWallCount >= nextWallIn){
      addWall();
      nextWallCount = 0;
      nextWallIn -= 1;
      wallHole -= 1;
   }
   for(var i = 0; i < walls.length; i ++){
      var w = walls[i];
      w.x -= 1;
      if(w.x < -wallWidth){
        walls.splice(i--,1);
      }
      if(w.x >= line.length- + wallWidth && w.x < line.length){
          var pos = line[head];
          if(pos < w.top || pos > w.bottom){
              gameOver = gameOverWait;
          }
      }
      if(w.point > 0 && w.x <= line.length){
        score += w.point;
        w.point = 0;
      }
   }
}
function drawWalls(){
  for(var i = 0; i < walls.length; i ++){
      var w = walls[i];
      ctx.fillStyle = "red";
      ctx.fillRect(w.x,0,wallWidth,w.top);
      ctx.fillRect(w.x,w.bottom,wallWidth,H-w.bottom);
  }
}
const sCurve = (x,p) =>  (2 / (1 + Math.pow(p,-x))) -1;
const ctx = canvas.getContext("2d");
var W,H; // canvas width and height
const line = [];
var move = 0;
var curvePower = 1.2;
var curveSpeed = 0.2;
var maxSpeed = 10;
var headMoveMultiply = 2;
var head;
function init(){
  line.length = 0;
  doFor(W / 2,i => line[i] = H / 2);
  head = line.length - 1;
  move = 0;
  walls.length = 0;
  score = 0;
  nextWallIn = 500
  nextWallCount = nextWallIn;
  wallHole = 50;
  ctx.font = "30px arial black";
}
function stepLine(){
  var pos = line[head];
  head += 1;
  head %= line.length;

  line[head] = pos + sCurve(move,curvePower)*headMoveMultiply ;

}
function drawLine(){
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.lineWidth = 3;
  ctx.lineJoin = "round";
  ctx.lineCap = "round";
  for(var i = 0; i <line.length; i++){
    ctx.lineTo(i,line[(i + head + 1) % line.length]);
  }
  ctx.stroke();
}

function mainLoop(time){
    if(canvas.width !== innerWidth || canvas.height !== innerHeight){
        W = canvas.width = innerWidth;
        H = canvas.height = innerHeight;
        init();
    }
    if(gameOver === 1){
      gameOver = 0;
      init();
    }
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,W,H);
    if(keys.ArrowUp){
        if(move > - maxSpeed){
          move -= curveSpeed;
        }

    }else if(keys.ArrowDown){
        if(move < maxSpeed){
           move += curveSpeed;
        }
    }else{
        move -= Math.sign(move)*curveSpeed;
        if(Math.abs(move) < curveSpeed){
            move = 0;
        }
    }
    if(gameOver === 0){
        stepLine();
        updateWalls();
    }
    drawLine();
    drawWalls();
    ctx.fillStyle = "Black";
    ctx.textAlign = "left";
    ctx.fillText("Score : " + score, 10,30);
    if(gameOver > 0){
        ctx.textAlign = "center";
        ctx.fillText("Crashed !!", W / 2,H * 0.4);
        gameOver -= 1;
    }
    requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
    position : absolute;
    top : 0px;
    left : 0px;
    z-index : -10;
}</code>```

Up down arrow keys to move line.
<canvas id=canvas></canvas>```

Body:
i have tried to move my curve but it is not moving well, when it changes its direction from left to right or right to left then the movement is quite awkward.
i want to move my curve like this video
video of curve movement what i actually want.
In this video when a it change its direction it is so graceful but in my case it change its direction and the curve gives a crazy shape at newly added point.
Experts please solve this problem.
here is my code

//create paths
private Bezier<Vector2> path1;
private CatmullRomSpline<Vector2> path2;
private ShapeRenderer sr;
int height,width;
Vector2 starting,ending,endingControl;
ArrayList<Vector2> listOfPoints;
Vector3 touchPos;
float timeDifference;
Boolean leftPos=false,rightPos=false;
Boolean isTouch=false,isTouchUp=false;
Vector2 mVector2;
private OrthographicCamera cam;
Vector2[] controlPoints;

@Override
public void create () {

     width = Gdx.graphics.getWidth();
     height = Gdx.graphics.getHeight();
     ending=new Vector2(width/2,height/2);
     endingControl=new Vector2(ending.x,ending.y+10);
     starting=new Vector2(width/2,0);

    controlPoints = new Vector2[]{starting,starting,ending,ending};

    // set up the curves

    path2 = new CatmullRomSpline<Vector2>(controlPoints, false);
    listOfPoints=new ArrayList<Vector2>();
    // setup ShapeRenderer
    sr = new ShapeRenderer();
    sr.setAutoShapeType(true);
    sr.setColor(Color.BLACK);
    cam=new OrthographicCamera();
    cam.setToOrtho(false);
    listOfPoints.add(new Vector2(width/2,0)); //starting
    listOfPoints.add(new Vector2(width/2,0)); //starting

}

@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub
    super.resize(width, height);

    cam.update();
}

@Override
public void render () {
    cam.update();
    Gdx.gl.glClearColor(1f, 1f, 1f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    sr.begin();
    sr.set(ShapeType.Filled);

    if(Gdx.input.isTouched())
    {

        if(!isTouch){
            listOfPoints.add(new Vector2(ending.x+2, ending.y-4));

            int s=listOfPoints.size();
            controlPoints=new Vector2[s+2];
            listOfPoints.toArray(controlPoints);

            controlPoints[s]=ending;
            //endingControl.x=ending.y;
            controlPoints[s+1]=ending;
            path2 = new CatmullRomSpline<Vector2>(controlPoints, false);

        }

        isTouch=true;
        ending.x+=3;

    }
    else {

        if(isTouch){
            listOfPoints.add(new Vector2(ending.x-2, ending.y-4));
           int s=listOfPoints.size();
            controlPoints=new Vector2[s+2];
            listOfPoints.toArray(controlPoints);

            controlPoints[s]=ending;

            controlPoints[s+1]=ending;

            path2 = new CatmullRomSpline<Vector2>(controlPoints, false);

        }
        isTouch=false;
        ending.x-=3;

    }

    moveAndReduce();

    for(int i = 0; i < 100; ++i){
        float t = i /100f;
        Vector2 st = new Vector2();
        Vector2 end = new Vector2();
        path2.valueAt(st,t);
        path2.valueAt(end, t-0.01f);
        sr.rectLine(st.x, st.y, end.x, end.y,3);

    }

    sr.end();

}

@Override
public void dispose () {
    sr.dispose();
}

public void moveAndReduce()
{
    for(Vector2 vector2:listOfPoints)
    {
        vector2.y-=3 ;

    }
    if(listOfPoints.size()>3 && listOfPoints.get(3).y<-1)
    {

        listOfPoints.remove(0);
        listOfPoints.set(0, listOfPoints.get(1));
        int s=listOfPoints.size();
        controlPoints=new Vector2[s+2];
        listOfPoints.toArray(controlPoints);
        controlPoints[s]=ending;
        controlPoints[s+1]=ending;
        path2 = new CatmullRomSpline<Vector2>(controlPoints, false);
    }
}

Body:
Going by the video the curve does not look like it is constrained by control points but just a simple trace of and accelerating point.

You create an array of floats the length in pixels matching the length of the line in the x direction. For example if screen is 200 pixels wide the line can be 100 so the array is 100 in length. Set each float in the array to the start value half the screen height. I call the array line in this answer. You call it what you like.

The you assign a head index that is the index of the rightmost point. Each frame you move the head index up by one. If it is over the array length-1 you set it to zero (beginning of array)

Rendering the Path

When you draw the line you draw all the points from head + 1

Path p = new Path();
for(int i = 0; i < 100; ++i){
   p.lineTo(i, line[(i + head + 1) % 100]); // add path points
}
// draw the path;

Moving up and down

To make it move you have a movement float move that is 0 for no movement or positive and negative values the move up or down.

When you want it to move increase the move amount by a fixed value.

// moving down
if(move < maxMove){  // set a max move amount eg 10
    move += moveAmount;  // moveAmount 0.2 just as an example
}

Same for moving up, but subtract

When there is no input you move the move amount back to zero by a fixed rate

// assume this is code run when no input
if(move != 0){
    if(Math.abs(move) < moveAmount){ // if close to zero set to zero
       move = 0;
    }else{
       move -= Math.sign(move) * moveAmount; // else move towards zero at
                                             // fixed rate
    }
}

Moving forward

The line does not move forward, just appears to do so as we move the head position up the array each frame.

Back to moving the line's head the following move the line head position up or down (but is not complete the last line is modified to create a smoother curve)

float pos = line[head]; // get the pos of line at head
head += 1; // move the head forward 1
head %= 100; // if past end of array move to 0
line[head] = pos + move; // set the new head position

A better curve

This will move the head of the line up or down depending on move. The curve we get is not that nice so to make it a little smoother you need to change the rate the move value changes the head position.

// an sCurve for any value of move the result is  from -1 to 1
// the greater or smaller move the closer to 1 or -1 the value gets
// the value -1.2 controls the rate at which the value moves to 1 or -1
// the closer to -1 the value is the slower the value moves to 1 or -1
float res =  (2 / (1 + Math.pow(move,-1.2))) -1;

This in effect changes the shape of the lines curve to a almost sine wave when moving up and down

// so instead of
//line[head] = pos + move; // set the new head position
line[head] = pos + ( (2 / (1 + Math.pow(move,-1.2))) -1 ) * maxSpeed;
// max speed is the max speed the line head can move up or down
// per frame in pixels.

Example to show the curve

Below is a Javascript implementation that does it as outlined above (is not intended as answer code). Use the keyboard Arrow Up and Arrow down to move the line

If you are using a tablet or phone then the following image is what you will see as way to late for me to add and test touch for the example

const doFor = (count, callback) => {var i = 0; while (i < count) { callback(i ++) } };
const keys = {
    ArrowUp : false,
    ArrowDown : false,
};
function keyEvents(e){
    if(keys[e.code] !== undefined){
        keys[e.code] = event.type === "keydown";
        e.preventDefault();
    }
}
addEventListener("keyup", keyEvents);
addEventListener("keydown", keyEvents);
focus();
var gameOver = 0;
var gameOverWait = 100;
var score = 0;
var nextWallIn = 500
var nextWallCount = nextWallIn;
var wallHole = 50;
const wallWidth = 5;
const walls = [];
function addWall(){
  var y = (Math.random() * (H - wallHole  * 2)) + wallHole *0.5;
  walls.push({
      x : W,
      top : y,
      bottom : y + wallHole,
      point : 1, // score point
  });
}
function updateWalls(){
   nextWallCount += 1;
   if(nextWallCount >= nextWallIn){
      addWall();
      nextWallCount = 0;
      nextWallIn -= 1;
      wallHole -= 1;
   }
   for(var i = 0; i < walls.length; i ++){
      var w = walls[i];
      w.x -= 1;
      if(w.x < -wallWidth){
        walls.splice(i--,1);
      }
      if(w.x >= line.length- + wallWidth && w.x < line.length){
          var pos = line[head];
          if(pos < w.top || pos > w.bottom){
              gameOver = gameOverWait;
          }
      }
      if(w.point > 0 && w.x <= line.length){
        score += w.point;
        w.point = 0;
      }
   }
}
function drawWalls(){
  for(var i = 0; i < walls.length; i ++){
      var w = walls[i];
      ctx.fillStyle = "red";
      ctx.fillRect(w.x,0,wallWidth,w.top);
      ctx.fillRect(w.x,w.bottom,wallWidth,H-w.bottom);
  }
}
const sCurve = (x,p) =>  (2 / (1 + Math.pow(p,-x))) -1;
const ctx = canvas.getContext("2d");
var W,H; // canvas width and height
const line = [];
var move = 0;
var curvePower = 1.2;
var curveSpeed = 0.2;
var maxSpeed = 10;
var headMoveMultiply = 2;
var head;
function init(){
  line.length = 0;
  doFor(W / 2,i => line[i] = H / 2);
  head = line.length - 1;
  move = 0;
  walls.length = 0;
  score = 0;
  nextWallIn = 500
  nextWallCount = nextWallIn;
  wallHole = 50;
  ctx.font = "30px arial black";
}
function stepLine(){
  var pos = line[head];
  head += 1;
  head %= line.length;

  line[head] = pos + sCurve(move,curvePower)*headMoveMultiply ;

}
function drawLine(){
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.lineWidth = 3;
  ctx.lineJoin = "round";
  ctx.lineCap = "round";
  for(var i = 0; i <line.length; i++){
    ctx.lineTo(i,line[(i + head + 1) % line.length]);
  }
  ctx.stroke();
}

function mainLoop(time){
    if(canvas.width !== innerWidth || canvas.height !== innerHeight){
        W = canvas.width = innerWidth;
        H = canvas.height = innerHeight;
        init();
    }
    if(gameOver === 1){
      gameOver = 0;
      init();
    }
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,W,H);
    if(keys.ArrowUp){
        if(move > - maxSpeed){
          move -= curveSpeed;
        }

    }else if(keys.ArrowDown){
        if(move < maxSpeed){
           move += curveSpeed;
        }
    }else{
        move -= Math.sign(move)*curveSpeed;
        if(Math.abs(move) < curveSpeed){
            move = 0;
        }
    }
    if(gameOver === 0){
        stepLine();
        updateWalls();
    }
    drawLine();
    drawWalls();
    ctx.fillStyle = "Black";
    ctx.textAlign = "left";
    ctx.fillText("Score : " + score, 10,30);
    if(gameOver > 0){
        ctx.textAlign = "center";
        ctx.fillText("Crashed !!", W / 2,H * 0.4);
        gameOver -= 1;
    }
    requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);

canvas {
    position : absolute;
    top : 0px;
    left : 0px;
    z-index : -10;
}

<br><br><br>Up down arrow keys to move line.
<canvas id=canvas></canvas>


来源: stackexchange

问:
vb.net escape reserved keywords in sql statement
I'm trying to execute an sql statement in vb.net to an Access database, I am escaping the reserverd word using square brackets []. This has worked in all my SELECT statements within the program.

The reserved word is level

But the SQL statement below fails saying

Syntax error in INSERT INTO statement.

If I directly copy the statement and execute this in Access it works fine

```<code>datalayer.getDataTable(String.Format("INSERT INTO users (username, password, [level]) VALUES ({0}, {1}, {2})", username, password, level))
</code>```

The above statement works if I remove [level] and replace this with another column name.

Thanks.

答:
You're not enclosing your values in quotation marks.  Try this:

```<code>datalayer.getDataTable(String.Format(
 "INSERT INTO users (username, password, [level]) VALUES ('{0}', '{1}', '{2}')",
 username, password, level))
</code>```

However, as Andrew says, you should really use parameters.  In Access SQL (David W Fenton will come along shortly and say it's "Jet" SQL) you have to use positional parameters.  Your statement would then look like this:

```<code>INSERT INTO users (username, password, [level]) VALUES (?, ?, ?)
</code>```

You'd need to create OleDbParameter objects with the correct values, and an OleDbCommand with the text above to execute in order to do your insert.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to execute an sql statement in vb.net to an Access database, I am escaping the reserverd word using square brackets []. This has worked in all my SELECT statements within the program.

The reserved word is level

But the SQL statement below fails saying

Syntax error in INSERT INTO statement.

If I directly copy the statement and execute this in Access it works fine

datalayer.getDataTable(String.Format("INSERT INTO users (username, password, [level]) VALUES ({0}, {1}, {2})", username, password, level))

The above statement works if I remove [level] and replace this with another column name.

Thanks.

Body:
You're not enclosing your values in quotation marks.  Try this:

datalayer.getDataTable(String.Format(
 "INSERT INTO users (username, password, [level]) VALUES ('{0}', '{1}', '{2}')",
 username, password, level))

However, as Andrew says, you should really use parameters.  In Access SQL (David W Fenton will come along shortly and say it's "Jet" SQL) you have to use positional parameters.  Your statement would then look like this:

INSERT INTO users (username, password, [level]) VALUES (?, ?, ?)

You'd need to create OleDbParameter objects with the correct values, and an OleDbCommand with the text above to execute in order to do your insert.


问:
Combining multiple 'elsif' statements
I try to programm snakes in Ruby. In order to get myself more familiar with Ruby. I define the position of every part of the snake through saving its X and Y value in two 1D arrays one for a X value and one for a Y value.

```<code> $x = [2,...]
 $y = [2,...]
</code>```

(What I forgot to tell is that the head of the Snake moves through user input while the rest just inherits its position from the part before like this.)

```<code>def length(f)
if $length >= f
    $y[f] = $y[f-1]
    $x[f] = $x[f-1]
end
end
</code>```

In order to get a field for the Snake to move around I programmed this.

```<code>for a in (1..20)
  for b in (1..20)
    print " X "
  end
  puts" "
end
</code>```

Which gives me a 20*20 field.

I then tried to display every part of the snake like on the field like this.(While also drawing a boarder around the field.)

```<code>for a in (1..20)
for b in (1..20)
    if a == 1 || a == 20
        if b == 1 || b == 20
            print " + "
        else
            print " - "
        end
    elsif b == 1 || b == 20
        print " | "
    elsif a == $x[0] && b == $y[0]
        body
    elsif a == $x[1] && b == $y[1]
        body
    elsif a == $x[2] && b == $y[2]
        body
    elsif a == $x[3] && b == $y[3]
        body
    elsif a == $x[4] && b == $y[4]
        body
    else
        print "   "
    end

end
puts""
end
</code>```

This works but if the user is really good/ has a lot of spare time I need to make allot of elsif for every one represents a part of the snake if the snake should have as a limit a length of 100 I would need to make 100 elsif statements.(The body is just:

```<code>def body
print " # ".green
end
</code>```

)

I tried fixing it with a for loop like this:

```<code>for c in (1..100)
  if a == $x[c] && b == $y[c]
    body
  end
end
</code>```

and this

```<code> loop do
    $x.size.times do |index|
        if $x[index] == a && $y[index] == b
            body
        end
    end
    break
 end
</code>```

But sadly this didn't gave the desired outcome for this interfered with the ifthat draws the boarders of the field.

Is there a way to combine these multiple elsif statements?

Every help would be highly appreciated. ( Sorry for being to vague in the first draft.)

答:
Recommended Refactorings

NB: You included no sample data in your original post, so your mileage with answers will vary.

You have a number of issues, not just one. Besides not being DRY, your code is also not very testable because it's not broken out into discrete operations. There are a number of things you can (and probably should) do:

Break your "body" stuff into discrete methods.

Use Array or Enumerator methods to simplify the data.

Use dynamic methods to loop over your arrays, rather than fixed ranges or for-loops.

Use case/when statements inside your loop to handle multiple conditionals for the same variable.

In short, you need to refactor your code to be more modular, and to leverage the language to iterate over your data objects rather than using one conditional per element as you're currently doing.

Simplify Your Data Set and Handle Procedurally

As an example, consider the following:

```<code>def handle_matched_values array
end

def handle_mismatched_values array
end

paired_array = a.zip b

matched_pairs   = paired_array.select { |subarray| subarray[0] == subarray[1] }
unmatched_pairs = paired_array.reject { |subarray| subarray[0] == subarray[1] }

matched_pairs.each { |pair| handle_matched_values pair }
matched_pairs.each { |pair| handle_mismatched_values pair }
</code>```

In this example, you may not even need an if statement. Instead, you could use Array#select or Array#reject to find indices that match whatever criteria you want, and then call the relevant handler for the results. This has the advantage of being very procedural, and makes it quite clear what data set and handler are being paired. It's also quite readable, which is extremely important.

Dynamic Looping and Case Statements

If you truly need to handle your data within a single loop, use a case statement to clean up your conditions. For example:

```<code># Extract methods to handle each case.
def do_something_with data; end
def do_something_else_with data; end
def handle_borders data; end

# Construct your data any way you want.
paired_array  = a.zip b

# Loop over your data to evaluate each pair of values.
paired_array.each do |pair|
  case pair
  when a == b
    do_something_with pair
  when a == paired_array.first || paired_array.last
     handle_borders pair
  else
     do_something_else_with pair
  end
end
</code>```

There are certainly plenty of other ways to work pairwise with a large data set. The goal is to give you a basic structure for refactoring your code. The rest is up to you!

ContentLicense: CC BY-SA 3.0

Title: Combining multiple 'elsif' statements

Body:
I try to programm snakes in Ruby. In order to get myself more familiar with Ruby. I define the position of every part of the snake through saving its X and Y value in two 1D arrays one for a X value and one for a Y value.

 $x = [2,...]
 $y = [2,...]

(What I forgot to tell is that the head of the Snake moves through user input while the rest just inherits its position from the part before like this.)

def length(f)
if $length >= f
    $y[f] = $y[f-1]
    $x[f] = $x[f-1]
end
end

In order to get a field for the Snake to move around I programmed this.

for a in (1..20)
  for b in (1..20)
    print " X "
  end
  puts" "
end

Which gives me a 20*20 field.

I then tried to display every part of the snake like on the field like this.(While also drawing a boarder around the field.)

for a in (1..20)
for b in (1..20)
    if a == 1 || a == 20
        if b == 1 || b == 20
            print " + "
        else
            print " - "
        end
    elsif b == 1 || b == 20
        print " | "
    elsif a == $x[0] && b == $y[0]
        body
    elsif a == $x[1] && b == $y[1]
        body
    elsif a == $x[2] && b == $y[2]
        body
    elsif a == $x[3] && b == $y[3]
        body
    elsif a == $x[4] && b == $y[4]
        body
    else
        print "   "
    end

end
puts""
end

This works but if the user is really good/ has a lot of spare time I need to make allot of elsif for every one represents a part of the snake if the snake should have as a limit a length of 100 I would need to make 100 elsif statements.(The body is just:

def body
print " # ".green
end

)

I tried fixing it with a for loop like this:

for c in (1..100)
  if a == $x[c] && b == $y[c]
    body
  end
end

and this

 loop do
    $x.size.times do |index|
        if $x[index] == a && $y[index] == b
            body
        end
    end
    break
 end

But sadly this didn't gave the desired outcome for this interfered with the ifthat draws the boarders of the field.

Is there a way to combine these multiple elsif statements?

Every help would be highly appreciated. ( Sorry for being to vague in the first draft.)

Body:
Recommended Refactorings

NB: You included no sample data in your original post, so your mileage with answers will vary.

You have a number of issues, not just one. Besides not being DRY, your code is also not very testable because it's not broken out into discrete operations. There are a number of things you can (and probably should) do:

Break your "body" stuff into discrete methods.

Use Array or Enumerator methods to simplify the data.

Use dynamic methods to loop over your arrays, rather than fixed ranges or for-loops.

Use case/when statements inside your loop to handle multiple conditionals for the same variable.

In short, you need to refactor your code to be more modular, and to leverage the language to iterate over your data objects rather than using one conditional per element as you're currently doing.

Simplify Your Data Set and Handle Procedurally

As an example, consider the following:

def handle_matched_values array
end

def handle_mismatched_values array
end

paired_array = a.zip b

matched_pairs   = paired_array.select { |subarray| subarray[0] == subarray[1] }
unmatched_pairs = paired_array.reject { |subarray| subarray[0] == subarray[1] }

matched_pairs.each { |pair| handle_matched_values pair }
matched_pairs.each { |pair| handle_mismatched_values pair }

In this example, you may not even need an if statement. Instead, you could use Array#select or Array#reject to find indices that match whatever criteria you want, and then call the relevant handler for the results. This has the advantage of being very procedural, and makes it quite clear what data set and handler are being paired. It's also quite readable, which is extremely important.

Dynamic Looping and Case Statements

If you truly need to handle your data within a single loop, use a case statement to clean up your conditions. For example:

# Extract methods to handle each case.
def do_something_with data; end
def do_something_else_with data; end
def handle_borders data; end

# Construct your data any way you want.
paired_array  = a.zip b

# Loop over your data to evaluate each pair of values.
paired_array.each do |pair|
  case pair
  when a == b
    do_something_with pair
  when a == paired_array.first || paired_array.last
     handle_borders pair
  else
     do_something_else_with pair
  end
end

There are certainly plenty of other ways to work pairwise with a large data set. The goal is to give you a basic structure for refactoring your code. The rest is up to you!


问:
Pull properties from an object by their name into a different object
i'm doing a project in VueJS and i have an array of data, which consists of a number of objects.

These objects are pulled from a PHP Backend and consist of values like

id: 2123
name: "Name Value"
status: "active"
account_id: "2KGGALS2353255"

Imagine i want to split these by the keys names into a similar array but i want to have a parent object that consists of two child objects

```<code>[
    0: {
     core: {
       id: 2123
       name: "Name Value"
     },
     extra: {
       status: "active",
       account_id: "2KGGALS2353255"
     }
]
</code>```

The question is how can i achieve this with Javascript? I don't really want to modify the data in PHP beforehand unless this is something very unadvised to do in Javascript.
I can use VueJS and Lodash.

答:
Using ES6's object destructuring, and the object rest spread proposal, which requires a babel transform, you can Array#map the array into a new array of objects in the required format:

const arr = [{"id":1,"name":"Name1","status":"active","account_id":"2KGGALS2353255"},{"id":2,"name":"Name2","status":"active","account_id":"4ABCLS2353255"},{"id":3,"name":"Name3","status":"active","account_id":"6LMNALS2353255"}];

const result = arr.map(({ id, name, ...extra }) => ({
  core: {
    id,
    name
  },
  extra
}));

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

<p>You can do the same thing using lodash's <code>_.pick()</code> to the get the <strong>core</strong>, and <code>_.omit()</code> to get the <strong>extra</strong>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [{"id":1,"name":"Name1","status":"active","account_id":"2KGGALS2353255"},{"id":2,"name":"Name2","status":"active","account_id":"4ABCLS2353255"},{"id":3,"name":"Name3","status":"active","account_id":"6LMNALS2353255"}];

var result = arr.map(function(obj) {
  return {
    core: _.pick(obj, ['id', 'name']),
    extra: _.omit(obj, ['id', 'name'])
  };
});

console.log(result);</code>```

```

Body:
i'm doing a project in VueJS and i have an array of data, which consists of a number of objects.

These objects are pulled from a PHP Backend and consist of values like

id: 2123
name: "Name Value"
status: "active"
account_id: "2KGGALS2353255"

Imagine i want to split these by the keys names into a similar array but i want to have a parent object that consists of two child objects

[
    0: {
     core: {
       id: 2123
       name: "Name Value"
     },
     extra: {
       status: "active",
       account_id: "2KGGALS2353255"
     }
]

The question is how can i achieve this with Javascript? I don't really want to modify the data in PHP beforehand unless this is something very unadvised to do in Javascript.
I can use VueJS and Lodash.

Body:
Using ES6's object destructuring, and the object rest spread proposal, which requires a babel transform, you can Array#map the array into a new array of objects in the required format:

const arr = [{"id":1,"name":"Name1","status":"active","account_id":"2KGGALS2353255"},{"id":2,"name":"Name2","status":"active","account_id":"4ABCLS2353255"},{"id":3,"name":"Name3","status":"active","account_id":"6LMNALS2353255"}];

const result = arr.map(({ id, name, ...extra }) => ({
  core: {
    id,
    name
  },
  extra
}));

console.log(result);

You can do the same thing using lodash's _.pick() to the get the core, and _.omit() to get the extra:

var arr = [{"id":1,"name":"Name1","status":"active","account_id":"2KGGALS2353255"},{"id":2,"name":"Name2","status":"active","account_id":"4ABCLS2353255"},{"id":3,"name":"Name3","status":"active","account_id":"6LMNALS2353255"}];

var result = arr.map(function(obj) {
  return {
    core: _.pick(obj, ['id', 'name']),
    extra: _.omit(obj, ['id', 'name'])
  };
});

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
Entity Framework optimistic concurrency exceptions occur when multi SaveChanges
I using Entity Framework 6. After calling SaveChanges method twice in my code, after DeleteObject, a ConcurrencyException occurred:

```<code>entities.DeleteObject(pu);

// First time
entities.Context.SaveChanges(SaveOptions.None);

// everything is ok

// Second Time
entities.Context.SaveChanges(SaveOptions.None);

// Concurrency exception
</code>```

But with using AddObject this exception did not occur !

Exception message is:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Handling optimistic concurrency exceptions.

How I can control multiple SaveChanges calls before AcceptAllChanges without a concurrency exception?

答: Are you calling the AcceptAllChanges() method before the second save? My understanding is that if you use SaveOptions.None, the context keeps the changes so they can be resubmitted to the database. If the first SaveChanges() succeeds, than the rowversion is updated in the db, but in the context, everything is kept as it was, so the second time it causes the conflict on the rowversion.</p>

Body:
I using Entity Framework 6. After calling SaveChanges method twice in my code, after DeleteObject, a ConcurrencyException occurred:

entities.DeleteObject(pu);

// First time
entities.Context.SaveChanges(SaveOptions.None);

// everything is ok

// Second Time
entities.Context.SaveChanges(SaveOptions.None);

// Concurrency exception

But with using AddObject this exception did not occur !

Exception message is:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Handling optimistic concurrency exceptions.

How I can control multiple SaveChanges calls before AcceptAllChanges without a concurrency exception?


问:
Xcode 8: Interface builder shows different color that set
Take a look at the picture below:

This is the same hex used in both places #28647B.
The lower part is set from code and appears to reflects the color properly:

```<code>let proxy = UIPageControl.appearance()
proxy.pageIndicatorTintColor = UIColor.lightGray.withAlphaComponent(0.6)
proxy.currentPageIndicatorTintColor = UIColor.white
proxy.backgroundColor = UIColor(red: 40.0/255.0, green: 100.0/255.0, blue: 123.0/255.0, alpha: 1.0)
</code>```

The upper part is set in interface builder.

I checked all other layers, opacity parameters etc and found nothing that can change the way this color look.

Now interesting part, I inspected both colors using HexColor mac app, this is the result:

for upper part:

Not sure what does it mean that RGB factors vary from the correct ones, but result is correct

Now, time to inspect the lower part:

This time RGB looks good but results is different.

Now it's the best part:

When I set the background color from code as I did in appearance proxy, it works fine. Is something interface builder speciffic that changes the visible shade of background color? How can one rely on colors set in Interface Builder?

答:
Same problem in my projects, I solved this issue choosing "Device RGB" and not "Generic RGB". Some. time the color not change , move opacity and the color will set.
see the image:

Body:
Take a look at the picture below:

This is the same hex used in both places #28647B.
The lower part is set from code and appears to reflects the color properly:

let proxy = UIPageControl.appearance()
proxy.pageIndicatorTintColor = UIColor.lightGray.withAlphaComponent(0.6)
proxy.currentPageIndicatorTintColor = UIColor.white
proxy.backgroundColor = UIColor(red: 40.0/255.0, green: 100.0/255.0, blue: 123.0/255.0, alpha: 1.0)

The upper part is set in interface builder.

I checked all other layers, opacity parameters etc and found nothing that can change the way this color look.

Now interesting part, I inspected both colors using HexColor mac app, this is the result:

for upper part:

Not sure what does it mean that RGB factors vary from the correct ones, but result is correct

Now, time to inspect the lower part:

This time RGB looks good but results is different.

Now it's the best part:

When I set the background color from code as I did in appearance proxy, it works fine. Is something interface builder speciffic that changes the visible shade of background color? How can one rely on colors set in Interface Builder?


问:
Image doesn't show in Wordpress but does in HTML/CSS
I have a div with a background image and text inside, but this doesn't show in Wordpress. However it works fine in HTML/CSS, as you can see here https://fiddle.jshell.net/tLavv0w1/

When I try to look at the code in Firefox developer tools, the CSS doesn't show. So it seems that the CSS doesn't connect with the HTML at all. I have also tried to change the div's name but it didn't work. I don't even know where to look for clues. Any help is much appreciated!

答:
You are referencing http://localhost/ so when run locally, it works, but when run on the server, it won't. Change the URLs to legit URLs

https://fiddle.jshell.net/tLavv0w1/3/


问:
react-onclickoutside don't work on iframe
I create the custom drop-down list based on the reactjs. I use react-onclickoutside for detecting of click in outside area and closing the my drop-down list. It work very good but not work for click in iframe area.

```<code>import onClickOutside from 'react-onclickoutside';

...

class DevicesGroupsFilter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            showGroups: false,
        };
        this.renderGroups = this.renderGroups.bind(this);
        this.handleClickOutside = this.handleClickOutside.bind(this);
        this.handleOnClick = this.handleOnClick.bind(this);
    }

    handleClickOutside(evt) {
        this.setState({showGroups: false});
    }

    handleOnClick(event) {
        this.setState({showGroups: !this.state.showGroups});
    }

    ...

    renderGroups() {
        if (this.state.showGroups) {
            return (<DevicesGroupsFilterList />)
        }
        return ""
    }

    render() {
        let className = "filter-wrap";
        if (this.state.showGroups) {
            className += " filter-dropped-down";
        }

        return (
            <div className={className} id={this.props.elementId} >
                {this.renderGroups()}
            </div>
        )
    }
}

module.exports = {
    DevicesGroupsFilter: onClickOutside(DevicesGroupsFilter),
}
</code>```

using (pass elementId through props of the react component):

```<code>ReactDOM.render(
        <DevicesGroupsFilter
                ...
                elementId={"my-groups-filter"}
                ...
        />, document.getElementById('place-groups-filter'))
</code>```

答:
I found the solution based on iframeTracker jQuery Plugin for my problem.
1. Install the plugin

```<code>npm install jquery.iframetracker
</code>```

2. Wrap the IFrame by div with class iframetrack

```<code><div class="iframetrack" id="my-iframe-id">
    <iframe src="{{ src_url }}" seamless
    style="position: absolute; border: none; zoom:1.0; overflow-y:visible;"
    frameborder="0" width="100%" scrolling="auto" id="i-frame">
    {% trans "Your browser does not support the <iframe> tag" %}
    </iframe>
</div>
</code>```

3. Add the callback handler for a blur event of the wrapped iframe

```<code>$('.iframetrack iframe').iframeTracker({
    blurCallback: function()
    {
        // click when the list dropped down only.
        if ($('#my-groups-filter').hasClass('filter-dropped-down'))
        {
            $('.filter-content').trigger('click');
        }
    }
});
</code>```

When we release the mouse button (mouse up) in the wrapped iframe area the blurCallback execute. In this callback  we check the filter has or not the class 'filter-dropped-down'. If the filter has this class then we generate click for his closing.

Body:
I create the custom drop-down list based on the reactjs. I use react-onclickoutside for detecting of click in outside area and closing the my drop-down list. It work very good but not work for click in iframe area.

import onClickOutside from 'react-onclickoutside';

...

class DevicesGroupsFilter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            showGroups: false,
        };
        this.renderGroups = this.renderGroups.bind(this);
        this.handleClickOutside = this.handleClickOutside.bind(this);
        this.handleOnClick = this.handleOnClick.bind(this);
    }

    handleClickOutside(evt) {
        this.setState({showGroups: false});
    }

    handleOnClick(event) {
        this.setState({showGroups: !this.state.showGroups});
    }

    ...

    renderGroups() {
        if (this.state.showGroups) {
            return (<DevicesGroupsFilterList />)
        }
        return ""
    }

    render() {
        let className = "filter-wrap";
        if (this.state.showGroups) {
            className += " filter-dropped-down";
        }

        return (

                {this.renderGroups()}

        )
    }
}

module.exports = {
    DevicesGroupsFilter: onClickOutside(DevicesGroupsFilter),
}

using (pass elementId through props of the react component):

ReactDOM.render(
        <DevicesGroupsFilter
                ...
                elementId={"my-groups-filter"}
                ...
        />, document.getElementById('place-groups-filter'))

Body:
I found the solution based on iframeTracker jQuery Plugin for my problem.
1. Install the plugin

npm install jquery.iframetracker

2. Wrap the IFrame by div with class iframetrack

<div class="iframetrack" id="my-iframe-id">
    <iframe src="{{ src_url }}" seamless
    style="position: absolute; border: none; zoom:1.0; overflow-y:visible;"
    frameborder="0" width="100%" scrolling="auto" id="i-frame">
    {% trans "Your browser does not support the <iframe> tag" %}
    </iframe>
</div>

3. Add the callback handler for a blur event of the wrapped iframe

$('.iframetrack iframe').iframeTracker({
    blurCallback: function()
    {
        // click when the list dropped down only.
        if ($('#my-groups-filter').hasClass('filter-dropped-down'))
        {
            $('.filter-content').trigger('click');
        }
    }
});

When we release the mouse button (mouse up) in the wrapped iframe area the blurCallback execute. In this callback  we check the filter has or not the class 'filter-dropped-down'. If the filter has this class then we generate click for his closing.


问:
ng new my-app unexpected token =
I have installed the angular2 cli via npm, but when I try to create a new typescript angular app with the command 'ng new my-app' I keep getting this error:

```<code>C:\Users\nicholas\AppData\Roaming\npm\node_modules\@angular\cli\models\config\config.js:15
    constructor(_configPath, schema, configJson, fallbacks = []) {
                                                           ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\Users\nicholas\AppData\Roaming\npm\node_modules\@angular\cli\models\config.js:2:18)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
</code>```

My NPM version is 4.1.2
My node version is 4.4.5 which from my understanding are acceptable versions for installing and using the angular-cli.

Please let me know if there is a fix to this, I have also tried uninstalling, cleaning npm cache and reinstalling but I keep getting the same issue.

Any and all help is very appreciated, thanks in advance!

答:
As of 2017-06-03, using Angular-CLI 1.1.0, NodeJS 7.10.0, npm 5.0.2, Angular 4.1.3, TypeScript 2.3.4, I experienced the error of the Original Poster (OP) in Visual Studio 2017 during Task Runner Explorer, running the build task (ng build as defined in package.json).

I launched a PowerShell prompt, navigated to the directory where the package.json lives, and invoked ng build from the command line, and it experienced zero errors.

That immediately raised my suspicions that it was a PATH (within VS 2017) issue that was causing the error to appear in VS 2017's Task Runner output window.

Sure enough, under Tools / Options / Projects and Solutions / Web Package Management / External Tools, I had to move the entry for $(PATH) up above $(VSINSTALLDIR)\Web\External and (in my case at least) below .\node_modules.bin.

Once I did all of the above, I was able to right-click on build (under the Custom tab) of Task Runner Explorer and this time it was successful.

Before anybody replies, keep in mind the following:

This is VERY SPECIFIC to Visual Studio 2017 in which an Angular 4.1.3 application is being developed to (hopefully) peacefully co-exist with ASP.Net Core 1.1.

I have TypeScript 2.3 globally installed and locally installed.

I have the very latest NodeJS and NPM editions (as of the time of writing this post at least).

The techniques I used that resolved this issue for me may not work for you.

Bottom line: it might be the order of where things are in your PATH that might be causing the error.

Title: ng new my-app unexpected token =

Body:
I have installed the angular2 cli via npm, but when I try to create a new typescript angular app with the command 'ng new my-app' I keep getting this error:

C:\Users\nicholas\AppData\Roaming\npm\node_modules\@angular\cli\models\config\config.js:15
    constructor(_configPath, schema, configJson, fallbacks = []) {
                                                           ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\Users\nicholas\AppData\Roaming\npm\node_modules\@angular\cli\models\config.js:2:18)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)

My NPM version is 4.1.2
My node version is 4.4.5 which from my understanding are acceptable versions for installing and using the angular-cli.

Please let me know if there is a fix to this, I have also tried uninstalling, cleaning npm cache and reinstalling but I keep getting the same issue.

Any and all help is very appreciated, thanks in advance!


问:
Writing Spark Streaming Output to a Socket
I have a DStream "Crowd" and I want to write each element in "Crowd" to a socket. When I try to read from that socket, it dosen't print anything. I am using following line of code:

```<code>val server = new ServerSocket(4000,200);
val conn = server.accept()
val out = new PrintStream(conn.getOutputStream());
crowd.foreachRDD(rdd => {rdd.foreach(record=>{out.println(record)})})
</code>```

But if use (this is not I want though):

```<code>crowd.foreachRDD(rdd => out.println(rdd))
</code>```

It does write something to the socket.

I suspect there is a problem with using rdd.foreach(). Although it should work. I am not sure what I am missing.

答:
Here in the official documentation you have the answer!

You have to create the connection inside of the foreachRDD function, and if you want to do it optimally you need to create a "pool" of connections, and then bring the connection you want inside of the foreachPartition function, and call to the foreach function to send the elements through that connection. This is the example code for doing it in the best way:

```<code>dstream.foreachRDD { rdd =>
  rdd.foreachPartition { partitionOfRecords =>
    // ConnectionPool is a static, lazily initialized pool of connections
    val connection = ConnectionPool.getConnection()
    partitionOfRecords.foreach(record => connection.send(record))
    ConnectionPool.returnConnection(connection)  // return to the pool for future reuse
  }
}
</code>```

In any case, check the other comments as they provide good knowledge about the context of the problem.

Body:
I have a DStream "Crowd" and I want to write each element in "Crowd" to a socket. When I try to read from that socket, it dosen't print anything. I am using following line of code:

val server = new ServerSocket(4000,200);
val conn = server.accept()
val out = new PrintStream(conn.getOutputStream());
crowd.foreachRDD(rdd => {rdd.foreach(record=>{out.println(record)})})

But if use (this is not I want though):

crowd.foreachRDD(rdd => out.println(rdd))

It does write something to the socket.

I suspect there is a problem with using rdd.foreach(). Although it should work. I am not sure what I am missing.

Body:
Here in the official documentation you have the answer!

You have to create the connection inside of the foreachRDD function, and if you want to do it optimally you need to create a "pool" of connections, and then bring the connection you want inside of the foreachPartition function, and call to the foreach function to send the elements through that connection. This is the example code for doing it in the best way:

dstream.foreachRDD { rdd =>
  rdd.foreachPartition { partitionOfRecords =>
    // ConnectionPool is a static, lazily initialized pool of connections
    val connection = ConnectionPool.getConnection()
    partitionOfRecords.foreach(record => connection.send(record))
    ConnectionPool.returnConnection(connection)  // return to the pool for future reuse
  }
}

In any case, check the other comments as they provide good knowledge about the context of the problem.


问:
Vertically align an image inside a div with responsive height
I have the following code which sets up a container which has a height that changes with the width when the browser is re-sized (to maintain a square aspect ratio).

HTML

```<code><div class="responsive-container">
    <div class="dummy"></div>
    <div class="img-container">
        <IMG HERE>
    </div>
</div>
</code>```

CSS

```<code>.responsive-container {
    position: relative;
    width: 100%;
    border: 1px solid black;
}

.dummy {
    padding-top: 100%; /* forces 1:1 aspect ratio */
}

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}
</code>```

How can I vertically align the IMG inside the container? All my images have variable heights and the container can't have a fixed height/line height because it's responsive... Please help!

答:
Make another div and add both 'dummy' and 'img-container' inside the div

Do HTML and CSS like follows

html , body {height:100%;}
.responsive-container { height:100%; display:table; text-align:center; width:100%;}
.inner-container {display:table-cell; vertical-align:middle;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="responsive-container">
    <div class="inner-container">
  <div class="dummy">Sample</div>
  <div class="img-container">
   Image tag
  </div>
 </div>
</div></code>```

Instead of 100% for the 'responsive-container' you can give the height that you want.,

Body:
I have the following code which sets up a container which has a height that changes with the width when the browser is re-sized (to maintain a square aspect ratio).

HTML

CSS

.responsive-container {
    position: relative;
    width: 100%;
    border: 1px solid black;
}

.dummy {
    padding-top: 100%; /* forces 1:1 aspect ratio */
}

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

How can I vertically align the IMG inside the container? All my images have variable heights and the container can't have a fixed height/line height because it's responsive... Please help!

Body:
Make another div and add both 'dummy' and 'img-container' inside the div

Do HTML and CSS like follows

html , body {height:100%;}
.responsive-container { height:100%; display:table; text-align:center; width:100%;}
.inner-container {display:table-cell; vertical-align:middle;}

<div class="responsive-container">
    <div class="inner-container">
  <div class="dummy">Sample</div>
  <div class="img-container">
   Image tag
  </div>
 </div>
</div>

Instead of 100% for the 'responsive-container' you can give the height that you want.,


问:
RSpec: how to test Rails logger message expectations?
I am trying to test that the Rails logger receives messages in some of my specs.  I am using the Logging gem.

Let's say that I have a class like this:

```<code>class BaseWorker

  def execute
    logger.info 'Starting the worker...'
  end

end
</code>```

And a spec like:

```<code>describe BaseWorker do

  it 'should log an info message' do
    base_worker = BaseWorker.new
    logger_mock = double('Logging::Rails').as_null_object
    Logging::Rails.stub_chain(:logger, :info).and_return(logger_mock)

    logger_mock.should_receive(:info).with('Starting the worker...')
    base_worker.execute
    Logging::Rails.unstub(:logger)
  end

end
</code>```

I get the following failure message:

```<code> Failure/Error: logger_mock.should_receive(:info).with('Starting worker...')
   (Double "Logging::Rails").info("Starting worker...")
       expected: 1 time
       received: 0 times
</code>```

I've tried out several different approaches to get the spec to pass.  This works for example:

```<code>class BaseWorker

  attr_accessor :log

  def initialize
    @log = logger
  end

  def execute
    @log.info 'Starting the worker...'
  end

end

describe BaseWorker do
  it 'should log an info message' do
    base_worker = BaseWorker.new
    logger_mock = double('logger')
    base_worker.log = logger_mock

    logger_mock.should_receive(:info).with('Starting the worker...')
    base_worker.execute
  end
end
</code>```

But having to setup an accessible instance variable like that seems like the tail is wagging the dog here. (Actually, I'm not even sure why copying logger to @log would make it pass.)

What's a good solution for testing the logging?

答:
If your goal is to test logging functionality you may also consider verifying the output to standard streams.

This will spare you the mocking process and test whether messages will actually end up where they supposed to (STDOUT/STDERR).

With RSpec's output matcher (introduced in 3.0) you can do the following:

```<code>expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr
</code>```

In case of libraries such as Logger or Logging you may have to use output.to_<>_from_any_process.

Body:
I am trying to test that the Rails logger receives messages in some of my specs.  I am using the Logging gem.

Let's say that I have a class like this:

class BaseWorker

  def execute
    logger.info 'Starting the worker...'
  end

end

And a spec like:

describe BaseWorker do

  it 'should log an info message' do
    base_worker = BaseWorker.new
    logger_mock = double('Logging::Rails').as_null_object
    Logging::Rails.stub_chain(:logger, :info).and_return(logger_mock)

    logger_mock.should_receive(:info).with('Starting the worker...')
    base_worker.execute
    Logging::Rails.unstub(:logger)
  end

end

I get the following failure message:

 Failure/Error: logger_mock.should_receive(:info).with('Starting worker...')
   (Double "Logging::Rails").info("Starting worker...")
       expected: 1 time
       received: 0 times

I've tried out several different approaches to get the spec to pass.  This works for example:

class BaseWorker

  attr_accessor :log

  def initialize
    @log = logger
  end

  def execute
    @log.info 'Starting the worker...'
  end

end

describe BaseWorker do
  it 'should log an info message' do
    base_worker = BaseWorker.new
    logger_mock = double('logger')
    base_worker.log = logger_mock

    logger_mock.should_receive(:info).with('Starting the worker...')
    base_worker.execute
  end
end

But having to setup an accessible instance variable like that seems like the tail is wagging the dog here. (Actually, I'm not even sure why copying logger to @log would make it pass.)

What's a good solution for testing the logging?

Body:
If your goal is to test logging functionality you may also consider verifying the output to standard streams.

This will spare you the mocking process and test whether messages will actually end up where they supposed to (STDOUT/STDERR).

With RSpec's output matcher (introduced in 3.0) you can do the following:

expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr

In case of libraries such as Logger or Logging you may have to use output.to_<>_from_any_process.


问:
How to determine whether a file has been closed
I'm writing a unit test, and I'm trying to find a way to test whether my class has properly closed a file handle (it uses old-style open() and close()). Ideally I'd like to be able to do it without having access to the actual handle - I want to be able to check a file in the file system and determine whether it is currently open elsewhere.

I've tried doing it through exclusive file locks, but I haven't had much luck. Besides, file locks are very much not cross-platform (this needs to work on Solaris, Linux and Windows).

Any suggestions?

答:
It's not a proper unit-test if you're relying on opening \ closing files like this - such tests can randomly fail for a variety of reasons, leading to false positives and general confusion. </p>

<p>Instead, consider abstracting away the file operations and ensuring that close is called on your representation of the file. </p>

Body:
It's not a proper unit-test if you're relying on opening \ closing files like this - such tests can randomly fail for a variety of reasons, leading to false positives and general confusion.

Instead, consider abstracting away the file operations and ensuring that close is called on your representation of the file.


答:
You're referencing localhost which means "the computer I am currently on".

If you change the URL to an image found online, it works.

See here: https://fiddle.jshell.net/tLavv0w1/1/

(I just used your stackoverflow image URL by right clicking it and "copy image address" -- this is what address it gave me: https://i.stack.imgur.com/V3nvj.jpg?s=32&g=1)

Title: Image doesn't show in Wordpress but does in HTML/CSS

Body:
I have a div with a background image and text inside, but this doesn't show in Wordpress. However it works fine in HTML/CSS, as you can see here https://fiddle.jshell.net/tLavv0w1/

When I try to look at the code in Firefox developer tools, the CSS doesn't show. So it seems that the CSS doesn't connect with the HTML at all. I have also tried to change the div's name but it didn't work. I don't even know where to look for clues. Any help is much appreciated!


问:
Delete git.io shortened URL
I wanted to shorten my GitHub repo's URL using git.io. I wanted a custom name but accidentally used their automatic name, which is full of random characters.

How can I revert this and get a new one?

答:
If someone else created it first, it will return the existing shortened URL. So, it is currently not possible to override but you can contact GitHub support team to either remove or change it.

I discovered following trick though, you can add a harmless query param ? to make it different:

```<code>$ curl -i https://git.io -F "url=YOUR_GITHUB_URL_HERE?" -F "code=YOUR_CUSTOM_NAME"
</code>```

Hope that helps.

Title: Delete git.io shortened URL

Body:
If someone else created it first, it will return the existing shortened URL. So, it is currently not possible to override but you can contact GitHub support team to either remove or change it.

I discovered following trick though, you can add a harmless query param ? to make it different:

$ curl -i https://git.io -F "url=YOUR_GITHUB_URL_HERE?" -F "code=YOUR_CUSTOM_NAME"

Hope that helps.

ContentLicense: CC BY-SA 4.0


问:
When the browser announces JavaScript codes time execution?
Sometimes when I load my website, this message appears in the console:

Why is this shown? Aren't my JS code optimized enough? And what should I do now?

答:
reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document.

Your Browser stops the execution of the script because reflow is user-blocking

Take a look at this List of what operations force reflow: https://gist.github.com/paulirish/5d52fb081b3570c81e3a


问:
Copy body of outlook mail to a text file
Is there any way to copy email body of an outlook mail to a text file using c#. I am not getting a way to do this</p>

答:
when using Interop this will help to save the whole mail as Text file. Then you can parse the file to get the body part and save it.</p>

```<code>mailItem.SaveAs(@"c:\path\to\save\mail.msg", Outlook.OlSaveAsType.olTXT);
</code>```

Body:
when using Interop this will help to save the whole mail as Text file. Then you can parse the file to get the body part and save it.

mailItem.SaveAs(@"c:\path\to\save\mail.msg", Outlook.OlSaveAsType.olTXT);


问:
How to create a string template: "some string {some_stub_var}"?
I want to create with a stub-template in it:

```<code>  my_str_template = "some string {some_stub_var}"
  # note that there's no variable "some_stub_var" in the current scope
</code>```

So that sometime later in my application I'm able to do something like this:

```<code>my_str = my_str_template.format(some_stub_var: "my_real_string_var_123")
</code>```

1) How to do that?

2) What's it called?

答:
Sounds like you're looking for a templating language.

There are many. A fairly simple one is called mustache.

bbmustache is an implementation in erlang.

You can add it to your mix file like so:

```<code>  defp deps do
    [
      {:bbmustache, "~> 1.4"},
    ]
  end
</code>```

and run mix deps.get to install.

Usage example:

```<code>iex(1)> :bbmustache.render("Hello {{who}}", %{ 'who' => "world" })
"Hello world"
</code>```

A bit of a snag for this library is that the keys in the map must be charlists (single quoted).

Body:
I want to create with a stub-template in it:

  my_str_template = "some string {some_stub_var}"
  # note that there's no variable "some_stub_var" in the current scope

So that sometime later in my application I'm able to do something like this:

my_str = my_str_template.format(some_stub_var: "my_real_string_var_123")

1) How to do that?

2) What's it called?

Body:
Sounds like you're looking for a templating language.

There are many. A fairly simple one is called mustache.

bbmustache is an implementation in erlang.

You can add it to your mix file like so:

  defp deps do
    [
      {:bbmustache, "~> 1.4"},
    ]
  end

and run mix deps.get to install.

Usage example:

iex(1)> :bbmustache.render("Hello {{who}}", %{ 'who' => "world" })
"Hello world"

A bit of a snag for this library is that the keys in the map must be charlists (single quoted).


问:
What is 'Editable' data type in Android?
The getText() method returns Editable datatype. Why does it not return String data type? What is the difference between Editable and String data type? I read about the Editable datatype on developers site, but I didn't understand properly.

答:
You can get string data easily just add</p>

```<code>submitbutton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String text = edittext.getText().toString();
    }
});
</code>```

Body:
You can get string data easily just add

submitbutton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String text = edittext.getText().toString();
    }
});


问:
broadcasting audio/video from android via udp to wifi and listen with vlc
I'm trying to broadcast a audio file from my android device via udp to the local wifi and have the clients on the local network listen to it via VLC's network streaming option. I can broadcast it and recieve it on anydevice connected to the network if i use my own recieve code, But i want VLC to be able to play it. Is ther any specific encoding or formatting that needs to be done before I send the datagram packet?

My sending code

```<code>public void SendAudio()
{
    Thread thrd = new Thread(new Runnable() {
        @Override
        public void run()
        {
            Log.e(LOG_TAG, "start send thread, thread id: "
                + Thread.currentThread().getId());
            long file_size = 0;
            int bytes_read = 0;
            int bytes_count = 0;
            File audio = new File(AUDIO_FILE_PATH);
            FileInputStream audio_stream = null;
            file_size = audio.length();
            byte[] buf = new byte[BUF_SIZE];
            try
            {
                InetAddress addr = InetAddress.getByName("192.168.1.255");
                DatagramSocket sock = new DatagramSocket();

                while(true){
                    bytes_count=0;
                    audio_stream = new FileInputStream(audio);
                while(bytes_count < file_size)
                {
                    bytes_read = audio_stream.read(buf, 0, BUF_SIZE);
                    DatagramPacket pack = new DatagramPacket(buf, bytes_read,
                            addr, AUDIO_PORT);
                    sock.send(pack);
                    bytes_count += bytes_read;
                    Log.d(LOG_TAG, "bytes_count : " + bytes_count);
                    Thread.sleep(SAMPLE_INTERVAL, 0);
                }
                }
            }
            catch (InterruptedException ie)
            {
                Log.e(LOG_TAG, "InterruptedException");
            }
            catch (FileNotFoundException fnfe)
            {
                Log.e(LOG_TAG, "FileNotFoundException");
            }
            catch (SocketException se)
            {
                Log.e(LOG_TAG, "SocketException");
            }
            catch (UnknownHostException uhe)
            {
                Log.e(LOG_TAG, "UnknownHostException");
            }
            catch (IOException ie)
            {
                Log.e(LOG_TAG, "IOException");
            }
        } // end run
    });
    thrd.start();
}
</code>```

My Recieving Code`

```<code>public void RecvAudio()
{
    Thread thrd = new Thread(new Runnable() {
        @Override
        public void run()
        {
            Log.e(LOG_TAG, "start recv thread, thread id: "
                + Thread.currentThread().getId());
            AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC,
                    SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, BUF_SIZE,
                    AudioTrack.MODE_STREAM);
            track.play();
            try
            {
                DatagramSocket sock = new DatagramSocket(AUDIO_PORT);
                byte[] buf = new byte[BUF_SIZE];

                while(true)
                {

                    DatagramPacket pack = new DatagramPacket(buf, BUF_SIZE);
                    sock.receive(pack);
                    Log.d(LOG_TAG, "recv pack: " + pack.getLength());
                    track.write(pack.getData(), 0, pack.getLength());
                }
            }
            catch (SocketException se)
            {
                Log.e(LOG_TAG, "SocketException: " + se.toString());
            }
            catch (IOException ie)
            {
                Log.e(LOG_TAG, "IOException" + ie.toString());
            }
        } // end run
    });
    thrd.start();

}
</code>```

Once again, using this i can send this from one android device and listen from another just fine using the recieve code ive given, but i want to play it using vlc's get network stream command and listen to h77p://@:port and get the audio playing.
Tnx again :)

答:
You can use the code from this tutorial:</p>

```<code>StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);
  try {
      AudioManager audio =  (AudioManager) getSystemService(Context.AUDIO_SERVICE);
      audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
      AudioGroup audioGroup = new AudioGroup();
      audioGroup.setMode(AudioGroup.MODE_NORMAL);
      AudioStream audioStream = new AudioStream(InetAddress.getByAddress(getLocalIPAddress ()));
      audioStream.setCodec(AudioCodec.PCMU);
      audioStream.setMode(RtpStream.MODE_NORMAL);
                           //set receiver(vlc player) machine ip address(please update with your machine ip)
      audioStream.associate(InetAddress.getByAddress(new byte[] {(byte)192, (byte)168, (byte)1, (byte)19 }), 22222);
      audioStream.join(audioGroup);

  } catch (Exception e) {
   Log.e("----------------------", e.toString());
   e.printStackTrace();
  }
 }
public static byte[] getLocalIPAddress () {
    byte ip[]=null;
       try {
           for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
               NetworkInterface intf = en.nextElement();
               for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                   InetAddress inetAddress = enumIpAddr.nextElement();
                   if (!inetAddress.isLoopbackAddress()) {
                    ip= inetAddress.getAddress();
                   }
               }
           }
       } catch (SocketException ex) {
           Log.i("SocketException ", ex.toString());
       }
       return ip;

 }
</code>```

Body:
I'm trying to broadcast a audio file from my android device via udp to the local wifi and have the clients on the local network listen to it via VLC's network streaming option. I can broadcast it and recieve it on anydevice connected to the network if i use my own recieve code, But i want VLC to be able to play it. Is ther any specific encoding or formatting that needs to be done before I send the datagram packet?

My sending code

public void SendAudio()
{
    Thread thrd = new Thread(new Runnable() {
        @Override
        public void run()
        {
            Log.e(LOG_TAG, "start send thread, thread id: "
                + Thread.currentThread().getId());
            long file_size = 0;
            int bytes_read = 0;
            int bytes_count = 0;
            File audio = new File(AUDIO_FILE_PATH);
            FileInputStream audio_stream = null;
            file_size = audio.length();
            byte[] buf = new byte[BUF_SIZE];
            try
            {
                InetAddress addr = InetAddress.getByName("192.168.1.255");
                DatagramSocket sock = new DatagramSocket();

                while(true){
                    bytes_count=0;
                    audio_stream = new FileInputStream(audio);
                while(bytes_count < file_size)
                {
                    bytes_read = audio_stream.read(buf, 0, BUF_SIZE);
                    DatagramPacket pack = new DatagramPacket(buf, bytes_read,
                            addr, AUDIO_PORT);
                    sock.send(pack);
                    bytes_count += bytes_read;
                    Log.d(LOG_TAG, "bytes_count : " + bytes_count);
                    Thread.sleep(SAMPLE_INTERVAL, 0);
                }
                }
            }
            catch (InterruptedException ie)
            {
                Log.e(LOG_TAG, "InterruptedException");
            }
            catch (FileNotFoundException fnfe)
            {
                Log.e(LOG_TAG, "FileNotFoundException");
            }
            catch (SocketException se)
            {
                Log.e(LOG_TAG, "SocketException");
            }
            catch (UnknownHostException uhe)
            {
                Log.e(LOG_TAG, "UnknownHostException");
            }
            catch (IOException ie)
            {
                Log.e(LOG_TAG, "IOException");
            }
        } // end run
    });
    thrd.start();
}

My Recieving Code`

public void RecvAudio()
{
    Thread thrd = new Thread(new Runnable() {
        @Override
        public void run()
        {
            Log.e(LOG_TAG, "start recv thread, thread id: "
                + Thread.currentThread().getId());
            AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC,
                    SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, BUF_SIZE,
                    AudioTrack.MODE_STREAM);
            track.play();
            try
            {
                DatagramSocket sock = new DatagramSocket(AUDIO_PORT);
                byte[] buf = new byte[BUF_SIZE];

                while(true)
                {

                    DatagramPacket pack = new DatagramPacket(buf, BUF_SIZE);
                    sock.receive(pack);
                    Log.d(LOG_TAG, "recv pack: " + pack.getLength());
                    track.write(pack.getData(), 0, pack.getLength());
                }
            }
            catch (SocketException se)
            {
                Log.e(LOG_TAG, "SocketException: " + se.toString());
            }
            catch (IOException ie)
            {
                Log.e(LOG_TAG, "IOException" + ie.toString());
            }
        } // end run
    });
    thrd.start();

}

Once again, using this i can send this from one android device and listen from another just fine using the recieve code ive given, but i want to play it using vlc's get network stream command and listen to h77p://@:port and get the audio playing.
Tnx again :)

Body:
You can use the code from this tutorial:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);
  try {
      AudioManager audio =  (AudioManager) getSystemService(Context.AUDIO_SERVICE);
      audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
      AudioGroup audioGroup = new AudioGroup();
      audioGroup.setMode(AudioGroup.MODE_NORMAL);
      AudioStream audioStream = new AudioStream(InetAddress.getByAddress(getLocalIPAddress ()));
      audioStream.setCodec(AudioCodec.PCMU);
      audioStream.setMode(RtpStream.MODE_NORMAL);
                           //set receiver(vlc player) machine ip address(please update with your machine ip)
      audioStream.associate(InetAddress.getByAddress(new byte[] {(byte)192, (byte)168, (byte)1, (byte)19 }), 22222);
      audioStream.join(audioGroup);

  } catch (Exception e) {
   Log.e("----------------------", e.toString());
   e.printStackTrace();
  }
 }
public static byte[] getLocalIPAddress () {
    byte ip[]=null;
       try {
           for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
               NetworkInterface intf = en.nextElement();
               for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                   InetAddress inetAddress = enumIpAddr.nextElement();
                   if (!inetAddress.isLoopbackAddress()) {
                    ip= inetAddress.getAddress();
                   }
               }
           }
       } catch (SocketException ex) {
           Log.i("SocketException ", ex.toString());
       }
       return ip;

 }


问:
How can I manipulate this object in jQuery
```<code>jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})
</code>```

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

答:
```<code>$('#square a').click(function(e) {
    alert($(this).attr("id"));
});
</code>```

I hope this is what you are looking for

Body:
jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

Body:
$('#square a').click(function(e) {
    alert($(this).attr("id"));
});

I hope this is what you are looking for


问:
JQUERY - Hide all table cells underneath table columns based on cell class
we are currently developing an internal report for a client and I can't quite crack this one...

I have a HTML table with a variable amount of column headers and then a variable amount of data rows. Each  in the table is assigned a class of either 'td-Red' 'td-Green' or 'td-Grey'. This controls the colour of the cell.

If all of a column's tds have the 'td-Grey' class, we want to hide the entire column including the header.

I'm sure this can be done with jQuery but I'm failing to do so...

Is anybody able to help?

答:
Loop through the headings , use heading index to filter data cells in each column that also have the grey class. Compare length of that collection to total rows and hide accordingly

var $dataRows = $('#myTable tbody tr'),
   rowCount = $dataRows.length;

$('#myTable thead th').each(function(i){
   var $greyCells = $dataRows.find('td:eq(' + i + ').td-Grey');
   if($greyCells.length === rowCount){
      $greyCells.add(this).hide();
      console.log('Hiding column index = ',i)
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
  <tr>
    <th>Heading 1</th>
    <th>Heading 2</th>
    <th>Heading 3</th>
    <th>Heading 4</th>
    <th>Heading 5</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
</tbody>
</table></code>```

Body:
Loop through the headings , use heading index to filter data cells in each column that also have the grey class. Compare length of that collection to total rows and hide accordingly

var $dataRows = $('#myTable tbody tr'),
   rowCount = $dataRows.length;

$('#myTable thead th').each(function(i){
   var $greyCells = $dataRows.find('td:eq(' + i + ').td-Grey');
   if($greyCells.length === rowCount){
      $greyCells.add(this).hide();
      console.log('Hiding column index = ',i)
   }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
  <tr>
    <th>Heading 1</th>
    <th>Heading 2</th>
    <th>Heading 3</th>
    <th>Heading 4</th>
    <th>Heading 5</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
  <tr>
    <td class="td-Grey">Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td class="td-Grey">Col 4</td>
    <td>Col 5</td>
  </tr>
</tbody>
</table>


问:
android:elevation applied to toolbar AND its title
I use a very simple style to format my Toolbar, I use android:elevation to display a shadow under the Toolbar like this:

```<code><style
    name="AppToolbarTheme"
    parent="AppTheme">

    <item name="android:background">@color/colorPrimary</item>
    <item name="android:titleTextColor">@android:color/white</item>
    <item name="android:elevation">4dip</item>
</style>
</code>```

And I'm applying it simply like that:

```<code><Toolbar
    android:id="@+id/main_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppToolbarTheme"/>
</code>```

The shadow displays under the toolbar like I want, howerver it is also somehow applied to the title of the toolbar which looks very weird:

答:
Remove <item name="android:elevation">4dip</item> from  style and put it in toolbar xml

```<code><Toolbar
    android:id="@+id/main_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppToolbarTheme"
    android:elevation="4dp"/>
</code>```

Body:
I use a very simple style to format my Toolbar, I use android:elevation to display a shadow under the Toolbar like this:

And I'm applying it simply like that:

<Toolbar
    android:id="@+id/main_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppToolbarTheme"/>

The shadow displays under the toolbar like I want, howerver it is also somehow applied to the title of the toolbar which looks very weird:

Body:
Remove <item name="android:elevation">4dip</item> from  style and put it in toolbar xml

<Toolbar
    android:id="@+id/main_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppToolbarTheme"
    android:elevation="4dp"/>


问:
Connect Django 1.11 to Mariadb Galera cluster
I am using Django 1.11 with MariaDB 10.1 Galera cluster
I didn`t find in the documentation how to connect to a cluster.

I tried using gcomm://NODE1,NODE2 url with no success... any idea?

答:
According to a ticket that I opened to Django project, there is no support in MariaDB Galera cluster and they probably will not add support for that soon

https://code.djangoproject.com/ticket/28270


问:
When should one use RxJava Observable and when simple Callback on Android?
I'm working on networking for my app. So I decided to try out Square's Retrofit. I see that they support simple Callback

```<code>@GET("/user/{id}/photo")
void getUserPhoto(@Path("id") int id, Callback<Photo> cb);
</code>```

and RxJava's Observable

```<code>@GET("/user/{id}/photo")
Observable<Photo> getUserPhoto(@Path("id") int id);
</code>```

Both look pretty similar at first glance, but when it gets to implementation it gets interesting...

While with simple callback implementation would look similar to this:

```<code>api.getUserPhoto(photoId, new Callback<Photo>() {
    @Override
    public void onSuccess() {
    }
});
</code>```

which is quite simple and straightforward. And with Observable it quickly gets verbose and quite complicated.

```<code>public Observable<Photo> getUserPhoto(final int photoId) {
    return Observable.create(new Observable.OnSubscribeFunc<Photo>() {
        @Override
        public Subscription onSubscribe(Observer<? super Photo> observer) {
            try {
                observer.onNext(api.getUserPhoto(photoId));
                observer.onCompleted();
            } catch (Exception e) {
                observer.onError(e);
            }

            return Subscriptions.empty();
        }
    }).subscribeOn(Schedulers.threadPoolForIO());
}
</code>```

And that is not it. You still have to do something like this:

```<code>Observable.from(photoIdArray)
        .mapMany(new Func1<String, Observable<Photo>>() {
            @Override
            public Observable<Photo> call(Integer s) {
                return getUserPhoto(s);
            }
        })
        .subscribeOn(Schedulers.threadPoolForIO())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Photo>() {
            @Override
            public void call(Photo photo) {
                //save photo?
            }
        });
</code>```

Am I missing something here? Or is this a wrong case to use Observables?
When would/should one prefer Observable over simple Callback?

Update

Using retrofit is much simpler than example above as @Niels showed in his answer or in Jake Wharton's example project U2020. But essentially the question stays the same - when should one use one way or the other?

答:
By the samples and conclusions in other answers, I think there is no big difference for simple one or two-steps tasks. However, Callback is simple and straightforward. RxJava is more complicated and too big for simple task. There is the third solution by: abacus-common. Let me implement above use cases with all three solutions: Callback, RxJava, CompletableFuture(abacus-common) with Retrolambda:

Fetch photo from network and save/display on device:

```<code>// By Callback
api.getUserPhoto(userId, new Callback<Photo>() {
    @Override
    public void onResponse(Call<Photo> call, Response<Photo> response) {
        save(response.body()); // or update view on UI thread.
    }

    @Override
    public void onFailure(Call<Photo> call, Throwable t) {
        // show error message on UI or do something else.
    }
});

// By RxJava
api.getUserPhoto2(userId) //
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(photo -> {
            save(photo); // or update view on UI thread.
        }, error -> {
            // show error message on UI or do something else.
        });

// By Thread pool executor and CompletableFuture.
TPExecutor.execute(() -> api.getUserPhoto(userId))
        .thenRunOnUI((photo, error) -> {
            if (error != null) {
                // show error message on UI or do something else.
            } else {
                save(photo); // or update view on UI thread.
            }
        });
</code>```

Load user details and photo in parallel

```<code>// By Callback
// ignored because it's little complicated

// By RxJava
Observable.zip(api.getUserDetails2(userId), api.getUserPhoto2(userId), (details, photo) -> Pair.of(details, photo))
        .subscribe(p -> {
            // Do your task.
        });

// By Thread pool executor and CompletableFuture.
TPExecutor.execute(() -> api.getUserDetails(userId))
          .runOnUIAfterBoth(TPExecutor.execute(() -> api.getUserPhoto(userId)), p -> {
    // Do your task
});
</code>```

Body:
I'm working on networking for my app. So I decided to try out Square's Retrofit. I see that they support simple Callback

@GET("/user/{id}/photo")
void getUserPhoto(@Path("id") int id, Callback<Photo> cb);

and RxJava's Observable

@GET("/user/{id}/photo")
Observable<Photo> getUserPhoto(@Path("id") int id);

Both look pretty similar at first glance, but when it gets to implementation it gets interesting...

While with simple callback implementation would look similar to this:

api.getUserPhoto(photoId, new Callback<Photo>() {
    @Override
    public void onSuccess() {
    }
});

which is quite simple and straightforward. And with Observable it quickly gets verbose and quite complicated.

public Observable<Photo> getUserPhoto(final int photoId) {
    return Observable.create(new Observable.OnSubscribeFunc<Photo>() {
        @Override
        public Subscription onSubscribe(Observer<? super Photo> observer) {
            try {
                observer.onNext(api.getUserPhoto(photoId));
                observer.onCompleted();
            } catch (Exception e) {
                observer.onError(e);
            }

            return Subscriptions.empty();
        }
    }).subscribeOn(Schedulers.threadPoolForIO());
}

And that is not it. You still have to do something like this:

Observable.from(photoIdArray)
        .mapMany(new Func1<String, Observable<Photo>>() {
            @Override
            public Observable<Photo> call(Integer s) {
                return getUserPhoto(s);
            }
        })
        .subscribeOn(Schedulers.threadPoolForIO())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Photo>() {
            @Override
            public void call(Photo photo) {
                //save photo?
            }
        });

Am I missing something here? Or is this a wrong case to use Observables?
When would/should one prefer Observable over simple Callback?

Update

Using retrofit is much simpler than example above as @Niels showed in his answer or in Jake Wharton's example project U2020. But essentially the question stays the same - when should one use one way or the other?

Body:
By the samples and conclusions in other answers, I think there is no big difference for simple one or two-steps tasks. However, Callback is simple and straightforward. RxJava is more complicated and too big for simple task. There is the third solution by: abacus-common. Let me implement above use cases with all three solutions: Callback, RxJava, CompletableFuture(abacus-common) with Retrolambda:

Fetch photo from network and save/display on device:

// By Callback
api.getUserPhoto(userId, new Callback<Photo>() {
    @Override
    public void onResponse(Call<Photo> call, Response<Photo> response) {
        save(response.body()); // or update view on UI thread.
    }

    @Override
    public void onFailure(Call<Photo> call, Throwable t) {
        // show error message on UI or do something else.
    }
});

// By RxJava
api.getUserPhoto2(userId) //
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(photo -> {
            save(photo); // or update view on UI thread.
        }, error -> {
            // show error message on UI or do something else.
        });

// By Thread pool executor and CompletableFuture.
TPExecutor.execute(() -> api.getUserPhoto(userId))
        .thenRunOnUI((photo, error) -> {
            if (error != null) {
                // show error message on UI or do something else.
            } else {
                save(photo); // or update view on UI thread.
            }
        });

Load user details and photo in parallel

// By Callback
// ignored because it's little complicated

// By RxJava
Observable.zip(api.getUserDetails2(userId), api.getUserPhoto2(userId), (details, photo) -> Pair.of(details, photo))
        .subscribe(p -> {
            // Do your task.
        });

// By Thread pool executor and CompletableFuture.
TPExecutor.execute(() -> api.getUserDetails(userId))
          .runOnUIAfterBoth(TPExecutor.execute(() -> api.getUserPhoto(userId)), p -> {
    // Do your task
});