答:
You can use Object.assign

let product={name:'name',briefPDescription:'text',details:{about:'text',description:'text',comment:{"text":'text'},subDescription:'text'}};
let author={name:'name',position:'text',photo:'../avatar.png'};

Object.assign(product.details.comment, author);
console.log(product);```

Body:
I need to write new properties for the comment property without erasing it.
This is my object now:

product:
{
  name: 'name',
  briefPDescription: 'text',
  details:
   {
     about: 'text',
     description: 'text',
     comment:
     {
         "text": 'text'
     },
     subDescription: 'text'
}

What you need to write:

author:
{
    name: 'name',
    position: 'text',
    photo: '../avatar.png'
}

How should it be:

product:
{
  name: 'name',
  briefPDescription: 'text',
  details:
  {
     about: 'text',
     description: 'text',
     comment:
     {
         text: ''text',
         name: 'name',
         position: 'text',
         photo: '../avatar.png'
     },
     subDescription: 'text'
}

I did this:

product.comment = author;

But it deleted the text property.
How can I write new properties to the comment property without erasing it?


来源: stackexchange

问:
I keep getting null values after adding new element to my object
I have an array object with some similar values. I'm excluding their duplicate values using a loop, and then I add the values to my other object(objectProperties) it's working fine however I get a NULL values inside category

   // data which im extracting
var data = [
   {
      "label":"May 14",
      "value":56714.4,
      "proID":"ISB"
   },
   {
      "label":"May 14",
      "value":15902.5,
      "proID":"LI8"
   },
   {
      "label":"May 14",
      "value":419.6,
      "proID":"TR2"
   },
   {
      "label":"May 15",
      "value":2754.8,
      "proID":"DAC"
   },
   {
      "label":"May 15",
      "value":50845.7,
      "proID":"ISB"
   },
   {
      "label":"May 15",
      "value":19760.3,
      "proID":"LI8"
   },
   {
      "label":"May 15",
      "value":1704.1,
      "proID":"TR2"
   },
   {
      "label":"May 16",
      "value":2145.6,
      "proID":"DAC"
   },
   {
      "label":"May 16",
      "value":55666.4,
      "proID":"ISB"
   },
   {
      "label":"May 16",
      "value":15044.4,
      "proID":"LI8"
   },
   {
      "label":"May 16",
      "value":2413.5,
      "proID":"TR2"
   },
   {
      "label":"May 17",
      "value":6564.4,
      "proID":"DAC"
   },
   {
      "label":"May 17",
      "value":71379,
      "proID":"ISB"
   },
   {
      "label":"May 17",
      "value":21774.2,
      "proID":"LI8"
   },
   {
      "label":"May 17",
      "value":2191.4,
      "proID":"TR2"
   },
   {
      "label":"May 18",
      "value":63338.9,
      "proID":"ISB"
   },
   {
      "label":"May 18",
      "value":24451,
      "proID":"LI8"
   },
   {
      "label":"May 18",
      "value":2616.5,
      "proID":"TR2"
   }
];

var propertiesObject = {    // my object
    type: 'mscolumn2d',
     renderAt: 'chart-container',
     width: '1000',
     height: '500',
     dataFormat: 'json',
     dataSource: {
        chart: {
            caption: "Kilos per Date Comparison"

            },
    categories: [
            {
                category: []
            }
        ]

    }
 };

    var propCount = Object.keys(data).length; // getting object length
    var checkSameLabel = data[0].label;    // for reference reference inside the loop
    var firstIndex = {"label":data[0].label}; // im taking first index of object and add manually
    propertiesObject.dataSource.categories[0].category[0] = firstIndex; // adding the first index to my object
    var currentProject = data[0].proID, counterCurrentProject = 0;
    for(let i = 0; i < propCount; i++) {
        if(checkSameLabel !== data[i].label) { // check if current value of label is not equal then add new data to my object

            const value = data[i].label;
            var obj = {
                "label": value
            };
            propertiesObject.dataSource.categories[0].category[i] = value; // adding new data
        }
        checkSameLabel = data[i].label; // for the next check
    }
    console.log(JSON.stringify(propertiesObject));
    document.getElementById("result").innerHTML = JSON.stringify(propertiesObject);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="result"></div></code>```

I'm expecting the output to be like this inside "category"

```<code>{ "label": "May 14" },
{ "label": "May 15" },
{ "label": "May 16" },
{ "label": "May 17" }
</code>```

I don't know if it's because of my loop or im doing something wrong.

答:
There are a few errors

You created variable 'obj', but not using it

```<code>
var obj = {
    "label": value
};

// No good
propertiesObject.dataSource.categories[0].category[i] = value;

// Should be this, but still not correct, see point (2)
propertiesObject.dataSource.categories[0].category[i] = obj;
</code>```

You are adding elements to array by setting it with index, you should use array push instead

```<code>// No good
propertiesObject.dataSource.categories[0].category[i] = obj;

// Should be
propertiesObject.dataSource.categories[0].category.push(obj);
</code>```

// data which im extracting
var data = [
   {
      "label":"May 14",
      "value":56714.4,
      "proID":"ISB"
   },
   {
      "label":"May 14",
      "value":15902.5,
      "proID":"LI8"
   },
   {
      "label":"May 14",
      "value":419.6,
      "proID":"TR2"
   },
   {
      "label":"May 15",
      "value":2754.8,
      "proID":"DAC"
   },
   {
      "label":"May 15",
      "value":50845.7,
      "proID":"ISB"
   },
   {
      "label":"May 15",
      "value":19760.3,
      "proID":"LI8"
   },
   {
      "label":"May 15",
      "value":1704.1,
      "proID":"TR2"
   },
   {
      "label":"May 16",
      "value":2145.6,
      "proID":"DAC"
   },
   {
      "label":"May 16",
      "value":55666.4,
      "proID":"ISB"
   },
   {
      "label":"May 16",
      "value":15044.4,
      "proID":"LI8"
   },
   {
      "label":"May 16",
      "value":2413.5,
      "proID":"TR2"
   },
   {
      "label":"May 17",
      "value":6564.4,
      "proID":"DAC"
   },
   {
      "label":"May 17",
      "value":71379,
      "proID":"ISB"
   },
   {
      "label":"May 17",
      "value":21774.2,
      "proID":"LI8"
   },
   {
      "label":"May 17",
      "value":2191.4,
      "proID":"TR2"
   },
   {
      "label":"May 18",
      "value":63338.9,
      "proID":"ISB"
   },
   {
      "label":"May 18",
      "value":24451,
      "proID":"LI8"
   },
   {
      "label":"May 18",
      "value":2616.5,
      "proID":"TR2"
   }
];

var propertiesObject = {    // my object
    type: 'mscolumn2d',
     renderAt: 'chart-container',
     width: '1000',
     height: '500',
     dataFormat: 'json',
     dataSource: {
        chart: {
            caption: "Kilos per Date Comparison"

            },
    categories: [
            {
                category: []
            }
        ]

    }
 };

    var propCount = Object.keys(data).length; // getting object length

    console.log(propCount)

    var checkSameLabel = data[0].label;    // for reference reference inside the loop
    var firstIndex = {"label":data[0].label}; // im taking first index of object and add manually
    propertiesObject.dataSource.categories[0].category[0] = firstIndex; // adding the first index to my object
    var currentProject = data[0].proID, counterCurrentProject = 0;
    for(let i = 0; i < propCount; i++) {
        if(checkSameLabel != data[i].label) { // check if current value of label is not equal then add new data to my object

            const value = data[i].label;
            var obj = {
                "label": value
            };

            // Use Array.push() to add new data
            propertiesObject.dataSource.categories[0].category.push(obj);
        }
        checkSameLabel = data[i].label; // for the next check
    }
    console.log(JSON.stringify(propertiesObject));
    document.getElementById("result").innerHTML = JSON.stringify(propertiesObject);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="result"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array object with some similar values. I'm excluding their duplicate values using a loop, and then I add the values to my other object(objectProperties) it's working fine however I get a NULL values inside category

   // data which im extracting
var data = [
   {
      "label":"May 14",
      "value":56714.4,
      "proID":"ISB"
   },
   {
      "label":"May 14",
      "value":15902.5,
      "proID":"LI8"
   },
   {
      "label":"May 14",
      "value":419.6,
      "proID":"TR2"
   },
   {
      "label":"May 15",
      "value":2754.8,
      "proID":"DAC"
   },
   {
      "label":"May 15",
      "value":50845.7,
      "proID":"ISB"
   },
   {
      "label":"May 15",
      "value":19760.3,
      "proID":"LI8"
   },
   {
      "label":"May 15",
      "value":1704.1,
      "proID":"TR2"
   },
   {
      "label":"May 16",
      "value":2145.6,
      "proID":"DAC"
   },
   {
      "label":"May 16",
      "value":55666.4,
      "proID":"ISB"
   },
   {
      "label":"May 16",
      "value":15044.4,
      "proID":"LI8"
   },
   {
      "label":"May 16",
      "value":2413.5,
      "proID":"TR2"
   },
   {
      "label":"May 17",
      "value":6564.4,
      "proID":"DAC"
   },
   {
      "label":"May 17",
      "value":71379,
      "proID":"ISB"
   },
   {
      "label":"May 17",
      "value":21774.2,
      "proID":"LI8"
   },
   {
      "label":"May 17",
      "value":2191.4,
      "proID":"TR2"
   },
   {
      "label":"May 18",
      "value":63338.9,
      "proID":"ISB"
   },
   {
      "label":"May 18",
      "value":24451,
      "proID":"LI8"
   },
   {
      "label":"May 18",
      "value":2616.5,
      "proID":"TR2"
   }
];

var propertiesObject = {    // my object
    type: 'mscolumn2d',
     renderAt: 'chart-container',
     width: '1000',
     height: '500',
     dataFormat: 'json',
     dataSource: {
        chart: {
            caption: "Kilos per Date Comparison"

            },
    categories: [
            {
                category: []
            }
        ]

    }
 };

    var propCount = Object.keys(data).length; // getting object length
    var checkSameLabel = data[0].label;    // for reference reference inside the loop
    var firstIndex = {"label":data[0].label}; // im taking first index of object and add manually
    propertiesObject.dataSource.categories[0].category[0] = firstIndex; // adding the first index to my object
    var currentProject = data[0].proID, counterCurrentProject = 0;
    for(let i = 0; i < propCount; i++) {
        if(checkSameLabel !== data[i].label) { // check if current value of label is not equal then add new data to my object

            const value = data[i].label;
            var obj = {
                "label": value
            };
            propertiesObject.dataSource.categories[0].category[i] = value; // adding new data
        }
        checkSameLabel = data[i].label; // for the next check
    }
    console.log(JSON.stringify(propertiesObject));
    document.getElementById("result").innerHTML = JSON.stringify(propertiesObject);

I'm expecting the output to be like this inside "category"

