问:
How do I rotate a html canvas shape by only using a transform?
I am wondering how you can rotate an image by only using the transform function. From my understanding this is not possible, since the only things you can do with transform are the following:

Horizontal scaling

Horizontal skewing

Vertical skewing

Vertical scaling

Horizontal moving

Vertical moving

Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations

And I don't see how any of these would be able to rotate the shape, is this even possible. I assume it must be possible, since rotate is in-fact a type transformation.

答:
2D transform basics

6 values as 3 vectors

The transform is a set of 6 numbers. The 6 numbers as 3 pairs represent the direction and scale of the x axis, the direction and scale of the y axis, and the position of the origin.

Default transform AKA Identity matrix

The default transform (called the identity matrix) has the values ctx.setTransform(1, 0, 0, 1, 0, 0) meaning that

the x axis is 1 transformed pixel per CSS pixel in the direction {x: 1, y: 0} left to right

the y axis is 1 transformed pixel per CSS pixel in the direction {x: 0, y: 1} top to bottom

the origin is at pixel location {x: 0, y: 0} top left corner

Scaling

If we scale the transform we increase the length of the first two vectors. To scale by 2 the transform is ctx.setTransform(2, 0, 0, 2, 0, 0);

the x axis is 1 transformed pixel for every 2 CSS pixel in the x direction {x: 2, y: 0} left to right

the y axis is 1 transformed pixel for every 2 CSS pixel in the y direction {x: 0, y: 2} top to bottom

the origin is still top left {x: 0, y: 0}

Rotate and translation

If we want to rotate by 90deg a square 256 by 256 image then the transform is ctx.setTransform(0, 1, -1, 0, 256, 0)

the x axis is 1 transformed pixel per CSS pixel down in the y direction {x: 0, y: 1}

the y axis is 1 transformed pixel per CSS pixel across in the negative x direction {x: -1, y: 0} right to left

the origin (where the image 0, 0 will be on the canvas) is  {x: 256, y: 0}

Thus if we run

```<code>ctx.setTransform(0, 1, -1, 0, 256, 0);
ctx.drawImage(myImage, 0, 0, 256, 256); // will draw image rotated 90deg CW
</code>```

We get a rotated image.

A vector

A vector is two values that have a x and y value. The vector defines a direction and length.

Create a rotated unit vector

To convert a direction to a vector we use sin and cos

```<code>const myDirection = angle;
const myDirectionAsRadians = angle * (Math.PI / 180);  // convert angle to radians

const x = Math.cos(myDirectionAsRadians)
const y = Math.sin(myDirectionAsRadians)
</code>```

If we set myDirection to 90 (deg) then x = 0 and y = 1 pointing down the canvas

Using sin and cos creates a vector in any direction. It has a special property in that its length is always 1. We call such a vector a Unit vector. You may sometimes see a vector being normalized. This converts a vector of any length to a unit vector. It is done by dividing the vector x and y by its length.

```<code> function normalize(vector) {
     const length = Math.hypot(vector.x, vector.y);
     vector.x /= length;
     vector.y /= length;
 }
</code>```

NOTE a vector with zero length eg x: 0, y:0 can not be normalized. Not because it has no length (the length is 0) but because it has no direction.

Scale a rotated vector

We can define an angle and a scale

```<code>const myDirection = -90;
const myDirectionAsRadians = -90 * (Math.PI / 180);  // -90 as radians
const myScale = 2;

const x = Math.cos(myDirectionAsRadians) * myScale
const y = Math.sin(myDirectionAsRadians) * myScale
</code>```

Now for -90 deg the vector is x = 0 and y = -2 pointing up and two CSS pixels long.

Quick rotate vector 90deg CW

For a uniform scale and rotation (the image is always square) all we need is a single vector. For example from the above. x = 0 and y = -2 (pointing up) can be rotated 90 CW by swapping the two components and negating the new x. eg xx = -y and y = x to get xx = 2 and y = 0 2 CSS pixels from left two right. Thus we have the direction and scale of both the x and y axis. With the y axis always 90 CW from the x.

Using the transform to draw

Create rotated and scaled transform

To create a transform that rotates any angle and scales by any amount

```<code> function scaleAndRotate(scale, rotate) { // rotate is in radians
     // get direction and length of x axis
     const xAX = Math.cos(rotate) * scale;
     const xAY = Math.sin(rotate) * scale;
     // get direction and length of y axis that is 90 deg CW of x axis and same length
     const [yAX, yAY] = [-xAY, xAX];  // swap and negate new x

     // set the transform
     ctx.setTransform(xAX, xAY, yAX, yAY, 0, 0);

 }
</code>```

Drawing an image

Lets create a function that will draw an image anywhere on the canvas that is rotated and scaled uniformly. We will use the center of the image as the reference point

```<code> function drawImageScaleRotate(img, x, y, scale, rotate) {
      // define the direction and scale of x axis
      const xAX = Math.cos(rotate) * scale;
      const xAY = Math.sin(rotate) * scale;

      // create the transform with yaxis at 90 CW of x axis and origin at x, y
      ctx.setTransform(xAX, xAY, -xAY, xAX, x, y);

      // Draw the image so that its center is at the new origin x, y
      ctx.drawImage(img, -img.width / 2, -img.height / 2);

   }
</code>```

There is much more

When we set the transform with ctx.setTranform we replace the existing transform. This transform remains current. If we use ctx.transform, ctx.rotate, ctx.scale, ctx.translate the transforms are applied to the current transform, you build a transform in stages.

The transform functions are relatively expensive in terms of CPU cycles. That is way using sin and cos to build the matrix is much faster than using ctx.scale, ctx.rotate, ctx.translate to do the same thing starting from default.

Building transforms can become tricky as we need to keep track of what stage we are at.

We generally only use these function not to transform a single image (text, path, or what ever)  but to create linked transforms.

For example a game object like a tank. The body of the tank is transformed (rotated and positioned) then the turret which is rotated with the body but has an additional independent rotation by using ctx.rotate. Full explanation is beyond the scope of this question.

The final function

From all this we can create a simplified function that will draw an image with its center at any location, that is uniformly scaled and rotated

```<code> function drawImageScaleRotate(img, x, y, scale, rotate) {
      const xAX = Math.cos(rotate) * scale;
      const xAY = Math.sin(rotate) * scale;
      ctx.setTransform(xAX, xAY, -xAY, xAX, x, y);
      ctx.drawImage(img, -img.width / 2, -img.height / 2);
   }
</code>```

To reset the transform to the default use ctx.resetTransform NOTE not fully supported yet or use ctx.setTransform(1,0,0,1,0,0);

Animated transforms faster than CSS + HTML or SVG

Using the above function is the 2nd fastest way to draw animated rotated scaled images, faster than CSS + HTML or SVG. You can literally fill the screen with animated images.

Demo

var w,h;
var image = new Image;
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
document.body.appendChild(canvas);
const resize = () => { w = canvas.width = innerWidth; h = canvas.height = innerHeight;}
const rand = (min,max) => Math.random() * (max ?(max-min) : min) + (max ? min : 0);
const DO = (count,callback) => { while (count--) { callback(count) } }

resize();
addEventListener("resize",resize);

const sprites = [];
DO(500,()=>{
    sprites.push({
       xr : rand(w), yr : rand(h),
       x : 0, y : 0, // actual position of sprite
       r : rand(Math.PI * 2),
       scale : rand(0.1,0.25),
       dx : rand(-2,2), dy : rand(-2,2),
       dr : rand(-0.2,0.2),
    });
});

function drawImage(image, spr){
    const xAX = Math.cos(spr.r) * spr.scale;
    const xAY = Math.sin(spr.r) * spr.scale;
    ctx.setTransform(xAX, xAY, -xAY, xAX, spr.x, spr.y);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}

