问:
Type hints for a function that accepts a (homogeneous) sequence of one of several types
I'm trying to provide type hints for a function that accepts a sequence
with one of two types of elements, and I'm at a loss how to make mypy happy.  Please note, the sequence is homogeneous, meaning the types can't be mixed, either-or.  Usually I do this when they are "compatible" types, e.g. a path str or a pathlib.Path object, and annotating that with Union works just fine.  But in the case of a sequence, Sequence[Union[..]] (or Union[Sequence[..]]) doesn't seem to work.  Here's a minimal working example:

```<code>from pathlib import Path
from typing import Sequence, Dict, Union

def fn_accepts_dict(adict):
    """Function from an external module that accepts `dict`s."""
    for key, val in adict.items():
        print(f"{key}, {val}")

def vararg_test(resources: Sequence[Union[str, Dict]]):
    """My function where I want to provide type hints"""
    if isinstance(resources[0], str):
        resources2 = [{"path": Path(f)} for f in resources]
    else:
        resources2 = resources
    for d in resources2:
        fn_accepts_dict(d)
</code>```

Now, with the above definitions, calling vararg_test with either of
these two work as expected:

```<code>l1 = ["foo/bar", "bar/baz"]
l2 = [{"path": Path("foo/bar")}, {"path": Path("bar/baz")}]
</code>```

But running mypy gives me the following errors:

```<code>type_hints.py:14: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:16: error: Incompatible types in assignment (expression has type "Sequence[Union[str, Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
Found 2 errors in 1 file (checked 1 source file)
</code>```

How can I resolve this?

Edit:
To give some background, the str is a path, and the dict has metadata corresponding to that path, and the function fn_accepts_dict collates metadata into one metadata object.  So they logical flow is either: str -> dict -> fn_accepts_dict or, dict -> fn_accepts_dict.

While @ShadowRanger's suggestion looked promising, no luck.  I get the same error with the following hints:

```<code>def vararg_test2(resources: Union[Sequence[str], Sequence[Dict]]):
    ... # same implementation as above
</code>```

mypy error:

```<code>type_hints.py:24: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:26: error: Incompatible types in assignment (expression has type "Union[Sequence[str], Sequence[Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
</code>```

Edit 2:  unfortunately, with all the annotations, it looks more like C/C++ than Python; see my own answer below for a much more Pythonic solution.

答:
As pointed out by @MisterMiyagi's answer, the issue stems from mypy not being able to infer the types when an expression is used in isinstance.  So I tried an alternative implementation where isinstance is passed a name.  This also had the benefit that vararg_test could now accept any iterable.

```<code>def vararg_test(resources: Iterable[Union[str, Dict]]):
    """My function where I want to use type hints"""
    resources2: List[Dict] = []
    for res in resources:
        if isinstance(res, str):
            res = {"path": Path(res)}
        resources2 += [res]
    for d in resources2:
        fn_accepts_dict(d)
</code>```

However this still requires us to annotate resources2, but it's easy to reformulate as list comprehension where we wouldn't need any annotations.

```<code>def vararg_test3(resources: Iterable[Union[str, Dict]]):
    """My function where I want to use type hints"""
    resources2 = [
        {"path": Path(res)} if isinstance(res, str) else res
        for res in resources
    ]
    for d in resources2:
        fn_accepts_dict(d)
</code>```

Body:
I'm trying to provide type hints for a function that accepts a sequence
with one of two types of elements, and I'm at a loss how to make mypy happy.  Please note, the sequence is homogeneous, meaning the types can't be mixed, either-or.  Usually I do this when they are "compatible" types, e.g. a path str or a pathlib.Path object, and annotating that with Union works just fine.  But in the case of a sequence, Sequence[Union[..]] (or Union[Sequence[..]]) doesn't seem to work.  Here's a minimal working example:

from pathlib import Path
from typing import Sequence, Dict, Union

def fn_accepts_dict(adict):
    """Function from an external module that accepts `dict`s."""
    for key, val in adict.items():
        print(f"{key}, {val}")

def vararg_test(resources: Sequence[Union[str, Dict]]):
    """My function where I want to provide type hints"""
    if isinstance(resources[0], str):
        resources2 = [{"path": Path(f)} for f in resources]
    else:
        resources2 = resources
    for d in resources2:
        fn_accepts_dict(d)

Now, with the above definitions, calling vararg_test with either of
these two work as expected:

l1 = ["foo/bar", "bar/baz"]
l2 = [{"path": Path("foo/bar")}, {"path": Path("bar/baz")}]

But running mypy gives me the following errors:

type_hints.py:14: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:16: error: Incompatible types in assignment (expression has type "Sequence[Union[str, Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
Found 2 errors in 1 file (checked 1 source file)

How can I resolve this?

Edit:
To give some background, the str is a path, and the dict has metadata corresponding to that path, and the function fn_accepts_dict collates metadata into one metadata object.  So they logical flow is either: str -> dict -> fn_accepts_dict or, dict -> fn_accepts_dict.

While @ShadowRanger's suggestion looked promising, no luck.  I get the same error with the following hints:

def vararg_test2(resources: Union[Sequence[str], Sequence[Dict]]):
    ... # same implementation as above

mypy error:

type_hints.py:24: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:26: error: Incompatible types in assignment (expression has type "Union[Sequence[str], Sequence[Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")

Edit 2:  unfortunately, with all the annotations, it looks more like C/C++ than Python; see my own answer below for a much more Pythonic solution.

Body:
As pointed out by @MisterMiyagi's answer, the issue stems from mypy not being able to infer the types when an expression is used in isinstance.  So I tried an alternative implementation where isinstance is passed a name.  This also had the benefit that vararg_test could now accept any iterable.

def vararg_test(resources: Iterable[Union[str, Dict]]):
    """My function where I want to use type hints"""
    resources2: List[Dict] = []
    for res in resources:
        if isinstance(res, str):
            res = {"path": Path(res)}
        resources2 += [res]
    for d in resources2:
        fn_accepts_dict(d)

However this still requires us to annotate resources2, but it's easy to reformulate as list comprehension where we wouldn't need any annotations.

def vararg_test3(resources: Iterable[Union[str, Dict]]):
    """My function where I want to use type hints"""
    resources2 = [
        {"path": Path(res)} if isinstance(res, str) else res
        for res in resources
    ]
    for d in resources2:
        fn_accepts_dict(d)


来源: stackexchange

问:
Android Gridview - Need to open different intents
Just a beginner at Android development. I've currently got a GridView setup to act as a main menu for my application. I've managed to get an intent working using OnItemClickListener(). However all 6 of my images when clicked go to the same Activity class. How do I go about giving each image an intent to different activities?

MainActivity:

```<code>public void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   GridView gridview = (GridView) findViewById(R.id.gridview);
   gridview.setAdapter(new ImageAdapter(this));
   gridview.setOnItemClickListener(new OnItemClickListener() {

       public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
           Toast.makeText(nclApp2.this, "" + position, Toast.LENGTH_SHORT).show();
           Intent i = new Intent(nclApp2.this, Screen2.class);

           startActivity(i);
       }
   });
</code>```

ImageAdapter:

```<code>public class ImageAdapter extends BaseAdapter {
private Context mContext;

public ImageAdapter(Context c) {
    mContext = c;
}

public int getCount() {
    return mThumbIds.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {  // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

// references to our images
private Integer[] mThumbIds = {
        R.drawable.icon, R.drawable.icon,
        R.drawable.icon, R.drawable.icon,
        R.drawable.icon, R.drawable.icon,

};

class MyOnClickListener implements OnClickListener
{
 private final int position;

 public MyOnClickListener(int position)
 {
  this.position = position;
 }

 public void onClick(View v)
 {

 }
}
</code>```

Edit: After hours searching, I found that this works!:

```<code>public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
           Toast.makeText(nclApp2.this, "" + position, Toast.LENGTH_SHORT).show();
           //Intent i = new Intent(nclApp2.this, Screen2.class);

           Intent myIntent = null;
           if(position == 0){
               myIntent = new Intent(v.getContext(), Screen1.class);
           }
           if(position == 1){
               myIntent = new Intent(v.getContext(), Screen2.class);
           }
           if(position ==2){
               myIntent = new Intent(v.getContext(), Screen3.class);
           }
           startActivity(myIntent);
       }
</code>```

答:
You have

```<code>public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
</code>```

so make use of the int position part of it...

```<code>switch (position) {
case 0:
// start one activity
break;
case 1:
// start another activity
break;
// etc.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just a beginner at Android development. I've currently got a GridView setup to act as a main menu for my application. I've managed to get an intent working using OnItemClickListener(). However all 6 of my images when clicked go to the same Activity class. How do I go about giving each image an intent to different activities?

MainActivity:

public void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   GridView gridview = (GridView) findViewById(R.id.gridview);
   gridview.setAdapter(new ImageAdapter(this));
   gridview.setOnItemClickListener(new OnItemClickListener() {

       public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
           Toast.makeText(nclApp2.this, "" + position, Toast.LENGTH_SHORT).show();
           Intent i = new Intent(nclApp2.this, Screen2.class);

           startActivity(i);
       }
   });

ImageAdapter:

public class ImageAdapter extends BaseAdapter {
private Context mContext;

public ImageAdapter(Context c) {
    mContext = c;
}

public int getCount() {
    return mThumbIds.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {  // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

// references to our images
private Integer[] mThumbIds = {
        R.drawable.icon, R.drawable.icon,
        R.drawable.icon, R.drawable.icon,
        R.drawable.icon, R.drawable.icon,

};

class MyOnClickListener implements OnClickListener
{
 private final int position;

 public MyOnClickListener(int position)
 {
  this.position = position;
 }

 public void onClick(View v)
 {

 }
}

Edit: After hours searching, I found that this works!:

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
           Toast.makeText(nclApp2.this, "" + position, Toast.LENGTH_SHORT).show();
           //Intent i = new Intent(nclApp2.this, Screen2.class);

           Intent myIntent = null;
           if(position == 0){
               myIntent = new Intent(v.getContext(), Screen1.class);
           }
           if(position == 1){
               myIntent = new Intent(v.getContext(), Screen2.class);
           }
           if(position ==2){
               myIntent = new Intent(v.getContext(), Screen3.class);
           }
           startActivity(myIntent);
       }

Body:
You have

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

so make use of the int position part of it...

switch (position) {
case 0:
// start one activity
break;
case 1:
// start another activity
break;
// etc.


问:
Why isnt Dijkstra's algorithm's (for shortest path) time complexity the same as DFS?
Can't Dijkstra's algorithm be implemented using a DFS that keeps track of the length of the current path traveled and every time it arrives in an unvisited node it updates the length of the shortest path to that node, and if the node arrived at is already visited, update the length if the current length is smaller than the length in the node?

Which is just DFS, meaning the run time should be linear ( O(|V| + |E|) ).

答:
When you arrive at a visited node, called A, assume that the length of current path is shorter than the length in A, so you update length to A. But what about those nodes that connect with A? You need to update them too, but you can't, because A is already visited.

In short, the run time is linear, but the algorithm is incorrect.

ContentLicense: CC BY-SA 4.0


问:
Three JS rotate group with same orientation as camera for View Cube/Orientation Cube
I'm trying to make a blender-esk orientation view that looks like this using Three JS:

My plan is to take the camera rotation and rotate 3 vector points (representing the X,Y and Z bubbles in the picture). Then once I have those points I can use the X and Y coordinates to draw circles on a canvas and draw lines to connect them to the center. I can then use the Z direction to determine what should be drawn on top of what.

Currently I'm using a 2nd three.js scene to visualize the position of these X, Y and Z points as I try different ways to rotate the group of vertices to have it match the camera's orientation. I'm struggling with this part and I've tried a bunch of things that haven't worked.

Here is a JS Fiddle for where I'm currently at:

https://jsfiddle.net/j9mcL0x4/4/
(doesn't load in Brave but works in Chrome)

As you pan the camera around, it moves the 3 cubes in the 2nd scene but I cannot get it to rotate correctly.

The X, Y and Z points are represented by a group of Vector3's as such:

```<code>this.ref = [
  [new THREE.Vector3(1,0,0), 0xFF0000],
  [new THREE.Vector3(0,1,0), 0x00FF00],
  [new THREE.Vector3(0,0,1), 0x0000FF],
]
</code>```

I then create each cube and add it to a group:

```<code>this.group = new THREE.Group();
for(var pos of this.ref) {
  var geometry = new THREE.BoxGeometry(.25,.25,.25);
  var material = new THREE.MeshBasicMaterial({
    color: pos[1]
  });
  var cube = new THREE.Mesh(geometry, material);
  cube.position.copy(pos[0]);
  this.group.add(cube);
}

this.scene.add(this.group);
</code>```

Then in my animate function, I'm trying to calculate the rotation for the group to get it to be in the same orientation as the main view:

```<code>var quaternion = new THREE.Quaternion();
camera.getWorldQuaternion( quaternion );

let rotation = new THREE.Euler();
rotation.setFromQuaternion(quaternion);

var dir = new THREE.Vector3();
dir.subVectors( camera.position, controls.target ).normalize();

orientationHelper.group.rotation.set(dir.x, dir.y, dir.z);
orientationHelper.animate();
</code>```

What I have is completely wrong but here are some things I've tried:

Calculate a point in front of the camera, then use that to make the group look in that direction using the lookAt function

I'm using orbit controls which has a target that the camera is focused on. I've tried subtracting the camera position vector and the target vector to get the look direction but this failed to work (what's currently in the jsfiddle)

I've tried using just the camera local rotation (and tried negating it)

Note
I could rotate the camera in the 2nd scene to match the camera in the main view but I really want to rotate the vectors themselves. This is so I can take those points and project them onto a basic canvas to draw 6 circles and 3 lines. I feel like this will be much easier than trying to use sprites in 3d and Three JS cannot easily draw thick lines without creating rectangular meshes for it.

Here are some examples of what I want the output to look like:

Update

This problem was solved by Rabbid76 and if anyone is interested in using a Blender Style orientation cube for their project, you can find the full source code here:

https://github.com/jrj2211/three-orientation-gizmo/

Or download it with npm:

https://www.npmjs.com/package/three-orientation-gizmo

答:
First of all in view space, the X-axis points to the right, the Y-axis points is up and the Z-axis points out of the canvas.

So you have to choose an initial position for the OrientationHelper camera on the positive Z-axis:

class OrientationHelper {
    constructor(canvas) {
        // [...]

        this.camera = new THREE.PerspectiveCamera(75, size / size, 0.1, 1000);
        this.camera.position.set(0, 0, 2);

        // [...]
```

<p>In the following I recommend to set the orientation of the group in the <code>OrientationHelper</code> scene by a matrix:</p>

<pre class="lang-js prettyprint-override"><code>class OrientationHelper {
    // [...]

    setCameraRotation(rotation) {
        this.group.setRotationFromMatrix(rotation);
    }

    // [...]
</code>```

The view matrix is the inverse matrix, of that matrix, that defines the position and orientation of the camera. You want to visualize the orientation of the camera. You want to visualize the orientation of the view matrix.

Create a rotation matrix from the camera.rotation. Compute the Inverse matrix and set the orientation of the OrientationHelper by the computed matrix:

let rotMat = new THREE.Matrix4().makeRotationFromEuler(camera.rotation);
let invRotMat = new THREE.Matrix4().getInverse(rotMat);

orientationHelper.setCameraRotation(invRotMat);
orientationHelper.update();
```

<p>See the example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class OrientationHelper {
  constructor(canvas) {
    this.canvas = canvas;

    this.ref = [
      [new THREE.Vector3(1,0,0), 0xFF0000],
      [new THREE.Vector3(0,1,0), 0x00FF00],
      [new THREE.Vector3(0,0,1), 0x0000FF],
    ]

    var size = 200;
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(75, size / size, 0.1, 1000);
    this.camera.position.set(0, 0, 2);

    this.renderer = new THREE.WebGLRenderer({alpha: true});
    this.renderer.setSize(size, size);
    canvas.appendChild(this.renderer.domElement);

    var controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);

    var geometry = new THREE.SphereGeometry( .1, 32, 32 );
    var material = new THREE.MeshBasicMaterial( {color: 0xffffff} );
    var sphere = new THREE.Mesh( geometry, material );
    this.scene.add( sphere );

    this.group = new THREE.Group();
    for(var pos of this.ref) {
      var geometry = new THREE.BoxGeometry(.25,.25,.25);
      var material = new THREE.MeshBasicMaterial({
        color: pos[1]
      });
      var cube = new THREE.Mesh(geometry, material);
      cube.position.copy(pos[0]);
      this.group.add(cube);
    }

    this.scene.add(this.group);
  }

  setCameraRotation(rotation) {
    this.group.setRotationFromMatrix(rotation);
  }

  update() {
   this.renderer.render(this.scene, this.camera);
  }
}

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);
camera.position.set(0, 3, 3);
controls.update();

//controls.autoRotate = true;

var size = 10;
var divisions = 10;

var gridHelper = new THREE.GridHelper(size, divisions);
scene.add(gridHelper);

var axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

 // material
  var material = new THREE.MeshBasicMaterial({
    color: 0xffffff,
    vertexColors: THREE.FaceColors
  });

var geometry = new THREE.BoxGeometry();

 // colors
  red = new THREE.Color(1, 0, 0);
  green = new THREE.Color(0, 1, 0);
  blue = new THREE.Color(0, 0, 1);
  var colors = [red, green, blue];

  for (var i = 0; i < 3; i++) {
    geometry.faces[4 * i].color = colors[i];
    geometry.faces[4 * i + 1].color = colors[i];
    geometry.faces[4 * i + 2].color = colors[i];
    geometry.faces[4 * i + 3].color = colors[i];
  }

var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// Orientation
var orientationHelper = new OrientationHelper(document.getElementById("orientation-helper"));

function animate() {
  requestAnimationFrame(animate);
  controls.update();

  let rotMat = new THREE.Matrix4().makeRotationFromEuler(camera.rotation);
  let invRotMat = new THREE.Matrix4().getInverse(rotMat);
  orientationHelper.setCameraRotation(invRotMat);
 orientationHelper.update();

  renderer.render(scene, camera);
}