{ "label": "May 14" },
{ "label": "May 15" },
{ "label": "May 16" },
{ "label": "May 17" }

I don't know if it's because of my loop or im doing something wrong.

Body:
There are a few errors

You created variable 'obj', but not using it

var obj = {
    "label": value
};

// No good
propertiesObject.dataSource.categories[0].category[i] = value;

// Should be this, but still not correct, see point (2)
propertiesObject.dataSource.categories[0].category[i] = obj;

You are adding elements to array by setting it with index, you should use array push instead

// No good
propertiesObject.dataSource.categories[0].category[i] = obj;

// Should be
propertiesObject.dataSource.categories[0].category.push(obj);

// data which im extracting
var data = [
   {
      "label":"May 14",
      "value":56714.4,
      "proID":"ISB"
   },
   {
      "label":"May 14",
      "value":15902.5,
      "proID":"LI8"
   },
   {
      "label":"May 14",
      "value":419.6,
      "proID":"TR2"
   },
   {
      "label":"May 15",
      "value":2754.8,
      "proID":"DAC"
   },
   {
      "label":"May 15",
      "value":50845.7,
      "proID":"ISB"
   },
   {
      "label":"May 15",
      "value":19760.3,
      "proID":"LI8"
   },
   {
      "label":"May 15",
      "value":1704.1,
      "proID":"TR2"
   },
   {
      "label":"May 16",
      "value":2145.6,
      "proID":"DAC"
   },
   {
      "label":"May 16",
      "value":55666.4,
      "proID":"ISB"
   },
   {
      "label":"May 16",
      "value":15044.4,
      "proID":"LI8"
   },
   {
      "label":"May 16",
      "value":2413.5,
      "proID":"TR2"
   },
   {
      "label":"May 17",
      "value":6564.4,
      "proID":"DAC"
   },
   {
      "label":"May 17",
      "value":71379,
      "proID":"ISB"
   },
   {
      "label":"May 17",
      "value":21774.2,
      "proID":"LI8"
   },
   {
      "label":"May 17",
      "value":2191.4,
      "proID":"TR2"
   },
   {
      "label":"May 18",
      "value":63338.9,
      "proID":"ISB"
   },
   {
      "label":"May 18",
      "value":24451,
      "proID":"LI8"
   },
   {
      "label":"May 18",
      "value":2616.5,
      "proID":"TR2"
   }
];

var propertiesObject = {    // my object
    type: 'mscolumn2d',
     renderAt: 'chart-container',
     width: '1000',
     height: '500',
     dataFormat: 'json',
     dataSource: {
        chart: {
            caption: "Kilos per Date Comparison"

            },
    categories: [
            {
                category: []
            }
        ]

    }
 };

    var propCount = Object.keys(data).length; // getting object length

    console.log(propCount)

    var checkSameLabel = data[0].label;    // for reference reference inside the loop
    var firstIndex = {"label":data[0].label}; // im taking first index of object and add manually
    propertiesObject.dataSource.categories[0].category[0] = firstIndex; // adding the first index to my object
    var currentProject = data[0].proID, counterCurrentProject = 0;
    for(let i = 0; i < propCount; i++) {
        if(checkSameLabel != data[i].label) { // check if current value of label is not equal then add new data to my object

            const value = data[i].label;
            var obj = {
                "label": value
            };

            // Use Array.push() to add new data
            propertiesObject.dataSource.categories[0].category.push(obj);
        }
        checkSameLabel = data[i].label; // for the next check
    }
    console.log(JSON.stringify(propertiesObject));
    document.getElementById("result").innerHTML = JSON.stringify(propertiesObject);

<div id="result"></div>


问:
Animation On Local Position
I am trying to make this:

The chracter walks up to a large crate, the player presses the e key and an animation starts playing, such that the character climbs up on to the crate. (all in first person view).

So far I tried this with normal "First Person Controller" Prefab in Unity.

My code so far:

function OnTriggerStay(other : Collider){
    if(other.tag == "GrabZone"){
        if(Input.GetKeyDown("e")){
            animation.Play("JumpToLedge");
        }
    }
}
```

However when I use this on the FPC, it will always play from the position the animation is created on. I also tried to create an empty game object, placing the FPC in there. Gives same effect.

Most recently, I tried just animating the graphics of the FPC alone. This seems to work, but since the Character Controller itself is not animated, that stays on the ground. So the whole FPC won't work anymore.

Is there anyway I could let this animation play on the local position the player is on at that time? Or can you think of any other logical solution for a grab and climb?

答: You should always animate from the 0,0 position. This way you can always easilyl determine what to do and where to go with your model.</p>

ContentLicense: CC BY-SA 3.0

Title: Animation On Local Position

Body:
I am trying to make this:

The chracter walks up to a large crate, the player presses the e key and an animation starts playing, such that the character climbs up on to the crate. (all in first person view).

So far I tried this with normal "First Person Controller" Prefab in Unity.

My code so far:

function OnTriggerStay(other : Collider){
    if(other.tag == "GrabZone"){
        if(Input.GetKeyDown("e")){
            animation.Play("JumpToLedge");
        }
    }
}

However when I use this on the FPC, it will always play from the position the animation is created on. I also tried to create an empty game object, placing the FPC in there. Gives same effect.

Most recently, I tried just animating the graphics of the FPC alone. This seems to work, but since the Character Controller itself is not animated, that stays on the ground. So the whole FPC won't work anymore.

Is there anyway I could let this animation play on the local position the player is on at that time? Or can you think of any other logical solution for a grab and climb?


问:
Whenever I open my anaconda command prompt the error message occurs, so help me with it
I have recently set up the latest version of anaconda and when I open my anaconda command prompt an error message occurs.
Due to this issue, I am also not able to set up venv in my anaconda.

I have tried to search that conda-645.tmp but I haven't found that in that particular location as well.

Access is denied. The system cannot find the file C:\Users\UDIT. Could
  Not Find C:\Users\UDIT DEO\AppData\Local\Temp\conda-645.tmp

答:
Try running it as administrator.
This should solve this error.</p>


问:
Separate a column of a dataframe in undefined number of columns with R/tidyverse
I have to import a table that look like as the following dataframe:

```<code>> df = data.frame(x = c("a", "a.b","a.b.c","a.b.d", "a.d"))
> df
      x
1  <NA>
2     a
3   a.b
4 a.b.c
5 a.b.d
6   a.d
</code>```

I'd like to separate the first column in one or more columns based one how many separator I'll find.

The output should lool like this

```<code>> df_separated
  col1 col2 col3
1    a <NA> <NA>
2    a    b <NA>
3    a    b    c
4    a    b    d
5    a    d <NA>
</code>```

I tried to use the separate function in tidyr but I need to specify a priori how many outoput columns I need.

Thank you very much for your help

答:
You can first count the number of columns it can take and then use separate.

```<code>nmax <- max(stringr::str_count(df$x, "\\.")) + 1
tidyr::separate(df, x, paste0("col", seq_len(nmax)), sep = "\\.", fill = "right")