function update(){
    var ihM,iwM;
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,w,h);
    if(image.complete){
      var iw = image.width;
      var ih = image.height;
      for(var i = 0; i < sprites.length; i ++){
          var spr = sprites[i];
          spr.xr += spr.dx;
          spr.yr += spr.dy;
          spr.r += spr.dr;
          // keeps images in canvas adds space to all sides so that image
          // can move completely of the canvas befor warping to other side
          // I do this to prevent images visualy popping in and out at edges
          iwM = iw * spr.scale * 2 + w;
          ihM = ih * spr.scale * 2 + h;
          spr.x = ((spr.xr % iwM) + iwM) % iwM - iw * spr.scale;
          spr.y = ((spr.yr % ihM) + ihM) % ihM - ih * spr.scale;

          drawImage(image,spr);
      }
    }
    requestAnimationFrame(update);
}
requestAnimationFrame(update);```

If you are wondering which is the fastest way to draw animated content. That is via webGL. The above can draw 1000 scaled rotated images on most devices at a good frame rate. WebGL can easily draw 10000 (with extra features eg colored) in the same time.

Body:
2D transform basics

6 values as 3 vectors

The transform is a set of 6 numbers. The 6 numbers as 3 pairs represent the direction and scale of the x axis, the direction and scale of the y axis, and the position of the origin.

Default transform AKA Identity matrix

The default transform (called the identity matrix) has the values ctx.setTransform(1, 0, 0, 1, 0, 0) meaning that

the x axis is 1 transformed pixel per CSS pixel in the direction {x: 1, y: 0} left to right

the y axis is 1 transformed pixel per CSS pixel in the direction {x: 0, y: 1} top to bottom

the origin is at pixel location {x: 0, y: 0} top left corner

Scaling

If we scale the transform we increase the length of the first two vectors. To scale by 2 the transform is ctx.setTransform(2, 0, 0, 2, 0, 0);

the x axis is 1 transformed pixel for every 2 CSS pixel in the x direction {x: 2, y: 0} left to right

the y axis is 1 transformed pixel for every 2 CSS pixel in the y direction {x: 0, y: 2} top to bottom

the origin is still top left {x: 0, y: 0}

Rotate and translation

If we want to rotate by 90deg a square 256 by 256 image then the transform is ctx.setTransform(0, 1, -1, 0, 256, 0)

the x axis is 1 transformed pixel per CSS pixel down in the y direction {x: 0, y: 1}

the y axis is 1 transformed pixel per CSS pixel across in the negative x direction {x: -1, y: 0} right to left

the origin (where the image 0, 0 will be on the canvas) is  {x: 256, y: 0}

Thus if we run

ctx.setTransform(0, 1, -1, 0, 256, 0);
ctx.drawImage(myImage, 0, 0, 256, 256); // will draw image rotated 90deg CW

We get a rotated image.

A vector

A vector is two values that have a x and y value. The vector defines a direction and length.

Create a rotated unit vector

To convert a direction to a vector we use sin and cos

const myDirection = angle;
const myDirectionAsRadians = angle * (Math.PI / 180);  // convert angle to radians

const x = Math.cos(myDirectionAsRadians)
const y = Math.sin(myDirectionAsRadians)

If we set myDirection to 90 (deg) then x = 0 and y = 1 pointing down the canvas

Using sin and cos creates a vector in any direction. It has a special property in that its length is always 1. We call such a vector a Unit vector. You may sometimes see a vector being normalized. This converts a vector of any length to a unit vector. It is done by dividing the vector x and y by its length.

 function normalize(vector) {
     const length = Math.hypot(vector.x, vector.y);
     vector.x /= length;
     vector.y /= length;
 }

NOTE a vector with zero length eg x: 0, y:0 can not be normalized. Not because it has no length (the length is 0) but because it has no direction.

Scale a rotated vector

We can define an angle and a scale

const myDirection = -90;
const myDirectionAsRadians = -90 * (Math.PI / 180);  // -90 as radians
const myScale = 2;

const x = Math.cos(myDirectionAsRadians) * myScale
const y = Math.sin(myDirectionAsRadians) * myScale

Now for -90 deg the vector is x = 0 and y = -2 pointing up and two CSS pixels long.

Quick rotate vector 90deg CW

For a uniform scale and rotation (the image is always square) all we need is a single vector. For example from the above. x = 0 and y = -2 (pointing up) can be rotated 90 CW by swapping the two components and negating the new x. eg xx = -y and y = x to get xx = 2 and y = 0 2 CSS pixels from left two right. Thus we have the direction and scale of both the x and y axis. With the y axis always 90 CW from the x.

Using the transform to draw

Create rotated and scaled transform

To create a transform that rotates any angle and scales by any amount

 function scaleAndRotate(scale, rotate) { // rotate is in radians
     // get direction and length of x axis
     const xAX = Math.cos(rotate) * scale;
     const xAY = Math.sin(rotate) * scale;
     // get direction and length of y axis that is 90 deg CW of x axis and same length
     const [yAX, yAY] = [-xAY, xAX];  // swap and negate new x

     // set the transform
     ctx.setTransform(xAX, xAY, yAX, yAY, 0, 0);

 }

Drawing an image

Lets create a function that will draw an image anywhere on the canvas that is rotated and scaled uniformly. We will use the center of the image as the reference point

 function drawImageScaleRotate(img, x, y, scale, rotate) {
      // define the direction and scale of x axis
      const xAX = Math.cos(rotate) * scale;
      const xAY = Math.sin(rotate) * scale;

      // create the transform with yaxis at 90 CW of x axis and origin at x, y
      ctx.setTransform(xAX, xAY, -xAY, xAX, x, y);

      // Draw the image so that its center is at the new origin x, y
      ctx.drawImage(img, -img.width / 2, -img.height / 2);

   }

There is much more

When we set the transform with ctx.setTranform we replace the existing transform. This transform remains current. If we use ctx.transform, ctx.rotate, ctx.scale, ctx.translate the transforms are applied to the current transform, you build a transform in stages.

The transform functions are relatively expensive in terms of CPU cycles. That is way using sin and cos to build the matrix is much faster than using ctx.scale, ctx.rotate, ctx.translate to do the same thing starting from default.

Building transforms can become tricky as we need to keep track of what stage we are at.

We generally only use these function not to transform a single image (text, path, or what ever)  but to create linked transforms.

For example a game object like a tank. The body of the tank is transformed (rotated and positioned) then the turret which is rotated with the body but has an additional independent rotation by using ctx.rotate. Full explanation is beyond the scope of this question.

The final function

From all this we can create a simplified function that will draw an image with its center at any location, that is uniformly scaled and rotated

 function drawImageScaleRotate(img, x, y, scale, rotate) {
      const xAX = Math.cos(rotate) * scale;
      const xAY = Math.sin(rotate) * scale;
      ctx.setTransform(xAX, xAY, -xAY, xAX, x, y);
      ctx.drawImage(img, -img.width / 2, -img.height / 2);
   }

To reset the transform to the default use ctx.resetTransform NOTE not fully supported yet or use ctx.setTransform(1,0,0,1,0,0);

Animated transforms faster than CSS + HTML or SVG

Using the above function is the 2nd fastest way to draw animated rotated scaled images, faster than CSS + HTML or SVG. You can literally fill the screen with animated images.

Demo

var w,h;
var image = new Image;
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
document.body.appendChild(canvas);
const resize = () => { w = canvas.width = innerWidth; h = canvas.height = innerHeight;}
const rand = (min,max) => Math.random() * (max ?(max-min) : min) + (max ? min : 0);
const DO = (count,callback) => { while (count--) { callback(count) } }

resize();
addEventListener("resize",resize);

const sprites = [];
DO(500,()=>{
    sprites.push({
       xr : rand(w), yr : rand(h),
       x : 0, y : 0, // actual position of sprite
       r : rand(Math.PI * 2),
       scale : rand(0.1,0.25),
       dx : rand(-2,2), dy : rand(-2,2),
       dr : rand(-0.2,0.2),
    });
});

function drawImage(image, spr){
    const xAX = Math.cos(spr.r) * spr.scale;
    const xAY = Math.sin(spr.r) * spr.scale;
    ctx.setTransform(xAX, xAY, -xAY, xAX, spr.x, spr.y);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}

function update(){
    var ihM,iwM;
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,w,h);
    if(image.complete){
      var iw = image.width;
      var ih = image.height;
      for(var i = 0; i < sprites.length; i ++){
          var spr = sprites[i];
          spr.xr += spr.dx;
          spr.yr += spr.dy;
          spr.r += spr.dr;
          // keeps images in canvas adds space to all sides so that image
          // can move completely of the canvas befor warping to other side
          // I do this to prevent images visualy popping in and out at edges
          iwM = iw * spr.scale * 2 + w;
          ihM = ih * spr.scale * 2 + h;
          spr.x = ((spr.xr % iwM) + iwM) % iwM - iw * spr.scale;
          spr.y = ((spr.yr % ihM) + ihM) % ihM - ih * spr.scale;

          drawImage(image,spr);
      }
    }
    requestAnimationFrame(update);
}
requestAnimationFrame(update);

If you are wondering which is the fastest way to draw animated content. That is via webGL. The above can draw 1000 scaled rotated images on most devices at a good frame rate. WebGL can easily draw 10000 (with extra features eg colored) in the same time.


来源: stackexchange

问:
Why can't my compiler convert this?
Error:

```<code>Type mismatch: cannot convert from Set<ConstraintViolation<capture#1-of ?>> to Set<ConstraintViolation<Class<?>>>
</code>```

My code:

```<code>public class validateValue(Class<?> beanType, String propertyName, Object value, Class<?>... groups){
    TraversableResolver tr = new MyTraversableResolver();
    Validator validator = Validation.buildDefaultValidatorFactory().usingContext().traversableResolver(tr).getValidator();
    final Set<ConstraintViolation<Class<?>>> constraintViolations = validator.validateValue(beanType, propertyName, value, groups);
}

private class MyTraversableResolver  implements TraversableResolver {

    public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
      return traversableObject == null || Hibernate.isInitialized(traversableObject);
      }
      public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
          return true;
      }
  }
</code>```

答:
@JustinKSU is correct about changing the wildcard (?) to a type arg (T).  The other issue is that validator.validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) doesn't return a set of constraint violations on the type's class, which would be:

```<code>Set<ConstraintViolation<Class<T>>>
</code>```

...but rather it returns a set of constraint violations on the type:

```<code>Set<ConstraintViolation<T>>
</code>```

It's a subtle difference to see, but it's noticeable if you check the error message closely and count the angle brackets.

So, your code should be as below. I simplified the validator creation for purposes of the example. I also added a return value since I assume you want to do something with the results.

```<code>public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    final Set<ConstraintViolation<T>> constraintViolations = validator.validateValue(beanType, propertyName, value, groups);
    return constraintViolations;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why can't my compiler convert this?

Body:
Error:

Type mismatch: cannot convert from Set<ConstraintViolation<capture#1-of ?>> to Set<ConstraintViolation<Class<?>>>

My code:

public class validateValue(Class<?> beanType, String propertyName, Object value, Class<?>... groups){
    TraversableResolver tr = new MyTraversableResolver();
    Validator validator = Validation.buildDefaultValidatorFactory().usingContext().traversableResolver(tr).getValidator();
    final Set<ConstraintViolation<Class<?>>> constraintViolations = validator.validateValue(beanType, propertyName, value, groups);
}

private class MyTraversableResolver  implements TraversableResolver {

    public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
      return traversableObject == null || Hibernate.isInitialized(traversableObject);
      }
      public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
          return true;
      }
  }

Body:
@JustinKSU is correct about changing the wildcard (?) to a type arg (T).  The other issue is that validator.validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) doesn't return a set of constraint violations on the type's class, which would be:

Set<ConstraintViolation<Class<T>>>

...but rather it returns a set of constraint violations on the type:

Set<ConstraintViolation<T>>

It's a subtle difference to see, but it's noticeable if you check the error message closely and count the angle brackets.

So, your code should be as below. I simplified the validator creation for purposes of the example. I also added a return value since I assume you want to do something with the results.

public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    final Set<ConstraintViolation<T>> constraintViolations = validator.validateValue(beanType, propertyName, value, groups);
    return constraintViolations;
}


问:
Class for easy generation of xpaths
I would like to write a class for generating xpaths. The class should have 2 methods: down(String string) and child(String string).

I would like to use the class like that:

```<code>XpathBuilder.child("div").down("button").child("a").child("span")

//That should return a String: div//button/a/span
</code>```

Could anybody suggest me how can I do that?

答:
You could take a look at builder pattern.

Here is one example (uses internal builder class):