animate();</code>```

body { margin: 0; }
canvas { display: block; }
#orientation-helper { position: absolute; top: 10px; left: 10px; background: #505050; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://rawcdn.githack.com/mrdoob/three.js/r113/build/three.js"></script>
<script src="https://rawcdn.githack.com/mrdoob/three.js/r113/examples/js/controls/OrbitControls.js"></script>
<div id='orientation-helper'></div></code>```

Body:
I'm trying to make a blender-esk orientation view that looks like this using Three JS:

My plan is to take the camera rotation and rotate 3 vector points (representing the X,Y and Z bubbles in the picture). Then once I have those points I can use the X and Y coordinates to draw circles on a canvas and draw lines to connect them to the center. I can then use the Z direction to determine what should be drawn on top of what.

Currently I'm using a 2nd three.js scene to visualize the position of these X, Y and Z points as I try different ways to rotate the group of vertices to have it match the camera's orientation. I'm struggling with this part and I've tried a bunch of things that haven't worked.

Here is a JS Fiddle for where I'm currently at:

https://jsfiddle.net/j9mcL0x4/4/
(doesn't load in Brave but works in Chrome)

As you pan the camera around, it moves the 3 cubes in the 2nd scene but I cannot get it to rotate correctly.

The X, Y and Z points are represented by a group of Vector3's as such:

this.ref = [
  [new THREE.Vector3(1,0,0), 0xFF0000],
  [new THREE.Vector3(0,1,0), 0x00FF00],
  [new THREE.Vector3(0,0,1), 0x0000FF],
]

I then create each cube and add it to a group:

this.group = new THREE.Group();
for(var pos of this.ref) {
  var geometry = new THREE.BoxGeometry(.25,.25,.25);
  var material = new THREE.MeshBasicMaterial({
    color: pos[1]
  });
  var cube = new THREE.Mesh(geometry, material);
  cube.position.copy(pos[0]);
  this.group.add(cube);
}

this.scene.add(this.group);

Then in my animate function, I'm trying to calculate the rotation for the group to get it to be in the same orientation as the main view:

var quaternion = new THREE.Quaternion();
camera.getWorldQuaternion( quaternion );

let rotation = new THREE.Euler();
rotation.setFromQuaternion(quaternion);

var dir = new THREE.Vector3();
dir.subVectors( camera.position, controls.target ).normalize();

orientationHelper.group.rotation.set(dir.x, dir.y, dir.z);
orientationHelper.animate();

What I have is completely wrong but here are some things I've tried:

Calculate a point in front of the camera, then use that to make the group look in that direction using the lookAt function

I'm using orbit controls which has a target that the camera is focused on. I've tried subtracting the camera position vector and the target vector to get the look direction but this failed to work (what's currently in the jsfiddle)

I've tried using just the camera local rotation (and tried negating it)

Note
I could rotate the camera in the 2nd scene to match the camera in the main view but I really want to rotate the vectors themselves. This is so I can take those points and project them onto a basic canvas to draw 6 circles and 3 lines. I feel like this will be much easier than trying to use sprites in 3d and Three JS cannot easily draw thick lines without creating rectangular meshes for it.

Here are some examples of what I want the output to look like:

Update

This problem was solved by Rabbid76 and if anyone is interested in using a Blender Style orientation cube for their project, you can find the full source code here:

https://github.com/jrj2211/three-orientation-gizmo/

Or download it with npm:

https://www.npmjs.com/package/three-orientation-gizmo

Body:
First of all in view space, the X-axis points to the right, the Y-axis points is up and the Z-axis points out of the canvas.

So you have to choose an initial position for the OrientationHelper camera on the positive Z-axis:

class OrientationHelper {
    constructor(canvas) {
        // [...]

        this.camera = new THREE.PerspectiveCamera(75, size / size, 0.1, 1000);
        this.camera.position.set(0, 0, 2);

        // [...]

In the following I recommend to set the orientation of the group in the OrientationHelper scene by a matrix:

class OrientationHelper {
    // [...]

    setCameraRotation(rotation) {
        this.group.setRotationFromMatrix(rotation);
    }

    // [...]

The view matrix is the inverse matrix, of that matrix, that defines the position and orientation of the camera. You want to visualize the orientation of the camera. You want to visualize the orientation of the view matrix.

Create a rotation matrix from the camera.rotation. Compute the Inverse matrix and set the orientation of the OrientationHelper by the computed matrix:

let rotMat = new THREE.Matrix4().makeRotationFromEuler(camera.rotation);
let invRotMat = new THREE.Matrix4().getInverse(rotMat);

orientationHelper.setCameraRotation(invRotMat);
orientationHelper.update();

See the example:

class OrientationHelper {
  constructor(canvas) {
    this.canvas = canvas;

    this.ref = [
      [new THREE.Vector3(1,0,0), 0xFF0000],
      [new THREE.Vector3(0,1,0), 0x00FF00],
      [new THREE.Vector3(0,0,1), 0x0000FF],
    ]

    var size = 200;
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(75, size / size, 0.1, 1000);
    this.camera.position.set(0, 0, 2);

    this.renderer = new THREE.WebGLRenderer({alpha: true});
    this.renderer.setSize(size, size);
    canvas.appendChild(this.renderer.domElement);

    var controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);

    var geometry = new THREE.SphereGeometry( .1, 32, 32 );
    var material = new THREE.MeshBasicMaterial( {color: 0xffffff} );
    var sphere = new THREE.Mesh( geometry, material );
    this.scene.add( sphere );

    this.group = new THREE.Group();
    for(var pos of this.ref) {
      var geometry = new THREE.BoxGeometry(.25,.25,.25);
      var material = new THREE.MeshBasicMaterial({
        color: pos[1]
      });
      var cube = new THREE.Mesh(geometry, material);
      cube.position.copy(pos[0]);
      this.group.add(cube);
    }

    this.scene.add(this.group);
  }

  setCameraRotation(rotation) {
    this.group.setRotationFromMatrix(rotation);
  }

  update() {
   this.renderer.render(this.scene, this.camera);
  }
}

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);
camera.position.set(0, 3, 3);
controls.update();

//controls.autoRotate = true;

var size = 10;
var divisions = 10;

var gridHelper = new THREE.GridHelper(size, divisions);
scene.add(gridHelper);

var axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

 // material
  var material = new THREE.MeshBasicMaterial({
    color: 0xffffff,
    vertexColors: THREE.FaceColors
  });

var geometry = new THREE.BoxGeometry();

 // colors
  red = new THREE.Color(1, 0, 0);
  green = new THREE.Color(0, 1, 0);
  blue = new THREE.Color(0, 0, 1);
  var colors = [red, green, blue];

  for (var i = 0; i < 3; i++) {
    geometry.faces[4 * i].color = colors[i];
    geometry.faces[4 * i + 1].color = colors[i];
    geometry.faces[4 * i + 2].color = colors[i];
    geometry.faces[4 * i + 3].color = colors[i];
  }

var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// Orientation
var orientationHelper = new OrientationHelper(document.getElementById("orientation-helper"));

function animate() {
  requestAnimationFrame(animate);
  controls.update();

  let rotMat = new THREE.Matrix4().makeRotationFromEuler(camera.rotation);
  let invRotMat = new THREE.Matrix4().getInverse(rotMat);
  orientationHelper.setCameraRotation(invRotMat);
 orientationHelper.update();

  renderer.render(scene, camera);
}

animate();

body { margin: 0; }
canvas { display: block; }
#orientation-helper { position: absolute; top: 10px; left: 10px; background: #505050; }

<script src="https://rawcdn.githack.com/mrdoob/three.js/r113/build/three.js"></script>
<script src="https://rawcdn.githack.com/mrdoob/three.js/r113/examples/js/controls/OrbitControls.js"></script>
<div id='orientation-helper'></div>


问:
Conditional subquery in where clause
I'm trying to create a query with conditional logic where I only calculate revenue for the most recent records by each month using a datetime column (start_date), but only if there are multiple records in that month from the same account_id.

Here's a basic example of the schema after I join two tables (full schema in sqlfiddle link).

```<code>| account_id | plan_id | start_date           | plan_interval | price |
|------------|---------|----------------------|---------------|-------|
| 1          | 1       | 2018-01-03T14:52:13Z | month         | 39    |
| 1          | 3       | 2018-02-07T11:10:17Z | year          | 999   |
| 1          | 2       | 2018-02-07T11:11:17Z | month         | 99    |
</code>```

In the above example, I would only like to include rows 1 and 3 in my output, as it's the one record from account_id 1 in January and the most recent of two records for account_id 1 in February.

```<code>SELECT
MONTH(start_date) AS month,
SUM(CASE WHEN plan_interval = 'month'
     THEN price * .01
     ELSE (price * .01)/12 END) AS mrr
FROM subscriptions
  JOIN plans
  ON plans.id = subscriptions.plan_id
WHERE Year(start_date) = 2018 AND
  CASE WHEN (account_id = account_id
             AND MONTH(start_date) = MONTH(start_date))
             THEN (SELECT MAX(start_date) FROM subscriptions)
             ELSE (SELECT start_date FROM subscriptions)
             END
GROUP BY month
ORDER BY month ASC;
</code>```

The case statement in the subquery above does not seem to work in doing this. It returns the data without filtering out records when the first condition is met.

Here is an example: sqlfiddle

Title: Conditional subquery in where clause

Body:
I'm trying to create a query with conditional logic where I only calculate revenue for the most recent records by each month using a datetime column (start_date), but only if there are multiple records in that month from the same account_id.

Here's a basic example of the schema after I join two tables (full schema in sqlfiddle link).

| account_id | plan_id | start_date           | plan_interval | price |
|------------|---------|----------------------|---------------|-------|
| 1          | 1       | 2018-01-03T14:52:13Z | month         | 39    |
| 1          | 3       | 2018-02-07T11:10:17Z | year          | 999   |
| 1          | 2       | 2018-02-07T11:11:17Z | month         | 99    |

In the above example, I would only like to include rows 1 and 3 in my output, as it's the one record from account_id 1 in January and the most recent of two records for account_id 1 in February.

SELECT
MONTH(start_date) AS month,
SUM(CASE WHEN plan_interval = 'month'
     THEN price * .01
     ELSE (price * .01)/12 END) AS mrr
FROM subscriptions
  JOIN plans
  ON plans.id = subscriptions.plan_id
WHERE Year(start_date) = 2018 AND
  CASE WHEN (account_id = account_id
             AND MONTH(start_date) = MONTH(start_date))
             THEN (SELECT MAX(start_date) FROM subscriptions)
             ELSE (SELECT start_date FROM subscriptions)
             END
GROUP BY month
ORDER BY month ASC;

The case statement in the subquery above does not seem to work in doing this. It returns the data without filtering out records when the first condition is met.

Here is an example: sqlfiddle

Body:
First work out the last entry by account and month (sub query a) join to subscriptions to get the plan_id and then get the plan

SELECT S.ACCOUNT_id,s.plan_id,s.start_date,p.Price,p.plan_interval,
         case when p.plan_interval = 'month' then p.price * .01 /12 else p.price * .01 end as rev
from subscriptions s
join (select s.account_id,month(s.start_date), max(s.start_date) start_date
        from subscriptions s
        group by account_id,month(start_date)) a on a.account_id = s.account_id and a.start_date = s.start_date
join plans p on p.id = s.plan_id;

+------------+---------+---------------------+----------+---------------+--------------+
| ACCOUNT_id | plan_id | start_date          | Price    | plan_interval | rev          |
+------------+---------+---------------------+----------+---------------+--------------+
|          1 |       1 | 2018-01-03 14:52:13 |  3900.00 | month         |   3.25000000 |
|          1 |       2 | 2018-02-07 11:11:17 |  9900.00 | month         |   8.25000000 |
|          2 |       3 | 2018-01-03 17:40:05 | 99900.00 | year          | 999.00000000 |
+------------+---------+---------------------+----------+---------------+--------------+


问:
mingw gdb do not have layout command
I am debuging a C++ program with gdb on windows using Mingw, But when I type layout command in gdb interactive command line:

```<code>(gdb) layout asm
Undefined command: "layout".  Try "help".
</code>```

the layout is not exists, how to fix that?

答: It seems that gdb TUI support was added to mingw in this pull request https://github.com/msys2/MINGW-packages/pull/1869. Try to update to a latest version of mingw or build gdb package yourself with patches applied from https://github.com/msys2/MINGW-packages/pull/1869/files.</p>

Title: mingw gdb do not have layout command

Body:
I am debuging a C++ program with gdb on windows using Mingw, But when I type layout command in gdb interactive command line:

(gdb) layout asm
Undefined command: "layout".  Try "help".

the layout is not exists, how to fix that?


问:
javascript cannot find a method which exists
I have a pretty simple function declared in my JavaScript file, which is just supposed to return whether or not the validation has begun:

```<code>window.Validator = function(){
    this._started = false;
    this.started = function(){
        return this._started;
    };
}

Validator.started();
</code>```

However, when I call Validator.started(), even though it's literally directly after the declaration, it will throw the error:

Uncaught TypeError: Validator.started is not a function

Really scratching my head with this one and have no idea why it isn't working.

答:
this in a function without 'use strict' points to the global object, that is window.

So your this.started = function(){...} is defined on the window object. Of course, it is only defined after the Validator is called.

So this code works, though it may not how you want to use it.

```<code>window.Validator = function(){
    this._started = false;
    this.started = function(){
        return this._started;
    };
}

Validator();
started();
console.log(_started);
</code>```

If you do use 'use strict', this is undefined in the function definition area. You need to create an Object of Validator, this would be the object when you call the method.

Body:
I have a pretty simple function declared in my JavaScript file, which is just supposed to return whether or not the validation has begun:

window.Validator = function(){
    this._started = false;
    this.started = function(){
        return this._started;
    };
}

Validator.started();

However, when I call Validator.started(), even though it's literally directly after the declaration, it will throw the error:

Uncaught TypeError: Validator.started is not a function

Really scratching my head with this one and have no idea why it isn't working.

Body:
this in a function without 'use strict' points to the global object, that is window.

So your this.started = function(){...} is defined on the window object. Of course, it is only defined after the Validator is called.

So this code works, though it may not how you want to use it.

window.Validator = function(){
    this._started = false;
    this.started = function(){
        return this._started;
    };
}

Validator();
started();
console.log(_started);

If you do use 'use strict', this is undefined in the function definition area. You need to create an Object of Validator, this would be the object when you call the method.


问:
Missing CascadeType.LOCK, CascadeType.REPLICATE, CascadeType.SAVE_UPDATE in cascadetypes
I am not able to find CascadeType.LOCK, CascadeType.REPLICATE, CascadeType.SAVE_UPDATE in Hibernate Cascade Types () .

Here is my pom.xml . Any suggestion please ?

```<code><dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.12.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.17.Final</version>
        </dependency>
    </dependencies>
</code>```

答:
Reason is that javax.persistence.CascadeType does not have constants other than ones shown on screenshot.

If target method takes org.hibernate.annotations.CascadeType as arguments, then issue is simply that wrong class is imported. If the method takes javax.persistence.CascadeType as argument, then choice is limited to constants shown in screenshot.

Body:
I am not able to find CascadeType.LOCK, CascadeType.REPLICATE, CascadeType.SAVE_UPDATE in Hibernate Cascade Types () .

Here is my pom.xml . Any suggestion please ?

<dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.12.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.17.Final</version>
        </dependency>
    </dependencies>


问:
Adding version number on Xamarin.iOS Splash screen
Anyone has an idea how can I update the label and put a version number on there so that I don't need it to write manually every time I publish the new version on iOS. Please download my sample project in this link Splashscreen with version number.

I try to add UIViewController to use it on Storyboard but it's not working.

答:
first thing, it is not possible to provide dynamic value on the launch screen which comes as a default view with the IOS project.
you have to create your own splashscreen by storyboard so you will have viewcontroller code behind and there you can do whatever the details you want to display. you can show the animation also there.

you have to set this splashviewcontroller as a rootviewcontroller in finishlaunching() of appdelegate.

check below code:- try something like this.

public override UIWindow Window { get; set; }
  public RootViewController RootViewController { get; set; }

```<code>  public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions){
     this.Window = new UIWindow(UIScreen.MainScreen.Bounds);
     UINavigationController navigationController = new
     UINavigationController(new SplashViewController());
     Window.RootViewController = navigationController;
</code>```

}

Body:
first thing, it is not possible to provide dynamic value on the launch screen which comes as a default view with the IOS project.
you have to create your own splashscreen by storyboard so you will have viewcontroller code behind and there you can do whatever the details you want to display. you can show the animation also there.

you have to set this splashviewcontroller as a rootviewcontroller in finishlaunching() of appdelegate.

check below code:- try something like this.

public override UIWindow Window { get; set; }
  public RootViewController RootViewController { get; set; }

  public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions){
     this.Window = new UIWindow(UIScreen.MainScreen.Bounds);
     UINavigationController navigationController = new
     UINavigationController(new SplashViewController());
     Window.RootViewController = navigationController;

}


问:
How to submit the form to a different server and from that server return to the same page php
I'm trying to verify user apiKey. so the I have a application which user installs on their server and they need to add their apiKey to activate it. so I've created a form where they can add their apiKey and it'll submit the key to my server and then my server verify the key. but I want to know how to get from which URL we recieved the request so we can send back results to that url?

```<code><form action="my-server-.com/verifyfile.php" method="post">
    <div class="form-group row">
        <label for="email" class="col-lg-2 col-form-label">Enter API Key</label>
        <div class="col-lg-6">
            <input type="text" placeholder="paste your api key here" name="apiKey" class="form-control" required="">
        </div>
        <div class="form-group col-lg-2">
            <input type="submit" value="Register" name="verify-api" class="btn btn-outline-success btn-sm">
        </div>
    </div>
</form>
</code>```

答:
hi you can make redirect back to url from where they came,but for some interaction you cant without proper code on client/user server side
https://www.php.net/manual/en/reserved.variables.server.php</p>

```<code>$_SERVER['HTTP_REFERER']
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
</code>```

Body:
I'm trying to verify user apiKey. so the I have a application which user installs on their server and they need to add their apiKey to activate it. so I've created a form where they can add their apiKey and it'll submit the key to my server and then my server verify the key. but I want to know how to get from which URL we recieved the request so we can send back results to that url?

<form action="my-server-.com/verifyfile.php" method="post">

        Enter API Key

            <input type="text" placeholder="paste your api key here" name="apiKey" class="form-control" required="">

            <input type="submit" value="Register" name="verify-api" class="btn btn-outline-success btn-sm">

</form>

Body:
hi you can make redirect back to url from where they came,but for some interaction you cant without proper code on client/user server side
https://www.php.net/manual/en/reserved.variables.server.php

$_SERVER['HTTP_REFERER']
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.


问:
how to efficiently find if a linux directory including sudirectories has at least 1 file
In my project various jobs are created as files in directories inside subdirectories.
But usually the case is I find that the jobs are mostly in some dirs and not in the most others

currently I use

```<code>find $DIR -type f | head -n 1
</code>```

to know if the directory has atleast 1 file , but this is a waste

how to efficiently  find if a linux directory including sudirectories  has at least 1 file

答:
This command finds the first subdiretory containing at least one file and then stop:

```<code>find . -mindepth 1 -type d -exec bash -c 'c=$(find {} -maxdepth 1 -type f -print -quit);test "x$c" != x' \; -print -quit
</code>```

The first find iterates through all subdirectories and second find finds the first file and then stop.

Body:
In my project various jobs are created as files in directories inside subdirectories.
But usually the case is I find that the jobs are mostly in some dirs and not in the most others

currently I use

find $DIR -type f | head -n 1

to know if the directory has atleast 1 file , but this is a waste

how to efficiently  find if a linux directory including sudirectories  has at least 1 file

Body:
This command finds the first subdiretory containing at least one file and then stop:

find . -mindepth 1 -type d -exec bash -c 'c=$(find {} -maxdepth 1 -type f -print -quit);test "x$c" != x' \; -print -quit

The first find iterates through all subdirectories and second find finds the first file and then stop.


问:
How to get properties from an Object filtering by an array in Javascript
I have a JS object like this:

```<code>const myObj = {
  '$prop1': 1,
  '$prop2': 2,
  '$prop3': 3
};
</code>```

and an array of object like this:

```<code>const myArray = [
  {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop1'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop2'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop5'
  },
];
</code>```

I am trying to write a function fo filter myObj and only get the fields I can find in myArray.propKey.

this is what I tried so far with no luck:

```<code>export const filterVariantContentByColumns = (myObj, myArray) => {
  const objArray = Object.keys(myObj).map(i => myObj[i]);
  return objArray.filter(value => myArray.includes(value.key_name));

  console.log(res);
};
</code>```

any idea how to do that please?

答:
Turn the myArray into a Set of propKeys first, then filter myObj by whether the key being iterated over is in the Set:

const myObj = {
  '$prop1': 1,
  '$prop2': 2,
  '$prop3': 3
};

const myArray = [
  {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop1'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop2'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop5'
  },
];
const haveKeys = new Set(myArray.map(({ propKey }) => propKey));
const output = Object.entries(myObj)
  .filter(([key]) => haveKeys.has(key))
console.log(output);```

Body:
I have a JS object like this:

const myObj = {
  '$prop1': 1,
  '$prop2': 2,
  '$prop3': 3
};

and an array of object like this:

const myArray = [
  {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop1'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop2'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop5'
  },
];

I am trying to write a function fo filter myObj and only get the fields I can find in myArray.propKey.

this is what I tried so far with no luck:

export const filterVariantContentByColumns = (myObj, myArray) => {
  const objArray = Object.keys(myObj).map(i => myObj[i]);
  return objArray.filter(value => myArray.includes(value.key_name));

  console.log(res);
};

any idea how to do that please?


问:
bitbucket pipeline with docker, how to add source dependencies from a git repo
Im using ROS industrial CI with pipelines. It fails to build because of a dependency on a package that I have to build from source.

Normally I would clone the source git repo and just build it. But I don't know how to specify that dependency on pipelines.

```<code>git clone https://github.com/AprilRobotics/apriltag.git      # Clone Apriltag library
cd april*
cmake .
sudo make install
</code>```

Would appreciate the help

答:
Well, let me share with you my approach on that. I use GitLab CI, which I guess it might be similar.

In my repository, I have a rosinstall file including the packages that I need to build from source.

In my case, coscr.rosinstall looks like

```<code>- git:
    local-name: ira_laser_tools
    uri: https://github.com/iralabdisco/ira_laser_tools.git
    version: master
</code>```

Then in my .gitlab-ci.yml file, I handle it like that:

```<code>stages:
  - build
  - test

image: osrf/ros:melodic-desktop-full

before_script:
  - apt-get update && apt-get upgrade -y
  - apt-get install -y python-rosinstall python-rosinstall-generator python-wstool build-essential
  - apt-get install -y alsa-utils
  - apt-get clean
  - mkdir -p ~/catkin_ws/src

build:
  stage: build
  script:
    - cd ~/catkin_ws/src
    - git clone https://gitlab.com/______/cs_monster.git
    - cd ~/catkin_ws
    - wstool init src src/cs_monster/coscr.rosinstall
    - rosdep install --from-paths src --ignore-src -r -y
    - catkin_make -DCMAKE_BUILD_TYPE=Release
</code>```

You can see how I use rosdep to make the trick.
As far as I remember it was working. Either way, I hope it can give you some hints.

Body:
Im using ROS industrial CI with pipelines. It fails to build because of a dependency on a package that I have to build from source.

Normally I would clone the source git repo and just build it. But I don't know how to specify that dependency on pipelines.

git clone https://github.com/AprilRobotics/apriltag.git      # Clone Apriltag library
cd april*
cmake .
sudo make install

Would appreciate the help

Body:
Well, let me share with you my approach on that. I use GitLab CI, which I guess it might be similar.

In my repository, I have a rosinstall file including the packages that I need to build from source.

In my case, coscr.rosinstall looks like

- git:
    local-name: ira_laser_tools
    uri: https://github.com/iralabdisco/ira_laser_tools.git
    version: master

Then in my .gitlab-ci.yml file, I handle it like that:

stages:
  - build
  - test

image: osrf/ros:melodic-desktop-full

before_script:
  - apt-get update && apt-get upgrade -y
  - apt-get install -y python-rosinstall python-rosinstall-generator python-wstool build-essential
  - apt-get install -y alsa-utils
  - apt-get clean
  - mkdir -p ~/catkin_ws/src

build:
  stage: build
  script:
    - cd ~/catkin_ws/src
    - git clone https://gitlab.com/______/cs_monster.git
    - cd ~/catkin_ws
    - wstool init src src/cs_monster/coscr.rosinstall
    - rosdep install --from-paths src --ignore-src -r -y
    - catkin_make -DCMAKE_BUILD_TYPE=Release

You can see how I use rosdep to make the trick.
As far as I remember it was working. Either way, I hope it can give you some hints.


问:
dplyr - recode several columns at once
Suppose you have a dataframe with variables named X1 - X30 and Y1 - Y30. Each of these variables holds integers 1 - 5. We wish to recode some of the variables starting with X like this:

```<code>df %<>%
   mutate_at(vars(starts_with("X") &
                  ends_with("5", "8", "16", "22", "28")),
             recode, "1" = 5, "2" = 4, "4" = 2, "5" = 1)
</code>```

This will, however, return the following error:

```<code>Error in UseMethod("recode") :
  no applicable method for 'recode' applied to an object of class "c('tbl_df', 'tbl', 'data.frame')"
</code>```

This is because recode needs to take a vector as an argument. So what is the way to bypass this?

答:
mutate_at is entirely designed to take functions that take vectors as an argument, like recode, that is not the issue. Your error is just because you don't use select helpers as logical calls chained with &, instead chain them using , within vars().

Also, if you want what you were aiming for, you would want to use matches to select only columns starting with X and ending with certain numbers.

library(dplyr)

set.seed(123)
df <- data.frame("X1" = sample(1:5, 10, TRUE),
                 "X2" = sample(1:5, 10, TRUE),
                 "X3" = sample(1:5, 10, TRUE))
df
#>    X1 X2 X3
#> 1   3  5  2
#> 2   3  3  1
#> 3   2  3  3
#> 4   2  1  4
#> 5   3  4  1
#> 6   5  1  3
#> 7   4  1  5
#> 8   1  5  4
#> 9   2  3  2
#> 10  3  2  5

df %>%
  mutate_at(vars(matches("^X.*1|2$")),
            recode, "1" = 5, "2" = 4, "3" = 3,"4" = 2, "5" = 1)
#>    X1 X2 X3
#> 1   3  1  2
#> 2   3  3  1
#> 3   4  3  3
#> 4   4  5  4
#> 5   3  2  1
#> 6   1  5  3
#> 7   2  5  5
#> 8   5  1  4
#> 9   4  3  2
#> 10  3  4  5
```

Title: dplyr - recode several columns at once

Body:
Suppose you have a dataframe with variables named X1 - X30 and Y1 - Y30. Each of these variables holds integers 1 - 5. We wish to recode some of the variables starting with X like this:

df %<>%
   mutate_at(vars(starts_with("X") &
                  ends_with("5", "8", "16", "22", "28")),
             recode, "1" = 5, "2" = 4, "4" = 2, "5" = 1)

This will, however, return the following error:

Error in UseMethod("recode") :
  no applicable method for 'recode' applied to an object of class "c('tbl_df', 'tbl', 'data.frame')"

This is because recode needs to take a vector as an argument. So what is the way to bypass this?


问:
No setter/field found
Hi everyone I try to retrieve data from Firebase dataset and I keep getting this error even tho I tried every single solution from StackOverflow and what I was able to find on Google but without any benefit.

Below I will link the Activity and the Class and the datasets.

I'm new to Android and I can't understand why is not working since some people solved the problem and I did the same thing but nothing worked.

Thank you in advance.

CODE ACTIVITY

```<code>package com.example.ipill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FirebaseSearch extends AppCompatActivity {

    private EditText mSearchField;
    private ImageButton mSearchBtn;

    private RecyclerView mResultList;

    private DatabaseReference mUserDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firebasesearch);

        mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

        mSearchField = (EditText) findViewById(R.id.search_field);

        mSearchBtn = findViewById(R.id.search_btn);
        mResultList = (RecyclerView)findViewById(R.id.result_list);

        mResultList.setHasFixedSize(true);
        mResultList.setLayoutManager(new LinearLayoutManager(this));

        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String searchText = mSearchField.getText().toString();

                firebaseUserSearch(searchText);

            }
        });

    }

    private void firebaseUserSearch(String searchText) {

        Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();

        Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");

        FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(

                Users.class,
                R.layout.list_layout,
                UsersViewHolder.class,
                firebaseSearchQuery

        ) {
            @Override
            protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
                viewHolder.setDetails(model.getName(), model.getSurname());

            }
        };

        mResultList.setAdapter(firebaseRecyclerAdapter);

    }

    // View Holder Class

    public static class UsersViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public UsersViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }

        public void setDetails(String name, String surname) {

            TextView user_name = (TextView) mView.findViewById(R.id.name_text);
            TextView user_surname = (TextView) mView.findViewById(R.id.status_text);

            user_name.setText(name);
            user_surname.setText(surname);

        }

    }
}
</code>```

enter code here

DATABASE:

```<code>{
  "Users" : {
    "01" : {
      "Name" : "Alex",
      "Surname" : "Kyto"
    }
  }
}
</code>```

The problem that I have:

No setter/field for Surname found on class com.example.ipill.Users (fields/setters are case
    sensitive!)
    No setter/field for Name found on class com.example.ipill.Users (fields/setters are case sensitive!)

Model CLASS

```<code>package com.example.ipill;

public class Users {

    public String name, surname;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Users(String name, String surname, String status) {
        this.name = name;
        this.surname = surname;

    }

    public Users(){

    }

}
</code>```

enter code here

答:
To be able to map your POJO class to the database, it needs to have the same variable names, also the instance variables are case sensitive. The problem is that in your database, you have Name and Surname with capital letter while in the POJO class you have them with lowercase letter.

Therefore, you need to change your database to the following:

```<code>{
  "Users" : {
    "01" : {
      "name" : "Alex",
      "surname" : "Kyto"
    }
  }
}
</code>```

Title: No setter/field found

Body:
Hi everyone I try to retrieve data from Firebase dataset and I keep getting this error even tho I tried every single solution from StackOverflow and what I was able to find on Google but without any benefit.

Below I will link the Activity and the Class and the datasets.

I'm new to Android and I can't understand why is not working since some people solved the problem and I did the same thing but nothing worked.

Thank you in advance.

CODE ACTIVITY

package com.example.ipill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FirebaseSearch extends AppCompatActivity {

    private EditText mSearchField;
    private ImageButton mSearchBtn;

    private RecyclerView mResultList;

    private DatabaseReference mUserDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firebasesearch);

        mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

        mSearchField = (EditText) findViewById(R.id.search_field);

        mSearchBtn = findViewById(R.id.search_btn);
        mResultList = (RecyclerView)findViewById(R.id.result_list);

        mResultList.setHasFixedSize(true);
        mResultList.setLayoutManager(new LinearLayoutManager(this));

        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String searchText = mSearchField.getText().toString();

                firebaseUserSearch(searchText);

            }
        });

    }

    private void firebaseUserSearch(String searchText) {

        Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();

        Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");

        FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(

                Users.class,
                R.layout.list_layout,
                UsersViewHolder.class,
                firebaseSearchQuery

        ) {
            @Override
            protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
                viewHolder.setDetails(model.getName(), model.getSurname());

            }
        };

        mResultList.setAdapter(firebaseRecyclerAdapter);

    }

    // View Holder Class

    public static class UsersViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public UsersViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }

        public void setDetails(String name, String surname) {

            TextView user_name = (TextView) mView.findViewById(R.id.name_text);
            TextView user_surname = (TextView) mView.findViewById(R.id.status_text);

            user_name.setText(name);
            user_surname.setText(surname);

        }

    }
}