#  col1 col2 col3
#1    a <NA> <NA>
#2    a    b <NA>
#3    a    b    c
#4    a    b    d
#5    a    d <NA>
</code>```

Body:
I have to import a table that look like as the following dataframe:

> df = data.frame(x = c("a", "a.b","a.b.c","a.b.d", "a.d"))
> df
      x
1  <NA>
2     a
3   a.b
4 a.b.c
5 a.b.d
6   a.d

I'd like to separate the first column in one or more columns based one how many separator I'll find.

The output should lool like this

> df_separated
  col1 col2 col3
1    a <NA> <NA>
2    a    b <NA>
3    a    b    c
4    a    b    d
5    a    d <NA>

I tried to use the separate function in tidyr but I need to specify a priori how many outoput columns I need.

Thank you very much for your help

Body:
You can first count the number of columns it can take and then use separate.

nmax <- max(stringr::str_count(df$x, "\\.")) + 1
tidyr::separate(df, x, paste0("col", seq_len(nmax)), sep = "\\.", fill = "right")

#  col1 col2 col3
#1    a <NA> <NA>
#2    a    b <NA>
#3    a    b    c
#4    a    b    d
#5    a    d <NA>


问:
How to detect intersections of two faces of two bufferGeometryBox?
I am developing a 3d configurator. A cube appears on the scene. If you click on the side of this cube, a rectangle appears. The problem is that if I click on the same side of the cube, another one will be added over the existing rectangle. I would like to block the clicked side. My cubes and rectangles is buffer geometry. I can get raycasting face (a,b,c) and faceIndex. But how to get intersection of two different faces of two different objects? Sorry for my english

This is my project https://alovert.ru

my code

```<code>if (intersect) {
            var index = Math.floor( intersect.faceIndex / 6 );
                if ( intersect.object.name == 'cube' ) {

                    switch ( index ) {
                        case 0: load( intersect.object.position.x + 6.58, intersect.object.position.y, intersect.object.position.z, 'beam', 0, 0, 0 ); break;
                        case 1: load( intersect.object.position.x - 6.58, intersect.object.position.y, intersect.object.position.z, 'beam', 0, 0, 0 ); break;
                        case 2: load( intersect.object.position.x, intersect.object.position.y + 6.58, intersect.object.position.z, 'beam', 0, 0, 90 ); break;
                        case 3: load( intersect.object.position.x, intersect.object.position.y - 6.58, intersect.object.position.z, 'beam', 0, 0, 90 ); break;
                        case 4: load( intersect.object.position.x, intersect.object.position.y, intersect.object.position.z + 6.58, 'beam', 0, 90, 0 ); break;
                        case 5: load( intersect.object.position.x, intersect.object.position.y, intersect.object.position.z - 6.58, 'beam', 0, 90, 0 ); break;
                    }

                }`

</code>```

答:
see the following meta-code that describes the idea:</p>

```<code>let newObject = loadObject(...);
parentObj.add(newObject);
newObject.position.set(new_x, new_y, new_z);
let globalPosition = new THREE.Vector3();
newObject.getWorldPosition(globalPosition);
for (let i = 0; i < existingPositions.length; i++){
    if(     existingPositions[i].x === globalPosition.x
        &&  existingPositions[i].y === globalPosition.y
        &&  existingPositions[i].z === globalPosition.z) {
            parentObj.remove(newObject);
            return;
    }
}
existingPositions.push(globalPosition);
</code>```

Body:
I am developing a 3d configurator. A cube appears on the scene. If you click on the side of this cube, a rectangle appears. The problem is that if I click on the same side of the cube, another one will be added over the existing rectangle. I would like to block the clicked side. My cubes and rectangles is buffer geometry. I can get raycasting face (a,b,c) and faceIndex. But how to get intersection of two different faces of two different objects? Sorry for my english

This is my project https://alovert.ru

my code

if (intersect) {
            var index = Math.floor( intersect.faceIndex / 6 );
                if ( intersect.object.name == 'cube' ) {

                    switch ( index ) {
                        case 0: load( intersect.object.position.x + 6.58, intersect.object.position.y, intersect.object.position.z, 'beam', 0, 0, 0 ); break;
                        case 1: load( intersect.object.position.x - 6.58, intersect.object.position.y, intersect.object.position.z, 'beam', 0, 0, 0 ); break;
                        case 2: load( intersect.object.position.x, intersect.object.position.y + 6.58, intersect.object.position.z, 'beam', 0, 0, 90 ); break;
                        case 3: load( intersect.object.position.x, intersect.object.position.y - 6.58, intersect.object.position.z, 'beam', 0, 0, 90 ); break;
                        case 4: load( intersect.object.position.x, intersect.object.position.y, intersect.object.position.z + 6.58, 'beam', 0, 90, 0 ); break;
                        case 5: load( intersect.object.position.x, intersect.object.position.y, intersect.object.position.z - 6.58, 'beam', 0, 90, 0 ); break;
                    }

                }`

Body:
see the following meta-code that describes the idea:

let newObject = loadObject(...);
parentObj.add(newObject);
newObject.position.set(new_x, new_y, new_z);
let globalPosition = new THREE.Vector3();
newObject.getWorldPosition(globalPosition);
for (let i = 0; i < existingPositions.length; i++){
    if(     existingPositions[i].x === globalPosition.x
        &&  existingPositions[i].y === globalPosition.y
        &&  existingPositions[i].z === globalPosition.z) {
            parentObj.remove(newObject);
            return;
    }
}
existingPositions.push(globalPosition);


问:
How to convert EventCallback<T> to EventCallback<bool>
Blazor has a generic class named EventCallback

How can I cast a

```<code>protected EventCallback<T> ValueChanged { get; set; }
</code>```

to

```<code>EventCallback<bool> BoolChanged
   {
     get
     {
       if (typeof(T) == typeof(bool))
         return ValueChanged; //<== Error needs cast some how?
     }
   }
</code>```

答:
Thanks to Levi Broderick via Twitter for the answer.

```<code>protected EventCallback<bool> BoolChanged => (EventCallback<bool>)(object)ValueChanged;
</code>```

He states: Bouncing the cast through object is basically a C# idiom for "I know the compiler can't reason about this at compile time, but try it anyway at runtime and I accept that an exception might occur."

Body:
Blazor has a generic class named EventCallback

How can I cast a

protected EventCallback<T> ValueChanged { get; set; }

to

EventCallback<bool> BoolChanged
   {
     get
     {
       if (typeof(T) == typeof(bool))
         return ValueChanged; //<== Error needs cast some how?
     }
   }

Body:
Thanks to Levi Broderick via Twitter for the answer.

protected EventCallback<bool> BoolChanged => (EventCallback<bool>)(object)ValueChanged;

He states: Bouncing the cast through object is basically a C# idiom for "I know the compiler can't reason about this at compile time, but try it anyway at runtime and I accept that an exception might occur."


问:
Host Actions On Google App With Dialogflow Using Node JS on Self Hosted HTTPS Server (MalformedResponse: Webhook error (206))
I have created one app in actions on google with dialogflow using nodejs. First it is hosted on heroku server, but now i want to host in my server with https.

it works properly on heroku server but not working on my server. It returns error "MalformedResponse: Webhook error (206)"

```<code>const express = require('express');
const bodyParser = require('body-parser');
var https = require('https');
var fs = require('fs');
const {
  dialogflow,
} = require('actions-on-google');

const app = dialogflow();
const expressApp = express().use(bodyParser.json());

// degault welcome intent on startup
app.intent('Default Welcome Intent', conv => {
    conv.ask('Hi, Ask me about Customer Ledger, Outstanding....');
});

app.intent('Default Fallback Intent', conv => {
  conv.ask('I didnt understand. Can you tell me something else?');
});

var options = {
  key: fs.readFileSync('ssl/office.key'),
  cert: fs.readFileSync('ssl/office.crt')
};

var server = https.createServer(options, expressApp).listen(3000, function(){
    //express().use(bodyParser.json(), app);
    expressApp.post('/fulfillment', app);
  console.log("Express server listening on port 3000" );
});
</code>```

Can anyone suggest me what is the problem with my code?Simulator Screenshot

答: If you are using express and there is no other layer in between (like Heroku has) to forward requests from port 443 to 3000, the request might not be reaching the target port</p>

Body:
I have created one app in actions on google with dialogflow using nodejs. First it is hosted on heroku server, but now i want to host in my server with https.

it works properly on heroku server but not working on my server. It returns error "MalformedResponse: Webhook error (206)"

const express = require('express');
const bodyParser = require('body-parser');
var https = require('https');
var fs = require('fs');
const {
  dialogflow,
} = require('actions-on-google');

const app = dialogflow();
const expressApp = express().use(bodyParser.json());

// degault welcome intent on startup
app.intent('Default Welcome Intent', conv => {
    conv.ask('Hi, Ask me about Customer Ledger, Outstanding....');
});

app.intent('Default Fallback Intent', conv => {
  conv.ask('I didnt understand. Can you tell me something else?');
});

var options = {
  key: fs.readFileSync('ssl/office.key'),
  cert: fs.readFileSync('ssl/office.crt')
};

var server = https.createServer(options, expressApp).listen(3000, function(){
    //express().use(bodyParser.json(), app);
    expressApp.post('/fulfillment', app);
  console.log("Express server listening on port 3000" );
});

Can anyone suggest me what is the problem with my code?Simulator Screenshot


问:
How do react hooks reference values passed to the array of dependencies?
Say I have this component, with  the following hook:

```<code>function SomeComponent(props) {
useEffect(
    () => {
        //....code
        if (props.propOne === ....) { .... }
        // ...code
        if (props.propTwo === ....) { .... }
    },
    [props.propOne]
)

return <Something />

}
</code>```

The above hook will run

once on the first time the component code gets executed

every time the value of props.propOne changes

Notice however that the hook callback also makes a reference to pros.propTwo, without actually having it passed to the dependencies array.

While props.propTwo will never factor in whether the hooks gets re-executed, what happens to the value of it that the hook callback references inside its body?

for example

During initial component rendering props.propOne === A and props.propTwo === B

The hook gets executed and references values A and B

During a subsequent rendering props.propOne === C and props.propTwo === D

The hook gets re-executed, since props.propOne changed. It references value C for the props.propOne but what does it reference for the props.propTwo value? B or D?

Does the hook reference values based on the closure created on component execution or does React do some voodoo where it only keeps the updated value for values passed to the dependencies array?

From the docs:

The array of dependencies is not passed as arguments to the callback. Conceptually, though, that’s what they represent: every value referenced inside the callback should also appear in the dependencies array.

UPDATE:

After asking the question I fell unto this article, by Dan Abramov:

https://overreacted.io/a-complete-guide-to-useeffect/

I suggest everyone to read it.

答:
React hooks rely heavily on closures to make use of values. The values that are referenced within the hook will be the values that were present in the closure of useEffect when it was last called.

For instance, in your example if props.propOne is changed and in the subsequent render props.propTwo is changed, the value of props.propTwo inside the useEffect callback will the previous value since useEffect is not executed when props.propTwo changes.

If however, you are updating props.propOne and props.propTwo together, then the value inside useEffect hook will be the updated one.

Considering your case where the props.propOne and props.propTwo are changed together and trigger a render, the value of props.propTwo will be D inside useEffect callback

Body:
Say I have this component, with  the following hook:

function SomeComponent(props) {
useEffect(
    () => {
        //....code
        if (props.propOne === ....) { .... }
        // ...code
        if (props.propTwo === ....) { .... }
    },
    [props.propOne]
)

return <Something />

}

The above hook will run

once on the first time the component code gets executed

every time the value of props.propOne changes

Notice however that the hook callback also makes a reference to pros.propTwo, without actually having it passed to the dependencies array.

While props.propTwo will never factor in whether the hooks gets re-executed, what happens to the value of it that the hook callback references inside its body?

for example

During initial component rendering props.propOne === A and props.propTwo === B

The hook gets executed and references values A and B

During a subsequent rendering props.propOne === C and props.propTwo === D

The hook gets re-executed, since props.propOne changed. It references value C for the props.propOne but what does it reference for the props.propTwo value? B or D?

Does the hook reference values based on the closure created on component execution or does React do some voodoo where it only keeps the updated value for values passed to the dependencies array?

From the docs:

The array of dependencies is not passed as arguments to the callback. Conceptually, though, that’s what they represent: every value referenced inside the callback should also appear in the dependencies array.

UPDATE:

After asking the question I fell unto this article, by Dan Abramov:

https://overreacted.io/a-complete-guide-to-useeffect/

I suggest everyone to read it.


问:
SQL JOIN with and
Some devs use JOIN and AND in this sql

```<code>SELECT * FROM A LEFT JOIN B
ON A.id = B.id AND B.date_begin < '2019' AND B.date_end > '2018'
WHERE B.group IN (..)
</code>```

Which yield a different result if moving the condition in where part

```<code>SELECT * FROM A LEFT JOIN B
ON A.id = B.id
WHERE B.group IN (..)
AND B.date_begin < '2019' AND B.date_end > '2018'
</code>```

Why and how does the SQL is interpreted?

答: You can do both things but with the clause in the join you will have a more structured query. It doesn't matter if you have a small query but with around 50 or more you loose the focus. I can recommend to use the AND instead of plenty of where conditions.</p>

Title: SQL JOIN with and

Body:
Some devs use JOIN and AND in this sql

SELECT * FROM A LEFT JOIN B
ON A.id = B.id AND B.date_begin < '2019' AND B.date_end > '2018'
WHERE B.group IN (..)

Which yield a different result if moving the condition in where part

SELECT * FROM A LEFT JOIN B
ON A.id = B.id
WHERE B.group IN (..)
AND B.date_begin < '2019' AND B.date_end > '2018'

Why and how does the SQL is interpreted?


问:
I am getting undefined is not an object (evaluating 'this.props.navigation.navigate')
```<code>firebase.notifications().onNotificationOpened((notificationOpen) => {
const { notification } = notificationOpen;
notification.android.setChannelId('notificationId');
this.props.navigation.navigate("LoginScreen");});
</code>```

I am facing issues of undefined is not an object (evaluating 'navigation.navigate') while clicking on firebase notification in react native

答:
Without any futher informations, the error is clear. You're trying to get a property of your content called navigation. But, in this context, it's not defined or not accessible.

To get the content of your property, make sure it's defined clearly in your content and accessible inside of your function .

Then you should be able to use the function navigate('LoginScreen') related to your property.

Body:
firebase.notifications().onNotificationOpened((notificationOpen) => {
const { notification } = notificationOpen;
notification.android.setChannelId('notificationId');
this.props.navigation.navigate("LoginScreen");});

I am facing issues of undefined is not an object (evaluating 'navigation.navigate') while clicking on firebase notification in react native


问:
Covert Values to Int
I'm creating an Android App that takes data from a ble device.
I have only a problem, the data that my ble device give to me are like:

Accelerometer + Gyroscope: "zLAi/wD/SpwiAOv/VwBnAML/xQE="

Pressure: "bgBvAHAAcQByAA="

Battery: "ChYKARoA"

While should have number, how can I convert these values??

For Example I have this function to manageCharacteristics

```<code>async setupNotifications(device) {
    for (const id in this.AccGyrMg) {

      const service = this.serviceUUID(id)
      const characteristicAccGyrMg = this.notifyUUIDAccGyrMg(id)

      device.monitorCharacteristicForService(service, characteristicAccGyrMg, (error, characteristic) => {
        if (error) {
          this.error(error.message)
          return
        }
        this.updateValue(characteristic.uuid, characteristic.value)
      })
    }
</code>```

And this is updateValue:

```<code>updateValue(key, value) {
  //        const readebleData = base64.decode(value);
    this.setState({ values: { ...this.state.values, [key]: value } })
  }
</code>```

I have try to use base64.decode(value) but the values that I receive are not number :/

答:
Apparently those values are hex encoded into base64. I could not find any documentation, but it's based on this Github issue: monitorCharacteristicForService value is fragmented

I used this tool to convert your base64 to hex:

Accelerometer + Gyroscope: "zLAi/wD/SpwiAOv/VwBnAML/xQE="

cc b0 22 ff 00 ff 4a 9c 22 00 eb ff 57 00 67 00 c2 ff c5 01

Pressure: "bgBvAHAAcQByAA="

6e 00 6f 00 70 00 71 00 72 00

Battery: "ChYKARoA"

0a 16 0a 01 1a 00

Unfortunately, without knowing the specifications for this device, it is impossible to convert these hex values to numbers. The manufacturer could have chosen from an infinite number of methods to map numbers to hex values. You will either have to find the protocol documentation or reverse engineer it.

Here are samples of how another BLE device converted numbers to hex (search for "notification consists"). You will find sections like this:

The notification consists of 6 byte:

```<code>byte 0: 02
byte 1: 01
byte 2: XY (see below)
byte 3: valve open state in % (from 0x00 to 0x64)
byte 4: undefined (battery level?)
byte 5: (temperature * 2)
</code>```

Title: Covert Values to Int

Body:
I'm creating an Android App that takes data from a ble device.
I have only a problem, the data that my ble device give to me are like:

Accelerometer + Gyroscope: "zLAi/wD/SpwiAOv/VwBnAML/xQE="

Pressure: "bgBvAHAAcQByAA="

Battery: "ChYKARoA"

While should have number, how can I convert these values??

For Example I have this function to manageCharacteristics

async setupNotifications(device) {
    for (const id in this.AccGyrMg) {

      const service = this.serviceUUID(id)
      const characteristicAccGyrMg = this.notifyUUIDAccGyrMg(id)

      device.monitorCharacteristicForService(service, characteristicAccGyrMg, (error, characteristic) => {
        if (error) {
          this.error(error.message)
          return
        }
        this.updateValue(characteristic.uuid, characteristic.value)
      })
    }

And this is updateValue:

updateValue(key, value) {
  //        const readebleData = base64.decode(value);
    this.setState({ values: { ...this.state.values, [key]: value } })
  }

I have try to use base64.decode(value) but the values that I receive are not number :/

Body:
Apparently those values are hex encoded into base64. I could not find any documentation, but it's based on this Github issue: monitorCharacteristicForService value is fragmented

I used this tool to convert your base64 to hex:

Accelerometer + Gyroscope: "zLAi/wD/SpwiAOv/VwBnAML/xQE="

cc b0 22 ff 00 ff 4a 9c 22 00 eb ff 57 00 67 00 c2 ff c5 01

Pressure: "bgBvAHAAcQByAA="

6e 00 6f 00 70 00 71 00 72 00

Battery: "ChYKARoA"

0a 16 0a 01 1a 00

Unfortunately, without knowing the specifications for this device, it is impossible to convert these hex values to numbers. The manufacturer could have chosen from an infinite number of methods to map numbers to hex values. You will either have to find the protocol documentation or reverse engineer it.

Here are samples of how another BLE device converted numbers to hex (search for "notification consists"). You will find sections like this:

The notification consists of 6 byte:

byte 0: 02
byte 1: 01
byte 2: XY (see below)
byte 3: valve open state in % (from 0x00 to 0x64)
byte 4: undefined (battery level?)
byte 5: (temperature * 2)


问:
How to remove first chracter from the string and store the same into new column in Pandas?
I have a column name called Student name and each row has four or five student names -- like this John mills, Tim Harry, Alex win, Kate marry... I want to take the first two student names and store into a new column called Student 1 and Student 2. Names have been separated from comma.

I created a function and i can able to extract first student name . result storing into my dataframe called student_0

```<code>def find_student(df2):
for i in range(2):
df2[f"student name_{i}"] = [x.split(',')[i] for x in df2["student name"]]
return df2
</code>```

```<code>new_df = find_student(df2)
</code>```

df2 is my dataframe name

I AM NOT GETTING SECOND STUDENT NAME. PLEASE ADVISE

答:
try this </p>

```<code>def find_student(df2):
    for i in range(2):
        df2[f"student name_{i}"] = pd.Series(map(lambda x: x.split(',')[i], df2["student name"]))
return df2
</code>```

Body:
I have a column name called Student name and each row has four or five student names -- like this John mills, Tim Harry, Alex win, Kate marry... I want to take the first two student names and store into a new column called Student 1 and Student 2. Names have been separated from comma.

I created a function and i can able to extract first student name . result storing into my dataframe called student_0

def find_student(df2):
for i in range(2):
df2[f"student name_{i}"] = [x.split(',')[i] for x in df2["student name"]]
return df2

new_df = find_student(df2)

df2 is my dataframe name

I AM NOT GETTING SECOND STUDENT NAME. PLEASE ADVISE

Body:
try this

def find_student(df2):
    for i in range(2):
        df2[f"student name_{i}"] = pd.Series(map(lambda x: x.split(',')[i], df2["student name"]))
return df2


问:
set value to
 tag and update the prop on:click $event vue.js
I am trying to update props child to parent with on:click $event.

I passed the data and $event to parent to child, like below.
in parent;

```<code><v-filter
    :sortTypePrice="sortTypePrice"
    :sortTypeNewest="sortTypeNewest"
    v-on:updatePrice="sortTypePrice = $event"
    v-on:updateDate="sortTypeNewest = $event"
/>

data(){
    return {
        sortTypePrice: "",
        sortTypeNewest: "",
    }
 }

computed: {
  filterArticles(){

      let filteredStates = this.api.filter((article) => {
          return (this.keyword.length === 0 || article.address.includes(this.keyword))
      });

      if(this.sortTypePrice == "price") {
          filteredStates = filteredStates.sort((prev, curr) => prev.price1 - curr.price1);
      }
      if(this.sortTypeNewest == 'created_at') {
          filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
      }

      return filteredStates;
  },
}
</code>```

I got the props and set the $event update. But my @click is not working.

in child

```<code><ul>
  <li v-model="sortPrice" @click="updatePrice" :value="price">lowest</li>
  <li v-model="sortDate" @click="updateDate" :value="created_at">newest</li>
</ul>

props:["sortTypePrice", "sortTypeNewest"],
name: "controller",
data(){
    return {
        price: "price",
        created_at: "created_at",
        sortPrice:this.sortTypePrice,
        sortDate:this.sortTypeNewest,
    };
},
methods: {
    updatePrice(e){
        this.$emit("updatePrice", e.target.value)
    },
    updateDate(e){
        this.$emit("updateDate", e.target.value)
    }
}
</code>```

I think, I am using very wrong way to do this. if it so, what is the right way to achieve this?

答:
You should not set both :value and v-model. You can try

```<code><ul>
  <li @click="$emit('updatePrice', 'price')" :value="price">lowest</li>
  <li @click="$emit('updateDate', 'created_at')" :value="created_at">newest</li>
</ul>
</code>```

Title: set value to <li> tag and update the prop on:click $event vue.js

Body:
I am trying to update props child to parent with on:click $event.

I passed the data and $event to parent to child, like below.
in parent;

<v-filter
    :sortTypePrice="sortTypePrice"
    :sortTypeNewest="sortTypeNewest"
    v-on:updatePrice="sortTypePrice = $event"
    v-on:updateDate="sortTypeNewest = $event"
/>

data(){
    return {
        sortTypePrice: "",
        sortTypeNewest: "",
    }
 }

computed: {
  filterArticles(){

      let filteredStates = this.api.filter((article) => {
          return (this.keyword.length === 0 || article.address.includes(this.keyword))
      });

      if(this.sortTypePrice == "price") {
          filteredStates = filteredStates.sort((prev, curr) => prev.price1 - curr.price1);
      }
      if(this.sortTypeNewest == 'created_at') {
          filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
      }

      return filteredStates;
  },
}

I got the props and set the $event update. But my @click is not working.

in child

lowest

newest

props:["sortTypePrice", "sortTypeNewest"],
name: "controller",
data(){
    return {
        price: "price",
        created_at: "created_at",
        sortPrice:this.sortTypePrice,
        sortDate:this.sortTypeNewest,
    };
},
methods: {
    updatePrice(e){
        this.$emit("updatePrice", e.target.value)
    },
    updateDate(e){
        this.$emit("updateDate", e.target.value)
    }
}

I think, I am using very wrong way to do this. if it so, what is the right way to achieve this?

Body:
You should not set both :value and v-model. You can try

<ul>
  <li @click="$emit('updatePrice', 'price')" :value="price">lowest</li>
  <li @click="$emit('updateDate', 'created_at')" :value="created_at">newest</li>
</ul>


问:
How to make specific lists value (tcl)
I want to make specific repetitive lists.
XA0 XB0 XC0 XD0 XD1 XC1 XB1 XA1 XA2 XB2 XC2 XD2 XD3 XC3 XB3 XA3.....
As you see, A-B-C-D-D-C-B-A ... what is repetitive patterns & counts are also expanded.

Experts! Please help me!!

答:
OK, flipping the pattern makes this a little trickier. But we have lreverse so it's not too difficult; we just need to flip the list of letters after each round of iterating through it.

```<code>set resultList {}
set letters {A B C D}
for {set i 0} {$i <= 3} {incr i} {
    foreach ch $letters {
        lappend resultList "X${ch}${i}"
    }
    set letters [lreverse $letters]
}
puts $resultList
# XA0 XB0 XC0 XD0 XD1 XC1 XB1 XA1 XA2 XB2 XC2 XD2 XD3 XC3 XB3 XA3
</code>```

Title: How to make specific lists value (tcl)

Body:
OK, flipping the pattern makes this a little trickier. But we have lreverse so it's not too difficult; we just need to flip the list of letters after each round of iterating through it.

set resultList {}
set letters {A B C D}
for {set i 0} {$i <= 3} {incr i} {
    foreach ch $letters {
        lappend resultList "X${ch}${i}"
    }
    set letters [lreverse $letters]
}
puts $resultList
# XA0 XB0 XC0 XD0 XD1 XC1 XB1 XA1 XA2 XB2 XC2 XD2 XD3 XC3 XB3 XA3


问:
Change Inet root folder for iis 7
I am facing a very exasperating challenge. I have to deploy my ASP.NET MVC 3 application in a production server.

In this production server I have two drives C: and D:. I am authorized to put my websites in the D:\data folder and I cannot use the C:.

Unfortunately IIS creates the Inet directory in C: and apparently there is no way in the IIS manager to change this destination. Is there any way to change this directory? In the case this is not possible, is there any way to solve this problem in an alternative way?

Consider that I have my code stored in the D: of the production server and I have Visual Studio installed in it.

Thanks

Francesco

答: You can set the root folder of the website to whatever location you want. And if you create a virtual directory and host this MVC application inside the directory it could even be outside of the root of the web site:

Title: Change Inet root folder for iis 7


问:
How I remove controllers name from the route (URL)?
How I remove controllers name from the route (URL)?

```<code>Example :

Existing Url: https://localhost:3000/home/contact_us

I want this URL https://localhost:3000/contact_us
</code>```

so how can I do that?

Route.rb

get "home/contact_us", to: "home#contact_us", as: :contact_us

答:
get "contact_us", to: "home#contact_us"

```<code>as: :contact_us # not required
</code>```

Body:
How I remove controllers name from the route (URL)?

Example :

Existing Url: https://localhost:3000/home/contact_us

I want this URL https://localhost:3000/contact_us

so how can I do that?

Route.rb

get "home/contact_us", to: "home#contact_us", as: :contact_us

Body:
get "contact_us", to: "home#contact_us"

as: :contact_us # not required


问:
Ionic 4 cordova build
When try to build android app on ionic 4 using cordova build getting an error
Target 'ionic-cordova-build' could not be found in project 'app'.

ionic cordova build android

```<code>Target 'ionic-cordova-build' could not be found in project 'app'.
Error: Target 'ionic-cordova-build' could not be found in project 'app'.
    at Architect._getProjectTarget (F:\Calibre\ionic4-start-theme-master\node_modules\@angular-devkit\architect\src\architect.js:90:19)
    at Architect.getBuilderConfiguration (F:\Calibre\ionic4-start-theme-master\node_modules\@angular-devkit\architect\src\architect.js:97:29)
</code>```

答: Run npm install in command line within your project directory (the one with package.json in), sounds like you haven't downloaded your node modules.

Title: Ionic 4 cordova build

Body:
When try to build android app on ionic 4 using cordova build getting an error
Target 'ionic-cordova-build' could not be found in project 'app'.

ionic cordova build android

Target 'ionic-cordova-build' could not be found in project 'app'.
Error: Target 'ionic-cordova-build' could not be found in project 'app'.
    at Architect._getProjectTarget (F:\Calibre\ionic4-start-theme-master\node_modules\@angular-devkit\architect\src\architect.js:90:19)
    at Architect.getBuilderConfiguration (F:\Calibre\ionic4-start-theme-master\node_modules\@angular-devkit\architect\src\architect.js:97:29)


问:
how to remove single quotes inside BETWEEN condition cakephp
I m trying to separated single quote from the values inside BETWEEN condition in cakephp 2 but it always gets values with single quotes like BETWEEN '2' and '34' .
here is my code:

```<code>$ref_no1 = $this->request->data['Lead']['ref_no1'];
$ref_no2 = $this->request->data['Lead']['ref_no2'];

$customerHo = $this-> Customer -> find('all',array(
'order' => array('Customer.customer_name' => 'asc'),
'joins'=>array(
array('table'=>'leads','alias'=>'Lead','type'=>'LEFT','foreignKey'=>false,'conditions'=>array('Customer.customer_id = Lead.customer_id')),
),
'fields'=>'Customer.*,Lead.*',
'conditions' => array(
'Customer.status' => 'active','Customer.customer_id Like'=>'S%',
'Customer.company_id'=>$company_id,
'AND' => array(
array('Lead.ref_no BETWEEN ? and ?' => array($ref_no1,$ref_no2) ),
),
)));
</code>```

I am getting output like :

```<code>SELECT `Customer`.*, `Lead`.*
FROM `customers` AS `Customer`
LEFT JOIN `timezip_db_demo`.`leads` AS `Lead` ON (`Customer`.`customer_id` = `Lead`.`customer_id`)
WHERE  `Customer`.`customer_id` Like 'S%' AND
`Lead`.`ref_no` BETWEEN '2' and '34'
ORDER BY `Customer`.`customer_name` asc
</code>```

Expected output :

```<code>SELECT `Customer`.*, `Lead`.*
FROM `customers` AS `Customer`
LEFT JOIN `timezip_db_demo`.`leads` AS `Lead` ON (`Customer`.`customer_id` = `Lead`.`customer_id`)
WHERE  `Customer`.`customer_id` Like 'S%' AND
`Lead`.`ref_no` BETWEEN 2 and 34
ORDER BY `Customer`.`customer_name` asc
</code>```

答:
you can convert that string into integer, i hope it will work</p>

```<code> array((int)$ref_no1,(int)$ref_no2)
</code>```

Body:
I m trying to separated single quote from the values inside BETWEEN condition in cakephp 2 but it always gets values with single quotes like BETWEEN '2' and '34' .
here is my code:

$ref_no1 = $this->request->data['Lead']['ref_no1'];
$ref_no2 = $this->request->data['Lead']['ref_no2'];

$customerHo = $this-> Customer -> find('all',array(
'order' => array('Customer.customer_name' => 'asc'),
'joins'=>array(
array('table'=>'leads','alias'=>'Lead','type'=>'LEFT','foreignKey'=>false,'conditions'=>array('Customer.customer_id = Lead.customer_id')),
),
'fields'=>'Customer.*,Lead.*',
'conditions' => array(
'Customer.status' => 'active','Customer.customer_id Like'=>'S%',
'Customer.company_id'=>$company_id,
'AND' => array(
array('Lead.ref_no BETWEEN ? and ?' => array($ref_no1,$ref_no2) ),
),
)));

I am getting output like :

SELECT `Customer`.*, `Lead`.*
FROM `customers` AS `Customer`
LEFT JOIN `timezip_db_demo`.`leads` AS `Lead` ON (`Customer`.`customer_id` = `Lead`.`customer_id`)
WHERE  `Customer`.`customer_id` Like 'S%' AND
`Lead`.`ref_no` BETWEEN '2' and '34'
ORDER BY `Customer`.`customer_name` asc

Expected output :

SELECT `Customer`.*, `Lead`.*
FROM `customers` AS `Customer`
LEFT JOIN `timezip_db_demo`.`leads` AS `Lead` ON (`Customer`.`customer_id` = `Lead`.`customer_id`)
WHERE  `Customer`.`customer_id` Like 'S%' AND
`Lead`.`ref_no` BETWEEN 2 and 34
ORDER BY `Customer`.`customer_name` asc

Body:
you can convert that string into integer, i hope it will work

 array((int)$ref_no1,(int)$ref_no2)


问:
Improve the cyclomatic complexity code for if-else statements
I have a block of if-else statements in a method for which I am getting cyclomatic complexity issue. I have tried using switch statement for this but still the issue remains.</p>

```<code>if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS)) {
    method1()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_PFEI_ERRORS)) {
    method2()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_RFAMP_ERRORS)) {
    method3()...
} and so on...