```<code>public class XpathBuilder {

    public Builder builder() {
        return new XpathBuilder.Builder();
    }

    class Builder {

        private final StringBuilder sb;

        Builder() {
            sb = new StringBuilder();
        }

        public Builder child(String name) {
            sb.append("/").append(name);
            return this;
        }

        public Builder down(String name) {
            sb.append("//").append(name);
            return this;
        }

        public String build() {
            return sb.toString();
        }
    }
}
</code>```

It can be called like this:

```<code>String path = new XpathBuilder().builder().child("div").down("button").child("a").child("span").build();
</code>```

Here is another example (uses builder as well as singleton pattern):

```<code>public class XpathBuilder {

    private final StringBuilder sb;

    private static XpathBuilder instance;

    private XpathBuilder() {
        sb = new StringBuilder();
    }

    public static XpathBuilder newInstance() {
        if (instance == null) {
            instance = new XpathBuilder();
        }
        return instance;
    }

    public XpathBuilder child(String name) {
        sb.append("/").append(name);
        return this;
    }

    public XpathBuilder down(String name) {
        sb.append("//").append(name);
        return this;
    }

    public String build() {
        return sb.toString();
    }

}
</code>```

It can be called like this:

```<code>String path = XpathBuilder.newInstance().child("div").down("button").child("a").child("span").build();
</code>```

ContentLicense: CC BY-SA 4.0

Title: Class for easy generation of xpaths

Body:
I would like to write a class for generating xpaths. The class should have 2 methods: down(String string) and child(String string).

I would like to use the class like that:

XpathBuilder.child("div").down("button").child("a").child("span")

//That should return a String: div//button/a/span

Could anybody suggest me how can I do that?

Body:
You could take a look at builder pattern.

Here is one example (uses internal builder class):

public class XpathBuilder {

    public Builder builder() {
        return new XpathBuilder.Builder();
    }

    class Builder {

        private final StringBuilder sb;

        Builder() {
            sb = new StringBuilder();
        }

        public Builder child(String name) {
            sb.append("/").append(name);
            return this;
        }

        public Builder down(String name) {
            sb.append("//").append(name);
            return this;
        }

        public String build() {
            return sb.toString();
        }
    }
}

It can be called like this:

String path = new XpathBuilder().builder().child("div").down("button").child("a").child("span").build();

Here is another example (uses builder as well as singleton pattern):

public class XpathBuilder {

    private final StringBuilder sb;

    private static XpathBuilder instance;

    private XpathBuilder() {
        sb = new StringBuilder();
    }

    public static XpathBuilder newInstance() {
        if (instance == null) {
            instance = new XpathBuilder();
        }
        return instance;
    }

    public XpathBuilder child(String name) {
        sb.append("/").append(name);
        return this;
    }

    public XpathBuilder down(String name) {
        sb.append("//").append(name);
        return this;
    }

    public String build() {
        return sb.toString();
    }

}

It can be called like this:

String path = XpathBuilder.newInstance().child("div").down("button").child("a").child("span").build();


问:
Value just available after second function call
I have the following function and it's working great but now I need the value out of the function to use it for another purpose.
But my problem is that I always have to execute the function twice to get a value in the outer part of the function (var valueOutOfFunction).

```<code>var valueOutOfFunction = [(String)]()
func loadQuery(com:@escaping( [(Int, String)] -> ())){
    var arrayOfTuples = [(Int, String)]()
    db.collection("Data").whereField("age", isGreaterThanOrEqualTo: 1).whereField("age", isLessThanOrEqualTo: 50).whereField("gender", isEqualTo: "F").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
                 for (index, document) in querySnapshot!.documents.enumerated() {
                 arrayOfTuples += [(index, document.documentID)]
                 }
        }
        com(arrayOfTuples)
    }
}
</code>```

Then I am calling it here:

```<code>loadQuery { arr in
  self.valueOutOfFunction = arr // Has a value in the first execution
}

print (valueOutOfFunction) //Executing the first time there is no value in the variable, the second time it have a value.
</code>```

Why is it just on the second attempt available and what could be a solution for this problem ?
Thanks!

答:
That is because the valueOutOfFunction is happening inside of that closure which is being called asynchronously to the print statement. Additionally, you are executing the completion outside of the else statement which may be firing before your for loop completes. What you want to do is control the flow from within the closure itself like so:

// move com(arrayOfTuples) up into the else block but outside of the for loop

func handleQuery() {
    loadQuery { doStuffWithResult($0) }
    // This line will run before the first line of doStuffWithResult
    // It would be best to end the function logic at loadQuery
}

func doStuffWithResult(_ arrayOfTuples: [(Int, String)]) {
    print(arrayOfTuples)
    // Do other work here
}
```

<p>What you're looking into is control flow. You want to execute <code>X if Y</code> has occurred and <code>Z if !Y</code> right? </p>

<p>I would recommend looking into swift's result type. This will help you manage control flow with closures.</p>

<p>An example:</p>

<pre class="lang-swift prettyprint-override"><code>typealias QueryResult = [(Int, String)]

enum QueryErrors: Error {
    case couldNotFind
}

func loadQuery(_ result: @escaping (Result<QueryResult, Error>) -> Void) {
    db.collection("Data").whereField("age", isGreaterThanOrEqualTo: 1).whereField("age", isLessThanOrEqualTo: 50).whereField("gender", isEqualTo: "F").getDocuments() { (querySnapshot, err) in
        guard let documents = querySnapshot?.documents.enumerated() else {
            // I think enumerated will give you an array of tuples... if not add this to the end of that line. After enumerated but before else
            // enumerated().compactMap { ($0, $1) }
            result(.failure(err ?? QueryErrors.couldNotFind))// passes back Firebase error if it exists or default error if it doesn't
            return
        }
            result(.success(documents))
    }
}

// how it works

loadQuery() { result in
    switch(result) {
    case .success(let arr): print(arr)
    case .failure(let error): print(error)
    }
}
</code>```

Body:
I have the following function and it's working great but now I need the value out of the function to use it for another purpose.
But my problem is that I always have to execute the function twice to get a value in the outer part of the function (var valueOutOfFunction).

var valueOutOfFunction = [(String)]()
func loadQuery(com:@escaping( [(Int, String)] -> ())){
    var arrayOfTuples = [(Int, String)]()
    db.collection("Data").whereField("age", isGreaterThanOrEqualTo: 1).whereField("age", isLessThanOrEqualTo: 50).whereField("gender", isEqualTo: "F").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
                 for (index, document) in querySnapshot!.documents.enumerated() {
                 arrayOfTuples += [(index, document.documentID)]
                 }
        }
        com(arrayOfTuples)
    }
}

Then I am calling it here:

loadQuery { arr in
  self.valueOutOfFunction = arr // Has a value in the first execution
}

print (valueOutOfFunction) //Executing the first time there is no value in the variable, the second time it have a value.

Why is it just on the second attempt available and what could be a solution for this problem ?
Thanks!

Body:
That is because the valueOutOfFunction is happening inside of that closure which is being called asynchronously to the print statement. Additionally, you are executing the completion outside of the else statement which may be firing before your for loop completes. What you want to do is control the flow from within the closure itself like so:

// move com(arrayOfTuples) up into the else block but outside of the for loop

func handleQuery() {
    loadQuery { doStuffWithResult($0) }
    // This line will run before the first line of doStuffWithResult
    // It would be best to end the function logic at loadQuery
}

func doStuffWithResult(_ arrayOfTuples: [(Int, String)]) {
    print(arrayOfTuples)
    // Do other work here
}

What you're looking into is control flow. You want to execute X if Y has occurred and Z if !Y right?

I would recommend looking into swift's result type. This will help you manage control flow with closures.

An example:

typealias QueryResult = [(Int, String)]

enum QueryErrors: Error {
    case couldNotFind
}

func loadQuery(_ result: @escaping (Result<QueryResult, Error>) -> Void) {
    db.collection("Data").whereField("age", isGreaterThanOrEqualTo: 1).whereField("age", isLessThanOrEqualTo: 50).whereField("gender", isEqualTo: "F").getDocuments() { (querySnapshot, err) in
        guard let documents = querySnapshot?.documents.enumerated() else {
            // I think enumerated will give you an array of tuples... if not add this to the end of that line. After enumerated but before else
            // enumerated().compactMap { ($0, $1) }
            result(.failure(err ?? QueryErrors.couldNotFind))// passes back Firebase error if it exists or default error if it doesn't
            return
        }
            result(.success(documents))
    }
}

// how it works

loadQuery() { result in
    switch(result) {
    case .success(let arr): print(arr)
    case .failure(let error): print(error)
    }
}


问:
sum all repetitious column in mysql
hello i have a table in mysql and i want to sum a multi records from this table when have repetitious data in another column.
for example
i have this table with this data:

table name = register_user_course
columns = register_user_course_id, register_user_register_id, register_user_course_name, register_user_course_price

data like =

1 | 3 | 3dmax | 300
2 | 3 | photoshop | 500
4 | 4 | 3dmax | 300
5 | 6 | icdl | 500
6 | 4 | icdl | 900
7 | 9 | accounting | 1000

```

<p>and i want to create to code that output like this</p>

<pre class="lang-sql prettyprint-override"><code>1 | 3 | 800 // sum all register_course_price with the same register_user_register_name on aoutput one records
4 | 4 | 1200 // sum all register_course_price with the same register_user_register_name on aoutput one records
5 | 6 | 500
7 | 9 | 1000
</code>```

lets I have another table like this

table name = deposit
columns = deposit_id, deposit_abutment_id, deposit_price

table data  like=
1 | 13 | 0,10,50,0,0 // every comma sign has one way to get money
2 | 13 | 10,30,0,0,0
3 | 13 | 100,0,0,0,0
4 | 15 | 50,0,0,0,50
5 | 17 | 100,10,5,0,0
6 | 15 | 33,50,0,0,0
```

<p>and i want to also show like this</p>

<pre class="lang-sql prettyprint-override"><code>1 | 13 | 200 // sum all way and all deposit that one abutment_user_id
4 | 15 | 183
5 | 17 | 115
</code>```

答:
You seem to want aggregation:

```<code>select
    min(register_user_course_id) register_user_course_id,
    register_user_register_id,
    sum(register_user_course_price) register_user_course_price
from register_user_course
group by register_user_register_id
</code>```

Side note: there is no point prefixing the column names with the table name: this makes the column names much longer, without any obvious benefit: register_user_course_id should be called id, register_user_course_price should be just price, and so on.