enter code here

DATABASE:

{
  "Users" : {
    "01" : {
      "Name" : "Alex",
      "Surname" : "Kyto"
    }
  }
}

The problem that I have:

No setter/field for Surname found on class com.example.ipill.Users (fields/setters are case
    sensitive!)
    No setter/field for Name found on class com.example.ipill.Users (fields/setters are case sensitive!)

Model CLASS

package com.example.ipill;

public class Users {

    public String name, surname;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Users(String name, String surname, String status) {
        this.name = name;
        this.surname = surname;

    }

    public Users(){

    }

}

enter code here

Body:
To be able to map your POJO class to the database, it needs to have the same variable names, also the instance variables are case sensitive. The problem is that in your database, you have Name and Surname with capital letter while in the POJO class you have them with lowercase letter.

Therefore, you need to change your database to the following:

{
  "Users" : {
    "01" : {
      "name" : "Alex",
      "surname" : "Kyto"
    }
  }
}


答:
Change your Users property like below to match with Firebase. You database and POJO should align to work with.

```<code>public String Name, Surname; //Capitalize each property
</code>```

Title: No setter/field found

Body:
Change your Users property like below to match with Firebase. You database and POJO should align to work with.

public String Name, Surname; //Capitalize each property


问:
SEO question with nuxt-link in a nuxt template
I have a card where for a demand on SEO i need to put the nuxt link on the title but the whole card must be clickable with a method :