public static void method1(IOutputWriter writer, String fileName, InputStream fileInputStream) throws IOException {
        //logic for the method
    }
</code>```

答:
You can solve this via Java 8 approach using Predicate & Function functional interfaces. You have to put all the conditions through predicates and in Function, you can add implementation which needs to be executed when condition matches.

```<code>Map<Predicate,Function<String,String>> map = new HashMap<>();

    Predicate<String> p = (fileName)->fileName.startsWith(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS);

  Function<String,String> method = (input)->{ return "output";};

   map.put(p,method);
    Optional<String> result =
    map.entrySet()
    .stream()
    .filter(entry->entry.getKey().test(fileName))
    .map(entry->entry.getValue().apply())
    .findFirst();
</code>```

OR

```<code>  map.entrySet()
    .stream()
    .filter(entry->entry.getKey().test(fileName))
    .forEach(entry->entry.getValue().apply());
</code>```

Body:
I have a block of if-else statements in a method for which I am getting cyclomatic complexity issue. I have tried using switch statement for this but still the issue remains.

if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS)) {
    method1()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_PFEI_ERRORS)) {
    method2()...
} else if (fileName.startsWith(HwErrorsEtlConstants.MR_RAW_RFAMP_ERRORS)) {
    method3()...
} and so on...

public static void method1(IOutputWriter writer, String fileName, InputStream fileInputStream) throws IOException {
        //logic for the method
    }

Body:
You can solve this via Java 8 approach using Predicate & Function functional interfaces. You have to put all the conditions through predicates and in Function, you can add implementation which needs to be executed when condition matches.

Map<Predicate,Function<String,String>> map = new HashMap<>();

    Predicate<String> p = (fileName)->fileName.startsWith(HwErrorsEtlConstants.MR_RAW_GRADIENT_ERRORS);

  Function<String,String> method = (input)->{ return "output";};

   map.put(p,method);
    Optional<String> result =
    map.entrySet()
    .stream()
    .filter(entry->entry.getKey().test(fileName))
    .map(entry->entry.getValue().apply())
    .findFirst();

OR

  map.entrySet()
    .stream()
    .filter(entry->entry.getKey().test(fileName))
    .forEach(entry->entry.getValue().apply());


问:
Mutually exclusive A/B tests with Firebase Remote Config
I wanted to perform two A/B tests on an app using Firebase A/B Testing with Remote Config.

The problem is that the two tests audiences should be mutually exclusive. Forming part of both experiments might pollute the results.

I've thought in setting a Firebase Analytics user property when the user enters in the Experiment 1 and excluding this property value from Experiment 2 audience, but I'm afraid that the user enters in both experiments simultaneously when fetching the Remote Config values.

Is there a better solution for preventing the user from entering on both experiments?

答: It should be able to run mutually exclusive A/B testing experiments in parallel leveraging "activation event", however, it needs extra work to maintain some states on the client side.</p>


问:
Overwrite repository definition in gradle subproject
Imagine you have a gradle build with a gradle subproject.
This subproject has some applied script plugin which define their own repositories like this:

```<code>buildscript {
    repositories {
        //jcenter()
        maven {
            url 'https://example.com/plugins.gradle.org/m2/'
        }
    }
    dependencies {
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
    }
}
</code>```

Now imagine you only own the main project, not the sub project (it is a git submodule).

How can you override the repository definitions of the subproject from the main project?

PS: if you need a better description of the subproject, here it is: https://github.com/docToolchain/docToolchain

Update: I've created an example to paly around with: https://github.com/rdmueller/SO56283254/blob/master/README.adoc

see the readme for more details

答:
I believe I have a solution for the scenario described in the question (but note the caveat below!). You can put something like the following into your settings.gradle file of the root project:

```<code>gradle.allprojects { project ->
    if (project.path == ':subproject') {
        project.buildscript.repositories { repos ->
            all { repo ->
                // filtering by repo name here; you could certainly also use
                // the URL or other properties
                if (repo.name == 'maven') {
                    remove repo
                    // TODO replace with the repo you need here:
                    mavenCentral()
                }
            }
        }
    }
}
</code>```

As M.Ricciuti’s answer says, the caveat is that this won’t work for buildscript repositories in script plugins like the one you apply to the subproject of your sample GitHub project (apply from: 'scripts/AsciiDocBasics.gradle').

Body:
Imagine you have a gradle build with a gradle subproject.
This subproject has some applied script plugin which define their own repositories like this:

buildscript {
    repositories {
        //jcenter()
        maven {
            url 'https://example.com/plugins.gradle.org/m2/'
        }
    }
    dependencies {
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
    }
}

Now imagine you only own the main project, not the sub project (it is a git submodule).

How can you override the repository definitions of the subproject from the main project?

PS: if you need a better description of the subproject, here it is: https://github.com/docToolchain/docToolchain

Update: I've created an example to paly around with: https://github.com/rdmueller/SO56283254/blob/master/README.adoc

see the readme for more details

Body:
I believe I have a solution for the scenario described in the question (but note the caveat below!). You can put something like the following into your settings.gradle file of the root project:

gradle.allprojects { project ->
    if (project.path == ':subproject') {
        project.buildscript.repositories { repos ->
            all { repo ->
                // filtering by repo name here; you could certainly also use
                // the URL or other properties
                if (repo.name == 'maven') {
                    remove repo
                    // TODO replace with the repo you need here:
                    mavenCentral()
                }
            }
        }
    }
}

As M.Ricciuti’s answer says, the caveat is that this won’t work for buildscript repositories in script plugins like the one you apply to the subproject of your sample GitHub project (apply from: 'scripts/AsciiDocBasics.gradle').


问:
How to handle shifting height when using translate3d with react-spring?
I'm trying to animate from/ to another component when I press a button. I am using useTransition from react-spring. When doing that, the animation works, however, my height shifts when the animation is ongoing.

I've tried putting different positions on the animated.div (from react-spring) and setting a fixed height on it. But nothing seems to work.

// The state that keeps track on the current component
const [index, setIndex] = useState(0);

// My function that updates my state
const onClick = useCallback(() => setIndex(state => (state === 0 ? 1 : 0)), []);

// The transition I'm using
const transitions = useTransition(index, p => p, {
    from: {
        opacity: 0,
        transform: index === 0 ? "translate3d(-100%,0,0)" : "translate3d(100%,0,0)"
    },
    enter: { opacity: 1, transform: "translate3d(0%,0,0)" },
    leave: {
        opacity: 0,
        transform: index === 0 ? "translate3d(50%,0,0)" : "translate3d(-50%,0,0)"
    }
});

// My components
const pages = [
    ({ style }) => <animated.div style={style}>1</animated.div>,
    ({ style }) => <animated.div style={style}>2</animated.div>
]

// How I'm rendering out the component
{transitions.map(({ item, props, key }) => {
    const Page = pages[item];
    return <Page key={key} style={props} />;
})}
```