Title: sum all repetitious column in mysql

Body:
hello i have a table in mysql and i want to sum a multi records from this table when have repetitious data in another column.
for example
i have this table with this data:

table name = register_user_course
columns = register_user_course_id, register_user_register_id, register_user_course_name, register_user_course_price

data like =

1 | 3 | 3dmax | 300
2 | 3 | photoshop | 500
4 | 4 | 3dmax | 300
5 | 6 | icdl | 500
6 | 4 | icdl | 900
7 | 9 | accounting | 1000

and i want to create to code that output like this

1 | 3 | 800 // sum all register_course_price with the same register_user_register_name on aoutput one records
4 | 4 | 1200 // sum all register_course_price with the same register_user_register_name on aoutput one records
5 | 6 | 500
7 | 9 | 1000

lets I have another table like this

table name = deposit
columns = deposit_id, deposit_abutment_id, deposit_price

table data  like=
1 | 13 | 0,10,50,0,0 // every comma sign has one way to get money
2 | 13 | 10,30,0,0,0
3 | 13 | 100,0,0,0,0
4 | 15 | 50,0,0,0,50
5 | 17 | 100,10,5,0,0
6 | 15 | 33,50,0,0,0

and i want to also show like this

1 | 13 | 200 // sum all way and all deposit that one abutment_user_id
4 | 15 | 183
5 | 17 | 115

Body:
You seem to want aggregation:

select
    min(register_user_course_id) register_user_course_id,
    register_user_register_id,
    sum(register_user_course_price) register_user_course_price
from register_user_course
group by register_user_register_id

Side note: there is no point prefixing the column names with the table name: this makes the column names much longer, without any obvious benefit: register_user_course_id should be called id, register_user_course_price should be just price, and so on.


问:
How can I access <Image Name="AddImg"/> from Code in WPF?
I have created an Image in XAML and I would like to access it from code to modify the Source dynamically. I could not access so far. Is there any solution?

```<code><Window x:Class="DDSV2.MasterMain"
    Name="MainWw"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DDSV2"
    mc:Ignorable="d"
    Title="MasterMain" Height="1123.439" Width="1822.363" Loaded="Window_Loaded">
<Grid Name="MainGrid">
    <ListView x:Name="MainMasterLv" Height="333" Margin="10,10,1494,0" VerticalAlignment="Top" SelectionChanged="MainMasterLv_SelectionChanged">
        <ListView.View>
            <GridView x:Name="GridVw">
                <GridViewColumn x:Name="DataGridCn"  Header="">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate x:Name="DataTmp">
                            <StackPanel Orientation="Horizontal">
                                <Image x:Name="AddImg" Source="pack://application:,,,/Resources        /gears.png" MaxWidth="80" MaxHeight="80" Margin="3,3,3,3"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

</Grid>
</code>```

答:
You can use xml methods like xml linq :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement image = doc.Descendants().Where(x => x.Name.LocalName == "Image").FirstOrDefault();
            XNamespace nsN = image.GetNamespaceOfPrefix("x");
            XAttribute name = image.Attribute(nsN + "Name");
            name.SetValue("newName");
        }
    }
}
</code>```

Body:
I have created an Image in XAML and I would like to access it from code to modify the Source dynamically. I could not access so far. Is there any solution?

<Window x:Class="DDSV2.MasterMain"
    Name="MainWw"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DDSV2"
    mc:Ignorable="d"
    Title="MasterMain" Height="1123.439" Width="1822.363" Loaded="Window_Loaded">
<Grid Name="MainGrid">
    <ListView x:Name="MainMasterLv" Height="333" Margin="10,10,1494,0" VerticalAlignment="Top" SelectionChanged="MainMasterLv_SelectionChanged">
        <ListView.View>
            <GridView x:Name="GridVw">
                <GridViewColumn x:Name="DataGridCn"  Header="">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate x:Name="DataTmp">
                            <StackPanel Orientation="Horizontal">
                                <Image x:Name="AddImg" Source="pack://application:,,,/Resources        /gears.png" MaxWidth="80" MaxHeight="80" Margin="3,3,3,3"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

</Grid>

Body:
You can use xml methods like xml linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement image = doc.Descendants().Where(x => x.Name.LocalName == "Image").FirstOrDefault();
            XNamespace nsN = image.GetNamespaceOfPrefix("x");
            XAttribute name = image.Attribute(nsN + "Name");
            name.SetValue("newName");
        }
    }
}


问:
how to check function is called or not after http post call?
I am trying to test my one function in which there is a http post request ,after success it call a function I want to check it function is called or not after success.

here is my code
https://codesandbox.io/s/ecstatic-currying-5q1b8
I am testing below function

```<code>export const saveWithoutSubmit = async (values, updateTaskListAfterFilter) => {
  var obj = {
    remarks: values.remarks,
    requestedBy: localStorage.getItem("msisdn")
  };
  try {
    const response = await sendPostRequest(`${API_TASK_URL}closeSr`, {
      ...obj,
      saveWithoutSubmit: true
    });

    if (response && response.data && response.data.status.code !== "200") {
      error(response.data.result.message);
    } else {
      console.log(response);
      success(response.data.status.message);
      updateTaskListAfterFilter();
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
      error(e.response.data.status.message);
    }
  }
};
</code>```

I am doing testing like this

```<code>describe("remark service test", () => {
  const fakeAxios = {
    post: jest.fn(() => Promise.resolve({ data: { greeting: "hello there" } }))
  };

  const sendPostRequest = jest.fn(() =>
    Promise.resolve({ data: { greeting: "hello there" } })
  );
  it("save without sumit", async done => {
    const mockUpdateTaskListAfterFilter = jest.fn();
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, mockUpdateTaskListAfterFilter);

    // expect(updateTaskListAfterFilter).toBeCalled();
    expect(mockUpdateTaskListAfterFilter).toBeCalled();
    done();
  });
});
</code>```

getting error

答:
Why not just put a variable in the normal arrow function and await saveWithoutSubmit

remark.service.js

const sendPostRequest = () => {
  return Promise.resolve({
    data: {
      greeting: "hello there",
      status: {
        code: "200"
      }
    }
  });
};

export const saveWithoutSubmit = async(values, updateTaskListAfterFilter) => {
  try {
    const response = await sendPostRequest();
    if (response && response.data && response.data.status.code !== "200") {
      console.log("Error");
      return;
    } else {
      console.log("Sucess");
      updateTaskListAfterFilter();
      return;
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
    }
  }
};
```

<p><strong>remark.service.test.js</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
  saveWithoutSubmit
} from "./remark.service";

describe("remark service test", () => {
  it("save without sumit", async function() {
    console.log("save without sumit getting called");
    let called = false;
    const mockUpdateTaskListAfterFilter = () => {
      console.log("callback");
      called = true;
    };

    await saveWithoutSubmit({}, mockUpdateTaskListAfterFilter);
    console.log("after saveWithoutSubmit", called);
    expect(called).toBe(true);
  });
});</code>```

Body:
I am trying to test my one function in which there is a http post request ,after success it call a function I want to check it function is called or not after success.

here is my code
https://codesandbox.io/s/ecstatic-currying-5q1b8
I am testing below function

export const saveWithoutSubmit = async (values, updateTaskListAfterFilter) => {
  var obj = {
    remarks: values.remarks,
    requestedBy: localStorage.getItem("msisdn")
  };
  try {
    const response = await sendPostRequest(`${API_TASK_URL}closeSr`, {
      ...obj,
      saveWithoutSubmit: true
    });

    if (response && response.data && response.data.status.code !== "200") {
      error(response.data.result.message);
    } else {
      console.log(response);
      success(response.data.status.message);
      updateTaskListAfterFilter();
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
      error(e.response.data.status.message);
    }
  }
};

I am doing testing like this

describe("remark service test", () => {
  const fakeAxios = {
    post: jest.fn(() => Promise.resolve({ data: { greeting: "hello there" } }))
  };

  const sendPostRequest = jest.fn(() =>
    Promise.resolve({ data: { greeting: "hello there" } })
  );
  it("save without sumit", async done => {
    const mockUpdateTaskListAfterFilter = jest.fn();
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, mockUpdateTaskListAfterFilter);

    // expect(updateTaskListAfterFilter).toBeCalled();
    expect(mockUpdateTaskListAfterFilter).toBeCalled();
    done();
  });
});

getting error

Body:
Why not just put a variable in the normal arrow function and await saveWithoutSubmit

remark.service.js

const sendPostRequest = () => {
  return Promise.resolve({
    data: {
      greeting: "hello there",
      status: {
        code: "200"
      }
    }
  });
};

export const saveWithoutSubmit = async(values, updateTaskListAfterFilter) => {
  try {
    const response = await sendPostRequest();
    if (response && response.data && response.data.status.code !== "200") {
      console.log("Error");
      return;
    } else {
      console.log("Sucess");
      updateTaskListAfterFilter();
      return;
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
    }
  }
};

remark.service.test.js

import {
  saveWithoutSubmit
} from "./remark.service";

describe("remark service test", () => {
  it("save without sumit", async function() {
    console.log("save without sumit getting called");
    let called = false;
    const mockUpdateTaskListAfterFilter = () => {
      console.log("callback");
      called = true;
    };

    await saveWithoutSubmit({}, mockUpdateTaskListAfterFilter);
    console.log("after saveWithoutSubmit", called);
    expect(called).toBe(true);
  });
});


问:
How to import Eviews data into pandas
I am unfortunately only given datasets for my time series course as an Eviews wf1 file. How can I import this into pandas? I cannot find an answer in pandas online documentation.</p>

答:
A work-around solution I have just found is to:
(1) Download gretl, an open-source econometrics software, see http://gretl.sourceforge.net

(2) open the Eviews file into Gretl

(3) export from Gretl as csv.

Title: How to import Eviews data into pandas


问:
How to deploy frontend and backend at the same time to App Engine?
Currently, I have two different packages - a WAR file with my Java web application (APIs, etc) and an Angular 8 dist zip file. I want to either deploy both to the same app engine instance or to separate app engine instances.

How do I deploy both of them to the same app engine instance and have them still be integrated?

Is it a good practice to deploy both of them to the same instance or should you have it separate?

If I deploy them to separate instances - how would I point one to the other and avoid CORS issues?

答:
I don't recommend you to deploy both on the same instance. Why? Because, if you want to update your front, for example, update a CSS or a type issue, you have to redeploy your full app only for this.

By the way I recommend you to deploy 2 different instances. The front on the frontend name instances, and the back on default backend instance.

You have to customize the app.yaml file. For the front end, for serving only static files, I use this file

```<code>service: frontend
runtime: python37