```<code><template>
  <div @click.prevent="clickit(item)" >
    <img class="background" :src="item.backgroundImage" />
    <nuxt-link
      :to="'/road/' + item.id"
    >{{ item.text }}</nuxt-link>
    <img class="mask" :src="item.backgroundMask" />
  </div>
</template>

<script>
export default {
  props: {
    item: {
      type: Object,
      default: () => {}
    }
  },
  methods: {
    clickit(item) {
      this.$router.push({
        path: "/road/" + item.id
      });
    }
  }
};
</script>
</code>```

So i did like that but the problem is when i click only in the title it fire two events. Is there a way to prevent default in a nuxt link ?

答:
i've found the solution :

```<code> <nuxt-link
    :to="'/road/' + item.id"
     @click.native="fuga"
     event
     class="ititle"
 >{{road.name}}</nuxt-link>
</code>```

and then i adde this method :

```<code>fuga(e) {
  e.preventDefault();
}
</code>```

Body:
I have a card where for a demand on SEO i need to put the nuxt link on the title but the whole card must be clickable with a method :

<template>

    <nuxt-link
      :to="'/road/' + item.id"
    >{{ item.text }}</nuxt-link>

</template>

So i did like that but the problem is when i click only in the title it fire two events. Is there a way to prevent default in a nuxt link ?