The animation works, however the height shifts. I've made a small codesandbox that demonstrates it here: https://codesandbox.io/s/dry-thunder-ydkg8

But in my actual code, my height looks like this: https://youtu.be/7cGLOK7fCco

答:
You need to use position:absolute on the two elements to avoid that shift (and add a position:relative on one of the parent container) -(see the updated codesandbox) :

```<code>const pages = [
    ({ style }) => (
      <animated.div
        style={{
          ...style,
          position: "absolute",
          top: "0",
          backgroundColor: "red"
        }}
      >
        First page
      </animated.div>
    ),
    ({ style }) => (
      <animated.div
        style={{
          ...style,
          position: "absolute",
          top: "0",
          backgroundColor: "blue"
        }}
      >
        Second page
      </animated.div>
    )
  ];

</code>```

Body:
I'm trying to animate from/ to another component when I press a button. I am using useTransition from react-spring. When doing that, the animation works, however, my height shifts when the animation is ongoing.

I've tried putting different positions on the animated.div (from react-spring) and setting a fixed height on it. But nothing seems to work.

// The state that keeps track on the current component
const [index, setIndex] = useState(0);

// My function that updates my state
const onClick = useCallback(() => setIndex(state => (state === 0 ? 1 : 0)), []);

// The transition I'm using
const transitions = useTransition(index, p => p, {
    from: {
        opacity: 0,
        transform: index === 0 ? "translate3d(-100%,0,0)" : "translate3d(100%,0,0)"
    },
    enter: { opacity: 1, transform: "translate3d(0%,0,0)" },
    leave: {
        opacity: 0,
        transform: index === 0 ? "translate3d(50%,0,0)" : "translate3d(-50%,0,0)"
    }
});