handlers:
# Routing for bundles to serve directly
- url: /((?:(?:(?:inline|main|runtime|common|polyfills|styles|vendor)\.[a-z0-9]+\.js)|(?:[0-9]+\.[a-z0-9]+\.js)))
  secure: always
  redirect_http_response_code: 301
  static_files: dist/\1
  upload: dist/.*

# Routing for a prod styles.bundle.css to serve directly
- url: /(styles\.[a-z0-9]+\.css)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/\1
  upload: dist/.*

# Routing for typedoc, assets and favicon.ico to serve directly
- url: /((?:assets|docs)/.*|favicon\.ico)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/\1
  upload: dist/.*

# Any other requests are routed to index.html for angular to handle so we don't need hash URLs
- url: /.*
  secure: always
  redirect_http_response_code: 301
  static_files: dist/index.html
  upload: dist/index\.html
  expiration: 0s
  http_headers:
    Strict-Transport-Security: max-age=31536000; includeSubDomains
    X-Frame-Options: DENY

</code>```

Only static resourced are served in the /static directory. No instance spawn, no cost.

Note: It was also an angular App and I use python runtime in the file. No impact, use what you want, it's only static resources served!

The backed is standard and specific to your app. if you set correctly your handlers, you shouldn't have cors issue.

Let me know if it's not the case, we will review your configuration.

Body:
I don't recommend you to deploy both on the same instance. Why? Because, if you want to update your front, for example, update a CSS or a type issue, you have to redeploy your full app only for this.

By the way I recommend you to deploy 2 different instances. The front on the frontend name instances, and the back on default backend instance.

You have to customize the app.yaml file. For the front end, for serving only static files, I use this file

service: frontend
runtime: python37

handlers:
# Routing for bundles to serve directly
- url: /((?:(?:(?:inline|main|runtime|common|polyfills|styles|vendor)\.[a-z0-9]+\.js)|(?:[0-9]+\.[a-z0-9]+\.js)))
  secure: always
  redirect_http_response_code: 301
  static_files: dist/\1
  upload: dist/.*

# Routing for a prod styles.bundle.css to serve directly
- url: /(styles\.[a-z0-9]+\.css)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/\1
  upload: dist/.*

# Routing for typedoc, assets and favicon.ico to serve directly
- url: /((?:assets|docs)/.*|favicon\.ico)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/\1
  upload: dist/.*

# Any other requests are routed to index.html for angular to handle so we don't need hash URLs
- url: /.*
  secure: always
  redirect_http_response_code: 301
  static_files: dist/index.html
  upload: dist/index\.html
  expiration: 0s
  http_headers:
    Strict-Transport-Security: max-age=31536000; includeSubDomains
    X-Frame-Options: DENY

Only static resourced are served in the /static directory. No instance spawn, no cost.

Note: It was also an angular App and I use python runtime in the file. No impact, use what you want, it's only static resources served!

The backed is standard and specific to your app. if you set correctly your handlers, you shouldn't have cors issue.

Let me know if it's not the case, we will review your configuration.


问:
How to set React-Particles-Js to background using React?
I am learning React and having some issues setting React-Particles-Js (https://www.npmjs.com/package/react-particles-js) to be the background of my website.

If I only render

```<code>  class App extends Component {
  render() {
    return (
      <div>
      <Particles />
      </div>

    );
  }
}
</code>```

I get the background just as I wish it to be. However, as soon as I render anything else (for example an h1 tag), it is not displayed on react-particles-js, so to say, but instead it moves react-particles-js and is displayed separately.

For example, if I render

```<code> class App extends Component {
      render() {
        return (
          <div>
          <h1>Hello World</h1>
          <h1>Hello World</h1>
          <h1>Hello World</h1>
          <Particles />

          </div>

        );
      }
    }

    export default App;
</code>```

what happens is that "Hello World" is displayed three times in the top left hand corner of the screen and Particles is displayed below it, meaning that Particles is interpreted as just another element on the same layer as h1 (as if it was another h1 tag) rather than as a background element that underlies all elements--whether they are h1 tags, cards, or navs or anything else--which is what I'd like it to be!

This is my Particles.js

```<code>import React, { Component } from 'react';
import Particles from 'react-particles-js';

var style = {
    width: "100vw",
    height: "100vh",
};

class ParticlesBackground extends Component {

    render() {
        return (
            <div style={style}>
            <Particles
                params={{
                    "particles": {
                    "number": {
                    "value": 90
                    },
                    "size": {
                    "value": 2.5
                    }
                },
                    "interactivity": {
                    "events": {
                    "onhover": {
                    "enable": true,
                    "mode": "repulse"
                    }
                    }
                    }
                }}/>
            </div>
            )
    }
}

export default ParticlesBackground;
</code>```

This is my App.js

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Nav from './Nav'
import MainArea from './MainArea';
import Particles from './Particles';
import PeopleCard from './PeopleCard'

class App extends Component {
  render() {
    return (
      <div>
      <h1>Hello World</h1>
      <h1>Hello World</h1>
      <h1>Hello World</h1>
      <Particles />

      </div>

    );
  }
}

export default App;
</code>```

And this is what I see
enter image description here
As you can see, the particles and the tags seem to be interpreted as being mutually exclusive.