Body:
i've found the solution :

 <nuxt-link
    :to="'/road/' + item.id"
     @click.native="fuga"
     event
     class="ititle"
 >{{road.name}}</nuxt-link>

and then i adde this method :

fuga(e) {
  e.preventDefault();
}


问:
Why the move-constructor is not called ? (only the constuctor by default, and nothing else)
Could you explain me why, in the following, code,

```<code>#include <iostream>
#include <variant>
#include <string>

class MySecondType {
public:
    MySecondType() { std::cout << "Constructeur par défaut de MySecondType\n"; }
    MySecondType(const MySecondType&) // Constructeur par copie
    {std::cout<< "Constructeur par copie de MySecondType\n";}
    MySecondType(MySecondType&&) noexcept//Constructeur par déplacement
    {
        std::cout << "COnstructeur par déplacement de MySecondType\n";
    }

    MySecondType& operator=(MySecondType&&) noexcept
    {
        std::cout << "Opérateur d'affection par déplacement\n";
        return *this;
    }

    MySecondType& operator=(MySecondType&)
    {
        std::cout << "Opérateur d'affection par copie\n";
        return *this;
    }

    ~MySecondType() {
        std::cout << "Destructeur de MySecondType\n";
    }

};

int main() {

    MySecondType e;
    e= MySecondType() ;
return 0;
}
</code>```

I have the result I wait, with :

```<code>MySecondType e;
e= MySecondType() ;
</code>```

BUT I don't have it , if I do :

```<code>MySecondType e = MySecondType() ;
</code>```

I expected that the line :

MySecondType e = MySecondType() ;

would call the move constructor(after the default constructor), but it does not call it. It only creates an object with the default constructor , and that's nothing else.

Can you explain me why ?

Thank you

答:
I'm asuming you actually do what @Jacob hinted at, i.e. MySecondType e = MySecondType();.

If so, then the compiler is eliding the copy/move constructor. It sees that you are creating a temporary object and right after assigning it to a variable. So instead of doing that, which would be inefficient, it skips the copy/move step and directly constructs the object at its final destination.