// My components
const pages = [
    ({ style }) => <animated.div style={style}>1</animated.div>,
    ({ style }) => <animated.div style={style}>2</animated.div>
]

// How I'm rendering out the component
{transitions.map(({ item, props, key }) => {
    const Page = pages[item];
    return <Page key={key} style={props} />;
})}

The animation works, however the height shifts. I've made a small codesandbox that demonstrates it here: https://codesandbox.io/s/dry-thunder-ydkg8

But in my actual code, my height looks like this: https://youtu.be/7cGLOK7fCco

Body:
You need to use position:absolute on the two elements to avoid that shift (and add a position:relative on one of the parent container) -(see the updated codesandbox) :

const pages = [
    ({ style }) => (
      <animated.div
        style={{
          ...style,
          position: "absolute",
          top: "0",
          backgroundColor: "red"
        }}
      >
        First page
      </animated.div>
    ),
    ({ style }) => (
      <animated.div
        style={{
          ...style,
          position: "absolute",
          top: "0",
          backgroundColor: "blue"
        }}
      >
        Second page
      </animated.div>
    )
  ];


问:
Do you need to fclose() both files after freopen()?
I'm writing a code which takes one file and saves it into another with a different name - however, I am not sure whether or not I need to fclose both files or not?</p>

```<code>FILE *logfile = fopen("log.txt", "a+");
while(1) {
    char filename[500];
    char logline[512];
    char channel[512];

    //Do stuff

    sprintf(filename, "%s.log.txt", channel);
    freopen(filename, "a+", logfile);
    log_to_file(logline, logfile);
}
</code>```

答:
From the man page

The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. [...]

So, you don't need to close the previous stream explicitly, once done usage, just close the recent stream.

Body:
I'm writing a code which takes one file and saves it into another with a different name - however, I am not sure whether or not I need to fclose both files or not?

FILE *logfile = fopen("log.txt", "a+");
while(1) {
    char filename[500];
    char logline[512];
    char channel[512];

    //Do stuff

    sprintf(filename, "%s.log.txt", channel);
    freopen(filename, "a+", logfile);
    log_to_file(logline, logfile);
}


问:
Undefined variable: data in laravel
Undefined variable: data error occure when i want to display data from database.

Here is my code

Controller

```<code>public function filter(Request $request)
{

    $data = Trial::where('zipcode',$request->zipcode)->select('lat','lng')->first();
    $lat = $data->lat;
    $lng = $data->lng;
    $distance = 5 ;// Diatanse in kms
    $query = Trial::getByDistance($lat, $lng, $distance);

    $ids = [];
    //Extract the id's
    if(!empty($query)) {
        foreach($query as $q)
        {
            array_push($ids, $q->id);
        }
    }

    // Now write final query
    if(!empty($ids)){
        $results = DB::table('trial')->whereIn( 'id', $ids)->where('zipcode');
    }

    return view('search.searchhome',compact('data',$data));
    dd($data);

}
</code>```

Blade

```<code><p>
@foreach($data as $dat)
    {{$dat->zipcode}}
@endforeach
</p>
</code>```

答:
Change in controller

```<code>public function filter(Request $request)
{

    $data = Trial::where('zipcode',$request->zipcode)->select('lat','lng')->first();
    $lat = $data->lat;
    $lng = $data->lng;
    $distance = 5 ;// Diatanse in kms
    $query = Trial::getByDistance($lat, $lng, $distance);

    $ids = [];
    //Extract the id's
    if(!empty($query)) {
        foreach($query as $q)
        {
            array_push($ids, $q->id);
        }
    }

    // Now write final query
    if(!empty($ids)){
        $results = DB::table('trial')->whereIn( 'id', $ids)->get();
    }

    return view('search.searchhome',['data' => $results]);
}
</code>```

Change in blade

```<code><p>
@foreach($data as $dat)
    {{$dat->zipcode}}
@endforeach
</p>
</code>```

Title: Undefined variable: data in laravel

Body:
Undefined variable: data error occure when i want to display data from database.

Here is my code

Controller

public function filter(Request $request)
{

    $data = Trial::where('zipcode',$request->zipcode)->select('lat','lng')->first();
    $lat = $data->lat;
    $lng = $data->lng;
    $distance = 5 ;// Diatanse in kms
    $query = Trial::getByDistance($lat, $lng, $distance);

    $ids = [];
    //Extract the id's
    if(!empty($query)) {
        foreach($query as $q)
        {
            array_push($ids, $q->id);
        }
    }

    // Now write final query
    if(!empty($ids)){
        $results = DB::table('trial')->whereIn( 'id', $ids)->where('zipcode');
    }

    return view('search.searchhome',compact('data',$data));
    dd($data);

}

Blade

@foreach($data as $dat)
    {{$dat->zipcode}}
@endforeach

Body:
Change in controller

public function filter(Request $request)
{

    $data = Trial::where('zipcode',$request->zipcode)->select('lat','lng')->first();
    $lat = $data->lat;
    $lng = $data->lng;
    $distance = 5 ;// Diatanse in kms
    $query = Trial::getByDistance($lat, $lng, $distance);

    $ids = [];
    //Extract the id's
    if(!empty($query)) {
        foreach($query as $q)
        {
            array_push($ids, $q->id);
        }
    }

    // Now write final query
    if(!empty($ids)){
        $results = DB::table('trial')->whereIn( 'id', $ids)->get();
    }

    return view('search.searchhome',['data' => $results]);
}

Change in blade

<p>
@foreach($data as $dat)
    {{$dat->zipcode}}
@endforeach
</p>


问:
Can I apply a whole commit from a file created with git show?
Is there a way to create a new commit in Git, using a file which provides both the changes and the commit message, like the output from git show does?