(PS, I set the body tag in my html.index to have the background color #e74c3c, which is the red-ish you see as the background)

Any advice on how I could fix this?

答:
hope this will help you</p>

```<code>import Particles from 'react-particles-js';
  class App extends Component {
  render() {
    return (
      <div className="App">

         <Particles className="particles"
         params={particlesOptions}/>
        <div
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            width: "100%",
            height: "100%"
          }}
        >
        <Header Data={Data}/>
      </div>
      </div>
    );
  }
}

export default App;
</code>```

Body:
I am learning React and having some issues setting React-Particles-Js (https://www.npmjs.com/package/react-particles-js) to be the background of my website.

If I only render

  class App extends Component {
  render() {
    return (

      <Particles />

    );
  }
}

I get the background just as I wish it to be. However, as soon as I render anything else (for example an h1 tag), it is not displayed on react-particles-js, so to say, but instead it moves react-particles-js and is displayed separately.

For example, if I render

 class App extends Component {
      render() {
        return (

Hello World

Hello World

Hello World

          <Particles />

        );
      }
    }

    export default App;

what happens is that "Hello World" is displayed three times in the top left hand corner of the screen and Particles is displayed below it, meaning that Particles is interpreted as just another element on the same layer as h1 (as if it was another h1 tag) rather than as a background element that underlies all elements--whether they are h1 tags, cards, or navs or anything else--which is what I'd like it to be!

This is my Particles.js

import React, { Component } from 'react';
import Particles from 'react-particles-js';

var style = {
    width: "100vw",
    height: "100vh",
};

class ParticlesBackground extends Component {

    render() {
        return (

            <Particles
                params={{
                    "particles": {
                    "number": {
                    "value": 90
                    },
                    "size": {
                    "value": 2.5
                    }
                },
                    "interactivity": {
                    "events": {
                    "onhover": {
                    "enable": true,
                    "mode": "repulse"
                    }
                    }
                    }
                }}/>

            )
    }
}

export default ParticlesBackground;

This is my App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Nav from './Nav'
import MainArea from './MainArea';
import Particles from './Particles';
import PeopleCard from './PeopleCard'

class App extends Component {
  render() {
    return (

Hello World

Hello World

Hello World

      <Particles />

    );
  }
}

export default App;

And this is what I see
enter image description here
As you can see, the particles and the tags seem to be interpreted as being mutually exclusive.

(PS, I set the body tag in my html.index to have the background color #e74c3c, which is the red-ish you see as the background)

Any advice on how I could fix this?

Body:
hope this will help you

import Particles from 'react-particles-js';
  class App extends Component {
  render() {
    return (
      <div className="App">

         <Particles className="particles"
         params={particlesOptions}/>
        <div
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            width: "100%",
            height: "100%"
          }}
        >
        <Header Data={Data}/>
      </div>
      </div>
    );
  }
}

export default App;


问:
etsy-api-oauth1 PUT Requests return invalid signature when made from python, but not from Postman
I've been troubleshooting an issue when sending a PUT Request to the ETSY REST API,
when I make a PUT request, I get a signature invalid error. I have tried all the solutions found on google, but none seem to work.

Sending the same request through POSTMAN works, if I specify the auth parameters to go in the body. However when I try to replicate this using python's standard procedures I get the same invalid signature error.

Even if I export the python code for that exact request from postman, I get a signature invalid error when running said code in python.

This is the json data I need to send:

```<code>"products": [
      {
         "product_id":4262200422,
         "sku":"00100012",
         "property_values":[
            {
               "property_id":200,
               "property_name":"Primary color",
               "scale_id":null,
               "scale_name":null,
               "values":[
                  "Black"
               ],
               "value_ids":[
                  1
               ]
            }
         ],
         "offerings":[
            {
               "offering_id":4128359213,
               "price":{
                  "amount":200,
                  "divisor":100,
                  "currency_code":"GBP",
                  "currency_formatted_short":"\\u00a32.00",
                  "currency_formatted_long":"\\u00a32.00 GBP",
                  "currency_formatted_raw":"2.00"
               },
               "quantity":12,
               "is_enabled":1,
               "is_deleted":0
            }
         ],
         "is_deleted":0
      },
      {
         "product_id":4031391357,
         "sku":"00100013",
         "property_values":[
            {
               "property_id":200,
               "property_name":"Primary color",
               "scale_id":null,
               "scale_name":null,
               "values":[
                  "Bronze"
               ],
               "value_ids":[
                  1216
               ]
            }
         ],
         "offerings":[
            {
               "offering_id":4244423138,
               "price":{
                  "amount":300,
                  "divisor":100,
                  "currency_code":"GBP",
                  "currency_formatted_short":"\\u00a33.00",
                  "currency_formatted_long":"\\u00a33.00 GBP",
                  "currency_formatted_raw":"3.00"
               },
               "quantity":56,
               "is_enabled":1,
               "is_deleted":0
            }
         ],
         "is_deleted":0
      }
   ],
"price_on_property": [200],
"quantity_on_property": [200],
"sku_on_property": [200]
</code>```

Etsy is using Oauth1, POST and GET requests work fine in Python, but don't work in POSTMAN, returning an invalid signature error.

Maybe they are doing something differently that causes this behaviour?

I need to build a request that simply takes product data, oauth1 details, and sends it to Etsy.
Please let me know what I'm missing.

答:
I managed to get it working... turns out you aren't supposed to include the actual oauth parameters in the signature calculations.

This is the code I used to make a PUT request --- Class Definition.

```<code>class etsyClient:
def __init__(self, consumer_key, consumer_secret, resource_owner_key,
                                                  resource_owner_secret):
    self.consumer_key = consumer_key
    self.consumer_secret = consumer_secret
    self.resource_owner_key = resource_owner_key
    self.resource_owner_secret = resource_owner_secret

    self.oauthclient = self.regen()

def regen(self, sig=oauth1.SIGNATURE_HMAC_SHA1):
    client = oauth1.Client(self.consumer_key,
                           client_secret=self.consumer_secret,
                           resource_owner_key=self.resource_owner_key,
                           resource_owner_secret=self.resource_owner_secret,
                           signature_method=sig)
    return client
</code>```

Actual request code:

```<code>    uri, headers, body = self.client.regen(sig=oauth1.SIGNATURE_PLAINTEXT).sign(
        f"https://openapi.etsy.com/v2/listings/{self.product.listing.id}/inventory")

    r = requests.session()
    headers["Content-Type"] = "application/x-www-form-urlencoded"
    data = {
            "listing_id": self.product.listing.id,
            "products": json.dumps(products),
            'price_on_property': [200],
            'quantity_on_property': [200],
            'sku_on_property': [200]
    }
    a = r.put(uri, headers=headers, data=data)
</code>```

Body:
I've been troubleshooting an issue when sending a PUT Request to the ETSY REST API,
when I make a PUT request, I get a signature invalid error. I have tried all the solutions found on google, but none seem to work.

Sending the same request through POSTMAN works, if I specify the auth parameters to go in the body. However when I try to replicate this using python's standard procedures I get the same invalid signature error.

Even if I export the python code for that exact request from postman, I get a signature invalid error when running said code in python.

This is the json data I need to send:

"products": [
      {
         "product_id":4262200422,
         "sku":"00100012",
         "property_values":[
            {
               "property_id":200,
               "property_name":"Primary color",
               "scale_id":null,
               "scale_name":null,
               "values":[
                  "Black"
               ],
               "value_ids":[
                  1
               ]
            }
         ],
         "offerings":[
            {
               "offering_id":4128359213,
               "price":{
                  "amount":200,
                  "divisor":100,
                  "currency_code":"GBP",
                  "currency_formatted_short":"\\u00a32.00",
                  "currency_formatted_long":"\\u00a32.00 GBP",
                  "currency_formatted_raw":"2.00"
               },
               "quantity":12,
               "is_enabled":1,
               "is_deleted":0
            }
         ],
         "is_deleted":0
      },
      {
         "product_id":4031391357,
         "sku":"00100013",
         "property_values":[
            {
               "property_id":200,
               "property_name":"Primary color",
               "scale_id":null,
               "scale_name":null,
               "values":[
                  "Bronze"
               ],
               "value_ids":[
                  1216
               ]
            }
         ],
         "offerings":[
            {
               "offering_id":4244423138,
               "price":{
                  "amount":300,
                  "divisor":100,
                  "currency_code":"GBP",
                  "currency_formatted_short":"\\u00a33.00",
                  "currency_formatted_long":"\\u00a33.00 GBP",
                  "currency_formatted_raw":"3.00"
               },
               "quantity":56,
               "is_enabled":1,
               "is_deleted":0
            }
         ],
         "is_deleted":0
      }
   ],
"price_on_property": [200],
"quantity_on_property": [200],
"sku_on_property": [200]

Etsy is using Oauth1, POST and GET requests work fine in Python, but don't work in POSTMAN, returning an invalid signature error.

Maybe they are doing something differently that causes this behaviour?

I need to build a request that simply takes product data, oauth1 details, and sends it to Etsy.
Please let me know what I'm missing.

Body:
I managed to get it working... turns out you aren't supposed to include the actual oauth parameters in the signature calculations.

This is the code I used to make a PUT request --- Class Definition.

class etsyClient:
def __init__(self, consumer_key, consumer_secret, resource_owner_key,
                                                  resource_owner_secret):
    self.consumer_key = consumer_key
    self.consumer_secret = consumer_secret
    self.resource_owner_key = resource_owner_key
    self.resource_owner_secret = resource_owner_secret

    self.oauthclient = self.regen()

def regen(self, sig=oauth1.SIGNATURE_HMAC_SHA1):
    client = oauth1.Client(self.consumer_key,
                           client_secret=self.consumer_secret,
                           resource_owner_key=self.resource_owner_key,
                           resource_owner_secret=self.resource_owner_secret,
                           signature_method=sig)
    return client

Actual request code:

    uri, headers, body = self.client.regen(sig=oauth1.SIGNATURE_PLAINTEXT).sign(
        f"https://openapi.etsy.com/v2/listings/{self.product.listing.id}/inventory")

    r = requests.session()
    headers["Content-Type"] = "application/x-www-form-urlencoded"
    data = {
            "listing_id": self.product.listing.id,
            "products": json.dumps(products),
            'price_on_property': [200],
            'quantity_on_property': [200],
            'sku_on_property': [200]
    }
    a = r.put(uri, headers=headers, data=data)


问:
Code to open a UIPopoverController
I currently have code to open a UIViewController, in this case you have opened it before so it will not totally load from scratch. So the old data will still be there when you return. I am not trying to save the data for the next time you go in the app. Only in that session. I am trying to adapt this code to the iPad for a UIPopOver. I have tried but am not able to do it.

//without popover

```<code>  - (IBAction) addPerson:(id) sender{
if (addPersonController == nil) {
    addPersonController = [[addPersonViewController alloc] initWithNibName:@"addPersonViewController" bundle:nil];
}

addPersonController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:addPersonController animated:YES];
[addPersonController retain];
 }
</code>```

//popover

```<code>  - (IBAction) addPerson:(id) sender{
// create your view controller if it doesn't exist yet
if (dateViewPopOverController == nil){
    addPersonViewController1 = [[addPersonViewControllerPopover_iPad alloc] init];
}
 pop = [[UIPopoverController alloc] initWithContentViewController:addPersonViewController1];

// rest of your method...
addPersonViewController1.delegate = self;

pop.popoverContentSize = CGSizeMake(320, 480);

CGRect rect = CGRectMake(790, 35, 175, 300);

[pop presentPopoverFromRect:rect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];

 }
</code>```

答: It looks like you just need an instance variable to hold your dateViewPopOverViewController_iPad instance.  Then use the same "if it's nil, create an instance" logic that you had for the DateViewController in the non-popover code.

Title: Code to open a UIPopoverController

Body:
I currently have code to open a UIViewController, in this case you have opened it before so it will not totally load from scratch. So the old data will still be there when you return. I am not trying to save the data for the next time you go in the app. Only in that session. I am trying to adapt this code to the iPad for a UIPopOver. I have tried but am not able to do it.

//without popover

  - (IBAction) addPerson:(id) sender{
if (addPersonController == nil) {
    addPersonController = [[addPersonViewController alloc] initWithNibName:@"addPersonViewController" bundle:nil];
}

addPersonController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:addPersonController animated:YES];
[addPersonController retain];
 }

//popover

  - (IBAction) addPerson:(id) sender{
// create your view controller if it doesn't exist yet
if (dateViewPopOverController == nil){
    addPersonViewController1 = [[addPersonViewControllerPopover_iPad alloc] init];
}
 pop = [[UIPopoverController alloc] initWithContentViewController:addPersonViewController1];

// rest of your method...
addPersonViewController1.delegate = self;

pop.popoverContentSize = CGSizeMake(320, 480);

CGRect rect = CGRectMake(790, 35, 175, 300);

[pop presentPopoverFromRect:rect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];

 }


问:
How to force 'cp' to overwrite directory instead of creating another one inside?
I'm trying to write a Bash script that will overwrite an existing directory. I have a directory foo/ and I am trying to overwrite bar/ with it. But when I do this:

```<code>cp -Rf foo/ bar/
</code>```

a new bar/foo/ directory is created. I don't want that. There are two files in foo/; a and b. There are files with same names in bar/ as well. I want the foo/a and foo/b to replace bar/a and bar/b.

答:
this should solve your problem. </p>

```<code>\cp -rf foo/* bar/
</code>```

Body:
I'm trying to write a Bash script that will overwrite an existing directory. I have a directory foo/ and I am trying to overwrite bar/ with it. But when I do this:

cp -Rf foo/ bar/

a new bar/foo/ directory is created. I don't want that. There are two files in foo/; a and b. There are files with same names in bar/ as well. I want the foo/a and foo/b to replace bar/a and bar/b.

Body:
this should solve your problem.