AFAIK, this is an optional optimization pre-C++17. Starting in C++17 it's mandatory.

Body:
Could you explain me why, in the following, code,

#include <iostream>
#include <variant>
#include <string>

class MySecondType {
public:
    MySecondType() { std::cout << "Constructeur par défaut de MySecondType\n"; }
    MySecondType(const MySecondType&) // Constructeur par copie
    {std::cout<< "Constructeur par copie de MySecondType\n";}
    MySecondType(MySecondType&&) noexcept//Constructeur par déplacement
    {
        std::cout << "COnstructeur par déplacement de MySecondType\n";
    }

    MySecondType& operator=(MySecondType&&) noexcept
    {
        std::cout << "Opérateur d'affection par déplacement\n";
        return *this;
    }

    MySecondType& operator=(MySecondType&)
    {
        std::cout << "Opérateur d'affection par copie\n";
        return *this;
    }

    ~MySecondType() {
        std::cout << "Destructeur de MySecondType\n";
    }

};

int main() {

    MySecondType e;
    e= MySecondType() ;
return 0;
}

I have the result I wait, with :

MySecondType e;
e= MySecondType() ;

BUT I don't have it , if I do :

MySecondType e = MySecondType() ;

I expected that the line :

MySecondType e = MySecondType() ;

would call the move constructor(after the default constructor), but it does not call it. It only creates an object with the default constructor , and that's nothing else.

Can you explain me why ?

Thank you


问:
How to change python version in Anaconda?
I am trying to get into deep learning. I installed Anaconda to use jupyter and generally not to care about installing all of those packages like matplotlib etc myself. But I cannot install tensorflow as it works only with Python  3.4, 3.5, or 3.6 but I have 3.7. After I read about it I installed python 3.6.8. I uninstalled Anaconda and installed it again, nothing changed. After that, I used this command

conda install python=3.6.8

to presumably install python 3.6.8 for it (I found this solution somewhere on the web). The command worked but didn't change anything. Please help

答:
The most pain-free approach that worked for me was to install the legacy version of Anaconda. If you want Python 3.6 as default, I recommand downloading Anaconda 5.2.0 which was the last version to use Python 3.6 in base environment as default. (Legacy versions can be found here.)

If you also want the latest version of Anaconda, there is an easy way. With Anaconda 5.2.0 installed, you can actually update to newer versions of Anaconda by

```<code>conda update anaconda
</code>```

which will try to update all your packages except keepping Python at 3.6.x.

Body:
The most pain-free approach that worked for me was to install the legacy version of Anaconda. If you want Python 3.6 as default, I recommand downloading Anaconda 5.2.0 which was the last version to use Python 3.6 in base environment as default. (Legacy versions can be found here.)

If you also want the latest version of Anaconda, there is an easy way. With Anaconda 5.2.0 installed, you can actually update to newer versions of Anaconda by

conda update anaconda

which will try to update all your packages except keepping Python at 3.6.x.


问:
How to insert index using if statement when using map function in react?
I am using redux and I am working on receiving data about membership information from action and processing it from components.

And try to process the data to a table.

I took data from user action and created a table through map functions... The incoming data contains

Data received as action ....

```<code>[{create_date : "2020-02-16T03:00:00Z", id:"test"},
{create_date : "2020-02-16T01:00:00Z", id:"test1"},
{create_date : "2020-02-14T03:00:00Z", id:"test2"},
{create_date : "2020-02-14T01:00:00Z", id:"test3"},
{create_date : "2020-02-14T00:00:01Z", id:"test4"},
{create_date : "2020-02-13T03:00:00Z", id:"test5"},
...]

</code>```

As you can see, only create_date id is included.

I would like to order them by date and number them in order by next day after day.

For example, would like to print like this.

```<code>index    create_date           id
2        2020-02-16T03:00:00Z  test
1        2020-02-16T01:00:00Z  test1

3        2020-02-14T03:00:00Z  test2
2        2020-02-14T01:00:00Z  test3
1        2020-02-14T00:00:01Z  test4

1        2020-02-13T03:00:00Z  test5
</code>```

How to insert index using if statement when using map function in react??

Mycode

```<code>    render() {
        const {user_list} = this.props;
        console.log(user_list);
        return (
            <div className="animated fadeIn">
                <Row>
                    <Col xl={12}>
                        <Card>
                            <CardHeader>
                                <i className="fa fa-align-justify"></i>userlist
                            </CardHeader>
                            <CardBody>
                                <Search searchUser={this.searchUser}/>
                                <Table responsive hover>
                                    <thead>
                                    <tr><th scope="col">Index</th>
                                        <th scope="col">create_time</th>
                                        <th scope="col">id/name</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {user_list.length > 0 && user_list.map((item, index) => (
                                        <tr key={item.id.toString()}>
                                            <td>{index}</td> //<<Does this change by date index.. if statement?
                                            <td className={'datetime'}>
                                                {item.hasOwnProperty('create_date') &&
                                                    <div>
                                                        {moment(item.create_date).format('YYYY-MM-DD')}<br/>
                                                        {moment(item.create_date).format('HH:mm')}
                                                    </div>
                                                }
                                            </td>
                                            <td scope="row">
                                                    {item.displayName}
                                            </td>

                                        </tr>
                                    ))}
                                    </tbody>
                                </Table>
                            </CardBody>
                        </Card>
                    </Col>
                </Row>

            </div>
        )
    }

....

</code>```

答:
Here's a minimal verifiable complete working demo (https://codepen.io/Alexander9111/pen/rNVeyyY), taking part of the excellent grouping and flattening function from @bedew and then sorting it into date and "index" to give the following output (in React CodePen):

JS:

```<code>const action_data = [
  {create_date : "2020-02-16T03:00:00Z", id:"test"},
  {create_date : "2020-02-16T01:00:00Z", id:"test1"},
  {create_date : "2020-02-14T03:00:00Z", id:"test2"},
  {create_date : "2020-02-14T01:00:00Z", id:"test3"},
  {create_date : "2020-02-14T00:00:01Z", id:"test4"},
  {create_date : "2020-02-13T03:00:00Z", id:"test5"}
];

const Demo = (props) => {
  console.log(props.action)

  let groups = {}
  for (let e of props.action.reverse()) {
    let date = e.create_date.slice(0, 10)
    if (groups[date]) {
      let group = groups[date];
      group.push({ index: group.length + 1, ...e });
    } else {
      groups[date] = [{ index: 1, ...e }]
    }
  }

  const dates = Object.keys(groups).reverse()
  const flatten = []
  for (let date of dates) {
    flatten.push(...(groups[date].reverse()))
  }
  const user_list = flatten.sort((a,b) => {
    if (moment(b.create_date).diff(moment(a.create_date), 'days') == 0){
      return (b.index - a.index);
    } else {
      return 0;
    }
  });
  console.log(user_list);

  return(
    <div>
    <table>
      <thead>
        <tr>
          <th scope="col">Index</th>
          <th scope="col">create_time</th>
          <th scope="col">id/name</th>
        </tr>
      </thead>
      <tbody>
        {user_list.length > 0 && user_list.map((item, index) => (
          <tr key={item.id.toString()}>
            <td>{item.index}</td>
            <td className={'datetime'}>
              {item.hasOwnProperty('create_date') &&
                <div>
                  {moment(item.create_date).format('YYYY-MM-DD') + "  "+ moment(item.create_date).format('HH:mm')}
                </div>
              }
            </td>
            <td scope="row">
              {item.id}
            </td>
          </tr>
        ))}
      </tbody>
    </table>
    </div>
  )
}

ReactDOM.render(
  <Demo action={action_data}/>,
  document.getElementById('root')
);
</code>```

Important is the sort function:

```<code>const user_list = flatten.sort((a,b) => {
    if (moment(b.create_date).diff(moment(a.create_date), 'days') == 0){
      return (b.index - a.index);
    } else {
      return 0;
    }
  });
</code>```

If the dates are not the same day, then don't sort, but if they are the same day then sort on the "index" created in the flatten array earlier.

Again demo here: https://codepen.io/Alexander9111/pen/rNVeyyY

Body:
I am using redux and I am working on receiving data about membership information from action and processing it from components.

And try to process the data to a table.

I took data from user action and created a table through map functions... The incoming data contains

Data received as action ....

[{create_date : "2020-02-16T03:00:00Z", id:"test"},
{create_date : "2020-02-16T01:00:00Z", id:"test1"},
{create_date : "2020-02-14T03:00:00Z", id:"test2"},
{create_date : "2020-02-14T01:00:00Z", id:"test3"},
{create_date : "2020-02-14T00:00:01Z", id:"test4"},
{create_date : "2020-02-13T03:00:00Z", id:"test5"},
...]

As you can see, only create_date id is included.

I would like to order them by date and number them in order by next day after day.

For example, would like to print like this.

index    create_date           id
2        2020-02-16T03:00:00Z  test
1        2020-02-16T01:00:00Z  test1

3        2020-02-14T03:00:00Z  test2
2        2020-02-14T01:00:00Z  test3
1        2020-02-14T00:00:01Z  test4

1        2020-02-13T03:00:00Z  test5

How to insert index using if statement when using map function in react??