It would be nice when the other metadata fields, like Author, AuthorDate and so on would also be taken into account.

答:
Yes, git show has a -p flag for this purpose.

```<code>git show -p abcd1234 > path/to/file.patch
</code>```

It'll generate a text file (you can open it with any text editor) with a content in the following form (mind the metadata you wanted)

```<code>commit 8aab31565962f681639d0a7b6b5b8c0d3fe6b695
Author: John Doe <john.doe@corporation.com>
Date:   Tue May 28 17:05:01 2019 +0200

    Made some critical changes to function foo_bar

diff --git a/path/to/file b/path/to/file
index 8a443961df..5b5ad4726a 100755
--- a/path/to/file
+++ b/path/to/file
@@ -2620,6 +2620,6 @@ function foo_bar() {
 /**
  * Function documentation
  */
-function foo_bar() {
+function foo_bar() {
   someFunction("param");
 }
</code>```

then you'll be able at some future point to apply the patch elsewhere with

```<code>git checkout someBranch
git apply path/to/file.patch
</code>```

See the appropriate doc section for the details.

Body:
Yes, git show has a -p flag for this purpose.

git show -p abcd1234 > path/to/file.patch

It'll generate a text file (you can open it with any text editor) with a content in the following form (mind the metadata you wanted)

commit 8aab31565962f681639d0a7b6b5b8c0d3fe6b695
Author: John Doe <john.doe@corporation.com>
Date:   Tue May 28 17:05:01 2019 +0200

    Made some critical changes to function foo_bar