\cp -rf foo/* bar/


问:
Retrieve all instances of a custom Blazor component on a Blazor page
I would like to get all the instances of a Blazor components on a Blazor Page:

Page:

```<code><div class="mb-4 pt-3">
    <SearchFilter Refinement="@refinementAuthor" FilterTitle="Auteur"></SearchFilter>
</div>
<div class="mb-4 pt-3">
    <SearchFilter Refinement="@refinementSubject" FilterTitle="Onderwerp"></SearchFilter>
</div>
<div class="mb-4 pt-3">
    <SearchFilter Refinement="@refinementLanguage" FilterTitle="Taal"></SearchFilter>
</div>
</code>```

How can I get a List of the three "SearchFilter"?

答:
I believe that currently such a feature does not exist in Blazor. You can, however, create a list of components by adding component references (@ref directive attribute) to a list object as follow:

ChildComponent.razor

```<code><h3>@Title</h3>

@code {
    [Parameter]
    public string Title { get; set; }

}
</code>```

Usage

```<code><ChildComponent @ref="ChildComponent1" Title="ChildComponent 1"/>
<ChildComponent @ref="ChildComponent2" Title="ChildComponent 2" />
<ChildComponent @ref="ChildComponent3" Title="ChildComponent 3" />

@if (components != null)
{
   @foreach (var component in components)
  {
    <p>@component.Title</p>
  }

}

@code{
  ChildComponent ChildComponent1;
  ChildComponent ChildComponent2;
  ChildComponent ChildComponent3;

  List<ChildComponent> components;

  protected override void OnAfterRender(bool firstRender)
  {
    if (firstRender)
    {
        components = new List<ChildComponent>();
        components.Add(ChildComponent1);
        components.Add(ChildComponent2);
        components.Add(ChildComponent3);

        StateHasChanged();
    }
   }

}
</code>```

Note that the list is only populated after the page component is rendered. You can't access the components before as they are not yet created...

Body:
I would like to get all the instances of a Blazor components on a Blazor Page:

Page:

    <SearchFilter Refinement="@refinementAuthor" FilterTitle="Auteur"></SearchFilter>

    <SearchFilter Refinement="@refinementSubject" FilterTitle="Onderwerp"></SearchFilter>

    <SearchFilter Refinement="@refinementLanguage" FilterTitle="Taal"></SearchFilter>

How can I get a List of the three "SearchFilter"?

Body:
I believe that currently such a feature does not exist in Blazor. You can, however, create a list of components by adding component references (@ref directive attribute) to a list object as follow:

ChildComponent.razor

<h3>@Title</h3>

@code {
    [Parameter]
    public string Title { get; set; }

}

Usage

<ChildComponent @ref="ChildComponent1" Title="ChildComponent 1"/>
<ChildComponent @ref="ChildComponent2" Title="ChildComponent 2" />
<ChildComponent @ref="ChildComponent3" Title="ChildComponent 3" />

@if (components != null)
{
   @foreach (var component in components)
  {
    <p>@component.Title</p>
  }

}

@code{
  ChildComponent ChildComponent1;
  ChildComponent ChildComponent2;
  ChildComponent ChildComponent3;

  List<ChildComponent> components;

  protected override void OnAfterRender(bool firstRender)
  {
    if (firstRender)
    {
        components = new List<ChildComponent>();
        components.Add(ChildComponent1);
        components.Add(ChildComponent2);
        components.Add(ChildComponent3);

        StateHasChanged();
    }
   }

}

Note that the list is only populated after the page component is rendered. You can't access the components before as they are not yet created...


问:
Convert a string containing a number in scientific notation to a double in PHP
I need help converting a string that contains a number in scientific notation to a double.

Example strings:
"1.8281e-009"
"2.3562e-007"
"0.911348"

I was thinking about just breaking the number into the number on the left and the exponent and than just do the math to generate the number; but is there a better/standard way to do this?

答: I tried the +1,-1,/1 solution but that was not sufficient without rounding the number afterwards using round($a,4) or similar</p>

ContentLicense: CC BY-SA 2.5


问:
default value for file input form when update image in laravel 5.8
I'm Using Laravel 5.8, I'm trying to make update data in laravel, the data is contained images, when the form update did not get a new image, laravel displays an error, that the image is null,
can I make the old image as the default value for the file input?

this is my controller

```<code>public function UploadEdit(Request $request, Books $book,$id_book){
    $book = Books::find($id_book);
    global $old_image;
    $old_image = public_path("img/books/". $book->image);
    if($request->hasFile('image')){
        if (File::exists($old_image)) {
            unlink($old image);
        }

        $image = $request->file('image');
        $image_name = time()."_".$image->getClientOriginalName();
        $image->move('img/books',$image_name);
        $book->image=$image_name;
    }else{
        $book->image = $old_image;
    }

    DB::table('books')->where('id_book',$request->id_book,$image_name)->update([
        'title' => $request->title,
        'image' => $request->image = $image_name,
        'category' => $request->category,
        'description' => $request->description
    ]);

    return redirect('/books');
}
</code>```

this is input file from my form :

```<code><div class="form-group">
    <label for="image">Image</label>
    <input type="file" class="form-control-file" id="image" name="image" id="image" enctype="multipart/form-data" value="{{ asset("img/books/$book->image") }}">
    <img src="{{ asset("img/books/$book->image") }}" width="150">
</div>
</code>```

I'm trying to make the default value  for file form, but still doesn't work

答:
You don't need to get the old file. If you do not change it in the DB and storage when doing the update, it will still there, or will be still null if it was.

You can prepare the array with the data to update from the beginning of the method and add the image element, only if it is present.

```<code>$data = [
    'title' => $request->title,
    'category' => $request->category,
    'description' => $request->description
];

if($request->hasFile('image')){
    $image = $request->file('image');
    $image_name = time()."_".$image->getClientOriginalName();
    $image->move('img/books',$image_name);
    $data = array_merge($data, ['image' => $image_name]); // here you merge the image name on the data
}

DB::table('books')->where('id_book',$request->id_book)->update($data);
</code>```

Body:
I'm Using Laravel 5.8, I'm trying to make update data in laravel, the data is contained images, when the form update did not get a new image, laravel displays an error, that the image is null,
can I make the old image as the default value for the file input?

this is my controller

public function UploadEdit(Request $request, Books $book,$id_book){
    $book = Books::find($id_book);
    global $old_image;
    $old_image = public_path("img/books/". $book->image);
    if($request->hasFile('image')){
        if (File::exists($old_image)) {
            unlink($old image);
        }

        $image = $request->file('image');
        $image_name = time()."_".$image->getClientOriginalName();
        $image->move('img/books',$image_name);
        $book->image=$image_name;
    }else{
        $book->image = $old_image;
    }

    DB::table('books')->where('id_book',$request->id_book,$image_name)->update([
        'title' => $request->title,
        'image' => $request->image = $image_name,
        'category' => $request->category,
        'description' => $request->description
    ]);

    return redirect('/books');
}

this is input file from my form :

    Image
    <input type="file" class="form-control-file" id="image" name="image" id="image" enctype="multipart/form-data" value="{{ asset("img/books/$book->image") }}">
    image") }}" width="150">

I'm trying to make the default value  for file form, but still doesn't work

Body:
You don't need to get the old file. If you do not change it in the DB and storage when doing the update, it will still there, or will be still null if it was.

You can prepare the array with the data to update from the beginning of the method and add the image element, only if it is present.

$data = [
    'title' => $request->title,
    'category' => $request->category,
    'description' => $request->description
];

if($request->hasFile('image')){
    $image = $request->file('image');
    $image_name = time()."_".$image->getClientOriginalName();
    $image->move('img/books',$image_name);
    $data = array_merge($data, ['image' => $image_name]); // here you merge the image name on the data
}

DB::table('books')->where('id_book',$request->id_book)->update($data);


问:
React,Typescript, ".map is not a function" error in recursive map when using cloneElement to pass a method on component props.children
I am a react newbie, and trying to write a CustomFormComp that will be used like below,
I will have some form element components too, which will be used like InputComponent.

The child Components (InputComponent) need to get a method from the parent component(CustomFormComp) to handle onChnage and lift up their state to CustomFormComp,
although they should be able to combine onChange with a given method to them as callbacks.

And also if inner components bind correctly I should be able to pass them some data.

```<code>import React, { Component } from "react";
import CustomFormComp from "../Form";
import InputComponent from "../FormElements/InputComponent";

interface IState { }

interface IProps { }

interface FormElData {
  [key: string]: string;
}

export class CustomForm extends Component<IProps, IState> {
  render() {
    const formData: FormElData = {
      email: "someone@some-mail.com",
      phone: "sdfsdf",
      address: "asdhf akshdfkahsdkahsdflka hsfnasdk f"
    };

    return (
      <CustomFormComp FormData={formData}>
        <h2>f</h2>
        asd
        <h3>asdf</h3>
        <div className="c1">
          <div className="c2">
            <div className="c3">
              <InputComponent label="email: " name="email" />
            </div>
            <div className="c33"></div>
          </div>
          <div className="c22"></div>
        </div>
        <InputComponent label="phone: " name="phone" />
      </CustomFormComp>
    );
  }
}
</code>```

So far this is my customFromComp:

```<code>import React, { Component, ReactNode, Fragment } from "react"

interface FormElData {
    [key: string]: string
}

interface IState {
    FormData: {
        [key: string]: string
    }
}

type ICustomFormChildren = Array<null | React.ReactChild> //  | React.ReactChildren

interface IProps {
    FormData: FormElData
    children: ICustomFormChildren
}

class CustomFormComp extends Component<IProps, IState> {
    state = {
        FormData: {}
    }

    constructor(props: IProps) {
        super(props)
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
        this.state.FormData = this.props.FormData
    }

    componentDidMount() {
        this.setState({
            FormData: this.props.FormData
        })
    }

    handleInputChange(inputData: FormElData) {
        const newFormData: any = { ...this.state.FormData }
        newFormData[inputData.name] = inputData.value

        this.setState({
            FormData: newFormData
        })
    }

    handleSubmit(event: React.FormEvent) {
        event.preventDefault()
        console.log(this.state)
    }

    recursiveClone(children: ICustomFormChildren): ICustomFormChildren {
        return (children).map((child, index: number) => {
            let value: string

            if (React.isValidElement(child)) {
                if (
                    child.props &&
                    this.state.FormData &&
                    (this.state.FormData as any)[child.props.name]) {
                    value = (this.state.FormData as any)[child.props.name]

                    return React.cloneElement(child, {
                        onChange: this.handleInputChange.bind(this),
                        key: index,
                        value: value
                    })
                } else if (!child.props || !Object.keys(child.props).length) {
                    return <Fragment key={index}>{child}</Fragment>
                } else {
                    console.log(Array.isArray(child.props.children), child.props.children)
                    return React.cloneElement(
                        child,
                        { key: index },
                        this.recursiveClone(child.props.children)
                    )
                }
            } else {
                return <Fragment key={index}>{child}</Fragment>
            }
        })
    }

    render() {
        const newChildren = this.recursiveClone(this.props.children)

        return (
            <form style={{ direction: "ltr" }} onSubmit={this.handleSubmit}>
                {newChildren}
            </form>
        )
    }
}

export default CustomFormComp
</code>```

and this is my InputComponent:

```<code>import React, { Component } from 'react'

interface inputData {
  name: string,
  label: string,
  value?: string,
  onChange?(e:any): void
}

class InputComponent extends React.Component<inputData> {
  constructor(props:inputData) {
    super(props)
    this.onChange = this.onChange.bind(this)
  }

  onChange(e:any) {
    this.props.onChange && this.props.onChange({
      name: this.props.name,
      value: e.target.value
    })
  }

  render() {
    const value:string | undefined = this.props.value
    const name:string = this.props.name

    return (
      <fieldset>
        <label>
          {this.props.label}
          <input name={name} value={value} onChange={this.onChange} />
        </label>
      </fieldset>
    )
  }
}

export default InputComponent
</code>```

Now I think It should work but some types error prevent page from loading, this is the error:

```<code>**UPDATE**
</code>```

Main problem here is this:

The first time that i run the map it works fine, when I pass the child.props.children to in recursion it does not recognize the new argument(children which is child.props.children) and it trow an error.

答:
The problem is that children in react are not always an array, if you have only one child it is not an array.

Your code will work if you force recursive clone to send an array when there is only one child. See here:

```<code>recursiveClone(children: ICustomFormChildren): ICustomFormChildren {
    return children.map((child, index: number) => {
      let value: string;

      if (React.isValidElement(child)) {
        if (
          child.props &&
          this.state.FormData &&
          (this.state.FormData as any)[child.props.name]
        ) {
          value = (this.state.FormData as any)[child.props.name];

          return React.cloneElement(child, {
            onChange: this.handleInputChange.bind(this),
            key: index,
            value: value
          });
        } else if (!child.props || !Object.keys(child.props).length) {
          return <Fragment key={index}>{child}</Fragment>;
        } else {
          console.log(
            Array.isArray(child.props.children),
            child.props.children
          );
          if (!Array.isArray(child.props.children)) {
            return React.cloneElement(
              child,
              { key: index },
              this.recursiveClone([child.props.children])
            );
          }
          return React.cloneElement(
            child,
            { key: index },
            this.recursiveClone(child.props.children)
          );
        }
      } else {
        return <Fragment key={index}>{child}</Fragment>;
      }
    });
  }
</code>```

I added this if in your else

```<code>if (!Array.isArray(child.props.children)) {
            return React.cloneElement(
              child,
              { key: index },
              this.recursiveClone([child.props.children])
            );
          }
</code>```

I tested it here in this https://codesandbox.io/s/new-surf-d17rk

Body:
I am a react newbie, and trying to write a CustomFormComp that will be used like below,
I will have some form element components too, which will be used like InputComponent.

The child Components (InputComponent) need to get a method from the parent component(CustomFormComp) to handle onChnage and lift up their state to CustomFormComp,
although they should be able to combine onChange with a given method to them as callbacks.

And also if inner components bind correctly I should be able to pass them some data.

import React, { Component } from "react";
import CustomFormComp from "../Form";
import InputComponent from "../FormElements/InputComponent";

interface IState { }

interface IProps { }

interface FormElData {
  [key: string]: string;
}

export class CustomForm extends Component<IProps, IState> {
  render() {
    const formData: FormElData = {
      email: "someone@some-mail.com",
      phone: "sdfsdf",
      address: "asdhf akshdfkahsdkahsdflka hsfnasdk f"
    };

    return (
      <CustomFormComp FormData={formData}>

f

        asd

asdf

              <InputComponent label="email: " name="email" />

        <InputComponent label="phone: " name="phone" />
      </CustomFormComp>
    );
  }
}

So far this is my customFromComp:

import React, { Component, ReactNode, Fragment } from "react"

interface FormElData {
    [key: string]: string
}

interface IState {
    FormData: {
        [key: string]: string
    }
}

type ICustomFormChildren = Array<null | React.ReactChild> //  | React.ReactChildren

interface IProps {
    FormData: FormElData
    children: ICustomFormChildren
}

class CustomFormComp extends Component<IProps, IState> {
    state = {
        FormData: {}
    }

    constructor(props: IProps) {
        super(props)
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
        this.state.FormData = this.props.FormData
    }

    componentDidMount() {
        this.setState({
            FormData: this.props.FormData
        })
    }

    handleInputChange(inputData: FormElData) {
        const newFormData: any = { ...this.state.FormData }
        newFormData[inputData.name] = inputData.value

        this.setState({
            FormData: newFormData
        })
    }

    handleSubmit(event: React.FormEvent) {
        event.preventDefault()
        console.log(this.state)
    }

    recursiveClone(children: ICustomFormChildren): ICustomFormChildren {
        return (children).map((child, index: number) => {
            let value: string

            if (React.isValidElement(child)) {
                if (
                    child.props &&
                    this.state.FormData &&
                    (this.state.FormData as any)[child.props.name]) {
                    value = (this.state.FormData as any)[child.props.name]

                    return React.cloneElement(child, {
                        onChange: this.handleInputChange.bind(this),
                        key: index,
                        value: value
                    })
                } else if (!child.props || !Object.keys(child.props).length) {
                    return <Fragment key={index}>{child}</Fragment>
                } else {
                    console.log(Array.isArray(child.props.children), child.props.children)
                    return React.cloneElement(
                        child,
                        { key: index },
                        this.recursiveClone(child.props.children)
                    )
                }
            } else {
                return <Fragment key={index}>{child}</Fragment>
            }
        })
    }

    render() {
        const newChildren = this.recursiveClone(this.props.children)

        return (
            <form style={{ direction: "ltr" }} onSubmit={this.handleSubmit}>
                {newChildren}
            </form>
        )
    }
}

export default CustomFormComp

and this is my InputComponent:

import React, { Component } from 'react'

interface inputData {
  name: string,
  label: string,
  value?: string,
  onChange?(e:any): void
}

class InputComponent extends React.Component<inputData> {
  constructor(props:inputData) {
    super(props)
    this.onChange = this.onChange.bind(this)
  }

  onChange(e:any) {
    this.props.onChange && this.props.onChange({
      name: this.props.name,
      value: e.target.value
    })
  }

  render() {
    const value:string | undefined = this.props.value
    const name:string = this.props.name

    return (
      <fieldset>

          {this.props.label}
          <input name={name} value={value} onChange={this.onChange} />

      </fieldset>
    )
  }
}

export default InputComponent

Now I think It should work but some types error prevent page from loading, this is the error:

**UPDATE**

Main problem here is this:

The first time that i run the map it works fine, when I pass the child.props.children to in recursion it does not recognize the new argument(children which is child.props.children) and it trow an error.

Body:
The problem is that children in react are not always an array, if you have only one child it is not an array.

Your code will work if you force recursive clone to send an array when there is only one child. See here:

recursiveClone(children: ICustomFormChildren): ICustomFormChildren {
    return children.map((child, index: number) => {
      let value: string;

      if (React.isValidElement(child)) {
        if (
          child.props &&
          this.state.FormData &&
          (this.state.FormData as any)[child.props.name]
        ) {
          value = (this.state.FormData as any)[child.props.name];

          return React.cloneElement(child, {
            onChange: this.handleInputChange.bind(this),
            key: index,
            value: value
          });
        } else if (!child.props || !Object.keys(child.props).length) {
          return <Fragment key={index}>{child}</Fragment>;
        } else {
          console.log(
            Array.isArray(child.props.children),
            child.props.children
          );
          if (!Array.isArray(child.props.children)) {
            return React.cloneElement(
              child,
              { key: index },
              this.recursiveClone([child.props.children])
            );
          }
          return React.cloneElement(
            child,
            { key: index },
            this.recursiveClone(child.props.children)
          );
        }
      } else {
        return <Fragment key={index}>{child}</Fragment>;
      }
    });
  }

I added this if in your else

if (!Array.isArray(child.props.children)) {
            return React.cloneElement(
              child,
              { key: index },
              this.recursiveClone([child.props.children])
            );
          }

I tested it here in this https://codesandbox.io/s/new-surf-d17rk


问:
How to logging information about 404 error while Debug = False
I have a django project on production.  In my settings.py file Debug=False to avoid security risks which arrises when Debug=True I heard about python logging module which I am trying to set up.  But after reading documentation like I understand I should put logging instances in each piece of code where error can be arrised,  but what if I need to handle 404 errors?  How I can handle them?  Please anyone guide me

答:
I think there is quite a bunch of information around about 404 handling in django. The most basic thing might be the 404 view that you can override with your custom logics (which i think is not preferred, but might come in handy in some specific cases): https://docs.djangoproject.com/en/3.0/topics/http/views/#customizing-error-views

The preferred method would be going deeper in to the core of request and response handling where you can manipulate your requests having a response status_code of 404 or what so ever. In your middleware you can extend and override behavior of existing middlewares or add your own: https://docs.djangoproject.com/en/3.0/topics/http/middleware/

Below you have  simple example of a middleware that checkes the response's status code and uses log.warning when the reponse has a status_code of 404. In this scenario you'll have a single location being responsible of logging the faulty paths that are being requested.

```<code># myproject.middleware.py
import logging

logger = logging.getLogger(__name__)

class PageNotFoundMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if response.status_code == 404:
            logger.warning("Page not found at {}".format(request.path))
        return response
</code>```

in your settings.py you can now add the middleware:

```<code>MIDDLEWARE = [
   ...
   'myproject.middleware.PageNotFoundMiddleware',
]
</code>```

Body:
I think there is quite a bunch of information around about 404 handling in django. The most basic thing might be the 404 view that you can override with your custom logics (which i think is not preferred, but might come in handy in some specific cases): https://docs.djangoproject.com/en/3.0/topics/http/views/#customizing-error-views

The preferred method would be going deeper in to the core of request and response handling where you can manipulate your requests having a response status_code of 404 or what so ever. In your middleware you can extend and override behavior of existing middlewares or add your own: https://docs.djangoproject.com/en/3.0/topics/http/middleware/

Below you have  simple example of a middleware that checkes the response's status code and uses log.warning when the reponse has a status_code of 404. In this scenario you'll have a single location being responsible of logging the faulty paths that are being requested.

# myproject.middleware.py
import logging

logger = logging.getLogger(__name__)

class PageNotFoundMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if response.status_code == 404:
            logger.warning("Page not found at {}".format(request.path))
        return response

in your settings.py you can now add the middleware:

MIDDLEWARE = [
   ...
   'myproject.middleware.PageNotFoundMiddleware',
]