Mycode

    render() {
        const {user_list} = this.props;
        console.log(user_list);
        return (

                <Row>
                    <Col xl={12}>
                        <Card>
                            <CardHeader>
                                userlist
                            </CardHeader>
                            <CardBody>
                                <Search searchUser={this.searchUser}/>

Index
                                        create_time
                                        id/name

                                    {user_list.length > 0 && user_list.map((item, index) => (

                                            {index}	 //<<Does this change by date index.. if statement?

                                                {item.hasOwnProperty('create_date') &&

                                                        {moment(item.create_date).format('YYYY-MM-DD')}

                                                        {moment(item.create_date).format('HH:mm')}

                                                }

                                                    {item.displayName}

                                    ))}

                            </CardBody>
                        </Card>
                    </Col>
                </Row>

        )
    }

....

Body:
Here's a minimal verifiable complete working demo (https://codepen.io/Alexander9111/pen/rNVeyyY), taking part of the excellent grouping and flattening function from @bedew and then sorting it into date and "index" to give the following output (in React CodePen):

JS:

const action_data = [
  {create_date : "2020-02-16T03:00:00Z", id:"test"},
  {create_date : "2020-02-16T01:00:00Z", id:"test1"},
  {create_date : "2020-02-14T03:00:00Z", id:"test2"},
  {create_date : "2020-02-14T01:00:00Z", id:"test3"},
  {create_date : "2020-02-14T00:00:01Z", id:"test4"},
  {create_date : "2020-02-13T03:00:00Z", id:"test5"}
];

const Demo = (props) => {
  console.log(props.action)

  let groups = {}
  for (let e of props.action.reverse()) {
    let date = e.create_date.slice(0, 10)
    if (groups[date]) {
      let group = groups[date];
      group.push({ index: group.length + 1, ...e });
    } else {
      groups[date] = [{ index: 1, ...e }]
    }
  }

  const dates = Object.keys(groups).reverse()
  const flatten = []
  for (let date of dates) {
    flatten.push(...(groups[date].reverse()))
  }
  const user_list = flatten.sort((a,b) => {
    if (moment(b.create_date).diff(moment(a.create_date), 'days') == 0){
      return (b.index - a.index);
    } else {
      return 0;
    }
  });
  console.log(user_list);

  return(
    <div>
    <table>
      <thead>
        <tr>
          <th scope="col">Index</th>
          <th scope="col">create_time</th>
          <th scope="col">id/name</th>
        </tr>
      </thead>
      <tbody>
        {user_list.length > 0 && user_list.map((item, index) => (
          <tr key={item.id.toString()}>
            <td>{item.index}</td>
            <td className={'datetime'}>
              {item.hasOwnProperty('create_date') &&
                <div>
                  {moment(item.create_date).format('YYYY-MM-DD') + "  "+ moment(item.create_date).format('HH:mm')}
                </div>
              }
            </td>
            <td scope="row">
              {item.id}
            </td>
          </tr>
        ))}
      </tbody>
    </table>
    </div>
  )
}

ReactDOM.render(
  <Demo action={action_data}/>,
  document.getElementById('root')
);

Important is the sort function:

const user_list = flatten.sort((a,b) => {
    if (moment(b.create_date).diff(moment(a.create_date), 'days') == 0){
      return (b.index - a.index);
    } else {
      return 0;
    }
  });

If the dates are not the same day, then don't sort, but if they are the same day then sort on the "index" created in the flatten array earlier.

Again demo here: https://codepen.io/Alexander9111/pen/rNVeyyY


问:
How does kube-proxy behave when it can't reach the master?
From what I've read about Kubernetes, if the master(s) die, the workers should still be able to function as normal (https://stackoverflow.com/a/39173007/281469), although no new scheduling will occur.

However, I've found this to not be the case when the master can also schedule worker pods. Take a 2-node cluster, where one node is a master and the other a worker, and the master has the taints removed:

If I shut down the master and docker exec into one of the containers on the worker I can see that:

```<code>nc -zv ip-of-pod 80
</code>```

succeeds, but

```<code>nc -zv ip-of-service 80
</code>```

fails half of the time. The Kubernetes version is v1.15.10, using iptables mode for kube-proxy.

I'm guessing that since the kube-proxy on the worker node can't connect to the apiserver, it will not remove the master node from the iptables rules.

Questions:

Is it expected behaviour that kube-proxy won't stop routing to pods on master nodes, or is there something "broken"?

Are any workarounds available for this kind of setup to allow the worker nodes to still function correctly?

I realise the best thing to do is separate the CP nodes but that's not viable for what I'm working on at the moment.

答:
Is it expected behaviour that kube-proxy won't stop routing to pods on
  master nodes, or is there something "broken"?

Are any workarounds
  available for this kind of setup to allow the worker nodes to still
  function correctly?

The cluster master plays the role of decision maker for the various activities in cluster's nodes. This can include scheduling workloads, managing the workloads' lifecycle, scaling etc.. Each node is managed by the master components and contains the services necessary to run pods. The services on a node typically includes the kube-proxy, container runtime and kubelet.

The kube-proxy component enforces network rules on nodes and helps kubernetes in managing the connectivity among Pods and Services. Also, the kube-proxy, acts as an egress-based load-balancing controller which keeps monitoring the the kubernetes API server and continually updates node's iptables subsystem based on it.

In simple terms, the master node only is aware of everything and is in charge of creating the list of routing rules as well based on node addition or deletion etc. kube-proxy plays a kind of enforcer whereby it takes charge of checking with master, syncing the information and enforcing the rules on the list.

If the master node(API server) is down, the cluster will not be able to respond to API commands or deploy nodes.  If another master node is not available, there shall be no one else available who can instruct the worker nodes on change in work allocation and hence they shall continue to execute the operations that were earlier scheduled by the master until the time the master node is back and gives different instructions. Inline to it, kube-proxy shall also be unable to get the latest rules by sync up with master, however it shall not stop routing and shall continue to handle the networking and routing functionalities (uses the earlier iptable rules that were determined before the master node went down) that shall allow network communication to your pods provided all pods in worker nodes are still up and running.

Single master node based architecture is not a preferred deployment architecture for production. Considering that resilience and reliability is one of the major business goal of kubernetes, it is recommended as a best practice to have HA cluster based architecture to avoid single point of failure.

Body:
From what I've read about Kubernetes, if the master(s) die, the workers should still be able to function as normal (https://stackoverflow.com/a/39173007/281469), although no new scheduling will occur.

However, I've found this to not be the case when the master can also schedule worker pods. Take a 2-node cluster, where one node is a master and the other a worker, and the master has the taints removed:

If I shut down the master and docker exec into one of the containers on the worker I can see that:

nc -zv ip-of-pod 80

succeeds, but

nc -zv ip-of-service 80

fails half of the time. The Kubernetes version is v1.15.10, using iptables mode for kube-proxy.

I'm guessing that since the kube-proxy on the worker node can't connect to the apiserver, it will not remove the master node from the iptables rules.

Questions:

Is it expected behaviour that kube-proxy won't stop routing to pods on master nodes, or is there something "broken"?

Are any workarounds available for this kind of setup to allow the worker nodes to still function correctly?

I realise the best thing to do is separate the CP nodes but that's not viable for what I'm working on at the moment.


问:
Newline for Google Calendar Api?
I'm trying to insert the description of an event in google calendar from my web application and i cant get \n or
 to be interpreted as a line break. How does the google calendar interpret newlines? Help would be appreciated!

答:
You can use an intent to add the description using \n for the newline. This code

```<code>        Intent intentCal = new Intent(Intent.ACTION_INSERT)
                .setData(CalendarContract.Events.CONTENT_URI)
                .putExtra(CalendarContract.Events.ALL_DAY, true)
                .putExtra(CalendarContract.Events.TITLE, "title")
                .putExtra(CalendarContract.Events.DESCRIPTION,"abc\ndef");
        startActivity(intentCal);
</code>```

produces the event description

```<code>abc
def
</code>```

If you are using a string instead of the literal above, be sure the string doesn't already have the slashes escaped, ie. "abc\\ndef" - when you output the string (eg. using Log.d) it looks like "abc\ndef", but of course it is not the same. For example, if you get a selection from a webview using

```<code>webview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
                        value->calendarString(value));
</code>```

then the string sent to the calendarString function in value has escaped slashes, and produces the event description

```<code>"abc\ndef"
</code>```

(complete with beginning and ending quotes.)

Title: Newline for Google Calendar Api?

Body:
You can use an intent to add the description using \n for the newline. This code

        Intent intentCal = new Intent(Intent.ACTION_INSERT)
                .setData(CalendarContract.Events.CONTENT_URI)
                .putExtra(CalendarContract.Events.ALL_DAY, true)
                .putExtra(CalendarContract.Events.TITLE, "title")
                .putExtra(CalendarContract.Events.DESCRIPTION,"abc\ndef");
        startActivity(intentCal);

produces the event description

abc
def

If you are using a string instead of the literal above, be sure the string doesn't already have the slashes escaped, ie. "abc\\ndef" - when you output the string (eg. using Log.d) it looks like "abc\ndef", but of course it is not the same. For example, if you get a selection from a webview using

webview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
                        value->calendarString(value));

then the string sent to the calendarString function in value has escaped slashes, and produces the event description

"abc\ndef"

(complete with beginning and ending quotes.)