diff --git a/path/to/file b/path/to/file
index 8a443961df..5b5ad4726a 100755
--- a/path/to/file
+++ b/path/to/file
@@ -2620,6 +2620,6 @@ function foo_bar() {
 /**
  * Function documentation
  */
-function foo_bar() {
+function foo_bar() {
   someFunction("param");
 }

then you'll be able at some future point to apply the patch elsewhere with

git checkout someBranch
git apply path/to/file.patch

See the appropriate doc section for the details.


问:
Access parent project SWIFT_FLAGS/SWIFT_ACTIVE_COMPILATION_CONDITIONS from pod framework
I know it's not very right way to do things but whatever.

I have this code in my framework, and I can set up current from a project. But I prefer for it to be done without direct set up.

```<code>public extension Environment {
    static var current: Environment = {
        #if DEBUG
            return .debug
        #elseif CIT
            return .cit
        #elseif STAGING
            return .staging
        #elseif PRODUCTION
            return .production
        #elseif RELEASE
            return .release
        #else
            return .debug
        #endif
    }()
}
</code>```

答:
Here is a post_install hook that I came up using help from other similar posts.

Fill SWIFT_ACTIVE_COMPILATION_CONDITIONS in the project
and add code below to the Podfile.

Xcode 10.

```<code>post_install do |installer|

  require 'xcodeproj'
  project_path = 'Test.xcodeproj' # path to your xcode project
  project = Xcodeproj::Project.open(project_path)

  project.targets.each do |projectTarget|
    if projectTarget.name == 'Test' # name of the target in your main project containing the custom flags
      installer.pods_project.build_configurations.each do |podConfig|
        projectTarget.build_configurations.each do |projectConfig|
          if projectConfig.name == podConfig.name
            podConfig.build_settings["SWIFT_ACTIVE_COMPILATION_CONDITIONS"] ||= [projectConfig.build_settings["SWIFT_ACTIVE_COMPILATION_CONDITIONS"]]
          end
        end
      end
    end
  end

end
</code>```

Body:
I know it's not very right way to do things but whatever.

I have this code in my framework, and I can set up current from a project. But I prefer for it to be done without direct set up.

public extension Environment {
    static var current: Environment = {
        #if DEBUG
            return .debug
        #elseif CIT
            return .cit
        #elseif STAGING
            return .staging
        #elseif PRODUCTION
            return .production
        #elseif RELEASE
            return .release
        #else
            return .debug
        #endif
    }()
}

Body:
Here is a post_install hook that I came up using help from other similar posts.

Fill SWIFT_ACTIVE_COMPILATION_CONDITIONS in the project
and add code below to the Podfile.

Xcode 10.

post_install do |installer|

  require 'xcodeproj'
  project_path = 'Test.xcodeproj' # path to your xcode project
  project = Xcodeproj::Project.open(project_path)

  project.targets.each do |projectTarget|
    if projectTarget.name == 'Test' # name of the target in your main project containing the custom flags
      installer.pods_project.build_configurations.each do |podConfig|
        projectTarget.build_configurations.each do |projectConfig|
          if projectConfig.name == podConfig.name
            podConfig.build_settings["SWIFT_ACTIVE_COMPILATION_CONDITIONS"] ||= [projectConfig.build_settings["SWIFT_ACTIVE_COMPILATION_CONDITIONS"]]
          end
        end
      end
    end
  end

end


问:
jQuery and AJAX Loading
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.

My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.

newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.

The code for the AJAX that loads the story and media is:

```<code>$.ajax({
  url: './scripts/storyLoader.php?storyid='+storyId,
  success: function(result){
    $('#storycontainer').hide();
    $('#loading').remove();
    $('#storycontainer').hide(0).html(result).fadeIn(1000);
    }
});
$.ajax({
  url: './scripts/mediaLoader.php?storyid='+storyId,
  success: function(result){
    $('.martefact').hide();
    $('#loading').remove();
    $('.martefact').html(result).slideDown(1000);
    }
});
</code>```

Basically, I only want the media div to slide down once the video or image has finished loading.

Thanks

答: What does your mediaLoader.php script do? Does it just check the database whether there are any media entries for the given story and if so format them properly and output them? Because currently I don't think you can slide down after the video is completely loaded, since you are embedding a vimeo video container, which handles the loading of the video itself and you have no access to it...

Title: jQuery and AJAX Loading

Body:
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.

My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.

newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.

The code for the AJAX that loads the story and media is:

$.ajax({
  url: './scripts/storyLoader.php?storyid='+storyId,
  success: function(result){
    $('#storycontainer').hide();
    $('#loading').remove();
    $('#storycontainer').hide(0).html(result).fadeIn(1000);
    }
});
$.ajax({
  url: './scripts/mediaLoader.php?storyid='+storyId,
  success: function(result){
    $('.martefact').hide();
    $('#loading').remove();
    $('.martefact').html(result).slideDown(1000);
    }
});

Basically, I only want the media div to slide down once the video or image has finished loading.

Thanks


问:
Facing error with JMeter in Non-GUI mode. Error: "Malformed option -"
I am using Jmeter(5.1.1) in Non-GUI mode and unable to execute it. It still runs fine in GUI mode but fails in Non-GUI with "Error: Malformed option -". I removed the listeners from the JMX file but it still has some HTTP Request which are disabled will that be the problem here.?
I am currently using this command in my Windows 7 machine with Java 8.

Commands:

```<code>jmeter -n -t (location: C:\Users\File.jmx) -l (location: C:\Users\Results.csv)
</code>```

Its not showing results neither updating the results.csv file, after each run its just showing "

Error: Malformed option -

" in command window. Can someone tell me what i am missing or what should i follow.?

答:
Please use it like the below:-

jmeter -n -t D:\TestScripts\script.jmx -l D:\TestScripts\scriptresults.jtl

Hope this helps.

Body:
I am using Jmeter(5.1.1) in Non-GUI mode and unable to execute it. It still runs fine in GUI mode but fails in Non-GUI with "Error: Malformed option -". I removed the listeners from the JMX file but it still has some HTTP Request which are disabled will that be the problem here.?
I am currently using this command in my Windows 7 machine with Java 8.

Commands:

jmeter -n -t (location: C:\Users\File.jmx) -l (location: C:\Users\Results.csv)

Its not showing results neither updating the results.csv file, after each run its just showing "

Error: Malformed option -

" in command window. Can someone tell me what i am missing or what should i follow.?


问:
difference between 2 dates in days saved into new column as float
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

```<code>df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])
</code>```

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

答:
Try:</p>

```<code>import numpy as np
enddates = np.asarray([pd.Timestamp(end) for end in df.end_date.values])
startdates = np.asarray([pd.Timestamp(start) for start in df.start_date.values])
df['time_diff'] = (enddates - startdates).astype("timedelta64")
</code>```

Body:
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

Body:
Try:

import numpy as np
enddates = np.asarray([pd.Timestamp(end) for end in df.end_date.values])
startdates = np.asarray([pd.Timestamp(start) for start in df.start_date.values])
df['time_diff'] = (enddates - startdates).astype("timedelta64")


问:
How to Store multilingual data in an RDBMS on cloud
I have to create an RDBMS table on Google cloud that supports multilingual data. Do we have a service on google cloud for that? CloudSQL or CloudSpanner?

This is for storing movie titles data from different countries and do some querying on the data.

I expect that I can do queries on the data that is stored. For example: Do a DISTINCT on the movie titles and it should list all different movie titles from various countries (Ex: I have chinese movie titles, Russian movie titles).

答:
In both Google Cloud SQL and Google Cloud Spanner you are able to store multilingual data and do queries with “DISTINCT” or something else. So, you choose the service that will serve your purpose in a better and more effective way.

Cloud SQL is a fully managed relation database service.

Cloud Spanner is a fully managed, scalable, relational database
  service for regional and global application data.

You can find more information about the use cases of Cloud SQL and Cloud Spanner in Google’s documentation.


问:
How to pass a TComparer<T> class to a generic type in Delphi?
I want to create a generic record with some functionality, including a search function.
To perform this search I wanted to pass a custom Comparer to compare items.
If it were a class, I could pass it in the constructor, but I want to use a record to avoid to create or free it. So, I don't have a constructor where to initialize the Comparer.

Then I decided to pass the Comparer class like a Type parameter, and when I need the comparer, create a instance of the comparer using TComparer.Default.

Well, here is the code:

```<code>TMyArray<T,C: TComparer<T>> = record
  FComparer: IComparer<T>;
  Items: TArray<T>;

  function Contains<AItem: T>: Boolean;
end;
</code>```

The problem appears when I try to use it in this way:

```<code>TMyRecord = record
  Score: Real;
  A: string;
  B: string;
end;

TMyRecordComparer = class(TComparer<TMyRecord>)
  function Compare(Left, Right: TMyRecord): Integer;
end;

TMyRecordArray = TMyArray<TMyRecord, TMyRecordComparer>;
</code>```

With this last declaration, I get this error:
E2515 Type parameter 'T' is not compatible with type 'System.Generics.Defaults.TComparer\'.

Any idea how to solve this issue?

答:
While David's answer fixes the problem with the compile error, I would actually use a different constraint:

```<code>TMyArray<T; C: class, constructor, IComparer<T>> = record
</code>```

That means C must be a class with a parameterless constructor and implement the IComparer<T> interface. That relaxes the constraint a little, as you don't have to inherit your comparer from System.Generics.Collections.TComparer<T> but only implement the needed IComparer<T> interface.

Also, fwiw, with the code posted in your question you will get a W1010 warning which means you are missing an override on your TMyRecordComparer.Compare method (and its missing const). This is needed if you inherit from TComparer<T> as that one implements IComparer<T> with a virtual abstract method.

Your idea to use .Default will also not work as that one creates a default implementation for a comparer for type T. But you want to use the custom one you specified.

So with the constraint I wrote above you then can do something like this (naive non-threadsafe implementation):

```<code>function TMyArray<T, C>.Contains<AItem>: Boolean;
begin
  if FComparer = nil then
    FComparer := C.Create;
  // ....
end;
</code>```

And last but not least, I am not sure your Contains method is correct - the way you wrote it suggests that you want to check if your array contains an element of type AItem that is of type T or a sub type (or if T is an interface type, implements T) - I would guess you meant to write

```<code>function Contains(AItem: T): Boolean;
</code>```

Body:
I want to create a generic record with some functionality, including a search function.
To perform this search I wanted to pass a custom Comparer to compare items.
If it were a class, I could pass it in the constructor, but I want to use a record to avoid to create or free it. So, I don't have a constructor where to initialize the Comparer.

Then I decided to pass the Comparer class like a Type parameter, and when I need the comparer, create a instance of the comparer using TComparer.Default.

Well, here is the code:

TMyArray<T,C: TComparer<T>> = record
  FComparer: IComparer<T>;
  Items: TArray<T>;

  function Contains<AItem: T>: Boolean;
end;

The problem appears when I try to use it in this way:

TMyRecord = record
  Score: Real;
  A: string;
  B: string;
end;

TMyRecordComparer = class(TComparer<TMyRecord>)
  function Compare(Left, Right: TMyRecord): Integer;
end;

TMyRecordArray = TMyArray<TMyRecord, TMyRecordComparer>;

With this last declaration, I get this error:
E2515 Type parameter 'T' is not compatible with type 'System.Generics.Defaults.TComparer\'.

Any idea how to solve this issue?

Body:
While David's answer fixes the problem with the compile error, I would actually use a different constraint:

TMyArray<T; C: class, constructor, IComparer<T>> = record

That means C must be a class with a parameterless constructor and implement the IComparer<T> interface. That relaxes the constraint a little, as you don't have to inherit your comparer from System.Generics.Collections.TComparer<T> but only implement the needed IComparer<T> interface.

Also, fwiw, with the code posted in your question you will get a W1010 warning which means you are missing an override on your TMyRecordComparer.Compare method (and its missing const). This is needed if you inherit from TComparer<T> as that one implements IComparer<T> with a virtual abstract method.

Your idea to use .Default will also not work as that one creates a default implementation for a comparer for type T. But you want to use the custom one you specified.

So with the constraint I wrote above you then can do something like this (naive non-threadsafe implementation):

function TMyArray<T, C>.Contains<AItem>: Boolean;
begin
  if FComparer = nil then
    FComparer := C.Create;
  // ....
end;

And last but not least, I am not sure your Contains method is correct - the way you wrote it suggests that you want to check if your array contains an element of type AItem that is of type T or a sub type (or if T is an interface type, implements T) - I would guess you meant to write

function Contains(AItem: T): Boolean;


问:
AttributeError: Can't get attribute on <module '__main__' from 'manage.py'>
```<code>def getNer(text):
    with open('chunker.pkl', 'rb') as pickle_file:
        chunker = pickle.load(pickle_file)
    return chunker.parse(pos_tag(word_tokenize(text)))
</code>```

Running this function works fine
But when I include this function in my Django Project
I get the following error

```<code>chunker = pickle.load(pickle_file)
AttributeError: Can't get attribute 'NamedEntityChunker' on <module '__main__' from 'manage.py'>
</code>```

The object being pickled is

```<code>class NamedEntityChunker(ChunkParserI):
    def __init__(self, train_sents, **kwargs):
        assert isinstance(train_sents, Iterable)

        self.feature_detector = features
        self.tagger = ClassifierBasedTagger(
            train=train_sents,
            feature_detector=features,
            **kwargs)

    def parse(self, tagged_sent):
        chunks = self.tagger.tag(tagged_sent)
        iob_triplets = [(w, t, c) for ((w, t), c) in chunks]
        return conlltags2tree(iob_triplets)
</code>```

Im using the latest version of Django and Python3

答:
I had the same error - turns out I wasn't importing the class before trying to open it. The GUI needs to know how to construct the object before being able to read it. Try:

```<code>from YourModuleName import NamedEntityChunker
</code>```

before calling your opening function.

Body:
def getNer(text):
    with open('chunker.pkl', 'rb') as pickle_file:
        chunker = pickle.load(pickle_file)
    return chunker.parse(pos_tag(word_tokenize(text)))

Running this function works fine
But when I include this function in my Django Project
I get the following error

chunker = pickle.load(pickle_file)
AttributeError: Can't get attribute 'NamedEntityChunker' on <module '__main__' from 'manage.py'>

The object being pickled is

class NamedEntityChunker(ChunkParserI):
    def __init__(self, train_sents, **kwargs):
        assert isinstance(train_sents, Iterable)

        self.feature_detector = features
        self.tagger = ClassifierBasedTagger(
            train=train_sents,
            feature_detector=features,
            **kwargs)

    def parse(self, tagged_sent):
        chunks = self.tagger.tag(tagged_sent)
        iob_triplets = [(w, t, c) for ((w, t), c) in chunks]
        return conlltags2tree(iob_triplets)

Im using the latest version of Django and Python3

Body:
I had the same error - turns out I wasn't importing the class before trying to open it. The GUI needs to know how to construct the object before being able to read it. Try:

from YourModuleName import NamedEntityChunker

before calling your opening function.


问:
How to load component on demand on react-native?
My app consists of 500+ screens and 1000+ global components. I need to load a component on demand not load a all components on first time.
For example in 'ReactJS' is code-spilting and react.lazy() concept is there for this problem.  How it is possible in react-native. How to spilt the component and code in react-native for decrease the app loading time at first time.

Thanks!

答:
use Dynamic Component Name

```<code>import React, { Component } from 'react';
import FooComponent from './foo-component';
import BarComponent from './bar-component';

class MyComponent extends Component {

components = {
    foo: FooComponent,
    bar: BarComponent
};

render() {
   const componentName='foo'
   const TagName = this.components[componentName];
   return <TagName />
}
</code>```

}

Body:
use Dynamic Component Name

import React, { Component } from 'react';
import FooComponent from './foo-component';
import BarComponent from './bar-component';

class MyComponent extends Component {

components = {
    foo: FooComponent,
    bar: BarComponent
};

render() {
   const componentName='foo'
   const TagName = this.components[componentName];
   return <TagName />
}

}


问:
Can i use a 32 Bit ODBC Driver for my 64 Bit app
I have a Win32 application that makes ODBC-Connections. We connect using SQLDriverConnect()
which displays a dialog to select the data source. In the x64-Version the Dialog shows and offers 2 different 32 Bit MS ACCESS Drivers. When i select one of these, in the 32 Bit version i would see a open file dialog to select a .mdb file. In the 64 Bit version the call to SQLDriverConnect() at this point returns with -1.

SQLError() returns: "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"

Is it in general possible to use a 32 Bit ODBC Driver from a 64-Bit executable? Why are these driver shown? As far as i can find there is no 64 Bit MS Access OBDC driver so far. What can i do?

答:
You absolutely cannot mix 32bit application and 64bit driver (or vice-versa).

Basically, an ODBC driver is, typically, a dll (windows) or a shared object (linux...) which is loaded by its parent application.

All executables, dlls, etc that share the same process space must be the same bit'ness...


问:
Format csv file with column creation in Spark scala
I have a csv file, as below

It has 6 rows with top row as header, while header read as "Students Marks"
dataframe is treating them as one columns, now i want to separate both columns with data. "student" and "marks" are separated by space.

```<code>df.show()
_______________
##Student Marks##
---------------
A   10;20;10;20
A   20;20;30;10
B   10;10;10;10
B   20;20;20;10
B   30;30;30;20
</code>```

Now i want to transform this csv table into two columns, with student and Marks, Also for every student the marks with add up, something like below

```<code>Student | Marks
A       | 30;40;40;30
B       | 60;60;60;40
</code>```

I have tried with below but it is throwing an error

```<code>df.withColumn("_tmp", split($"Students Marks","\\ ")).select($"_tmp".getItem(0).as("col1"),$"_tmp".getItem(1).as("col2")).drop("_tmp")
</code>```

答:
Three Ideas. The first one is to read the file, split it by space and then create the dataFrame:

```<code>val df = sqlContext.read
  .format("csv")
  .option("header", "true")
  .option("delimiter", " ")
  .load("your_file.csv")
</code>```

The second one is to read the file to dataframe and split it:

```<code>df.withColumn("Student", split($"Students Marks"," ").getItem(0))
  .withColumn("Marks", split($"Students Marks"," ").getItem(1))
  .drop("Students Marks")
</code>```

The last one is your solution. It should work, but when you use the select, you don't use $"_tmp", therefore, it should work without the .drop("_tmp")

```<code>df.withColumn("_tmp", split($"Students Marks"," "))
  .select($"_tmp".getItem(0).as("Student"),$"_tmp".getItem(1).as("Marks"))
</code>```

Body:
I have a csv file, as below

It has 6 rows with top row as header, while header read as "Students Marks"
dataframe is treating them as one columns, now i want to separate both columns with data. "student" and "marks" are separated by space.

df.show()
_______________
##Student Marks##
---------------
A   10;20;10;20
A   20;20;30;10
B   10;10;10;10
B   20;20;20;10
B   30;30;30;20

Now i want to transform this csv table into two columns, with student and Marks, Also for every student the marks with add up, something like below

Student | Marks
A       | 30;40;40;30
B       | 60;60;60;40

I have tried with below but it is throwing an error

df.withColumn("_tmp", split($"Students Marks","\\ ")).select($"_tmp".getItem(0).as("col1"),$"_tmp".getItem(1).as("col2")).drop("_tmp")

Body:
Three Ideas. The first one is to read the file, split it by space and then create the dataFrame:

val df = sqlContext.read
  .format("csv")
  .option("header", "true")
  .option("delimiter", " ")
  .load("your_file.csv")

The second one is to read the file to dataframe and split it:

df.withColumn("Student", split($"Students Marks"," ").getItem(0))
  .withColumn("Marks", split($"Students Marks"," ").getItem(1))
  .drop("Students Marks")

The last one is your solution. It should work, but when you use the select, you don't use $"_tmp", therefore, it should work without the .drop("_tmp")

df.withColumn("_tmp", split($"Students Marks"," "))
  .select($"_tmp".getItem(0).as("Student"),$"_tmp".getItem(1).as("Marks"))