问:
How to pass an Object Model (that has an Array of Objects Models in it) to API for insert as Params
i am new to angular, trying to make parameters of my object Model, whenever i stringify my object it makes a large string that API does not accept. What should i do..?

here is the object that i want to convert to parameters.

```<code>{
    "qaevaluationid": 1,
    "agentid": 1,
    "callerid": "1234",
    "calledon": "02/13/2020 10:38:14 AM",
    "duration": "304",
    "overallfeedback": "adasdasd",
    "isfatal": false,
    "fatalcallreasonid": "3",
    "evaluationtypeid": "1",
    "callratings": [{
        "callratingid": 1,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 8,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "7"
    }, {
        "callratingid": 2,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 9,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "6"
    }, {
        "callratingid": 3,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 10,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "8"
    }],
    "createdby": 1,
    "createdbyname": "John",
    "createdon": null,
    "modifiedby": -1,
    "modifiedbyname": null,
    "modifiedon": null,
    "is_deleted": "F"
}
</code>```

and in TypeScript i am doing like this

```<code>this.httpOptions.params = new HttpParams();

this.httpOptions.params = this.httpOptions.params.set('qaEval', JSON.stringify(qaevaluation));

return this._httpClient.post<APIResponse<QAEvaluation>>(this.myAppUrl + 'QAEvaluation/insert', { qaEval: qaevaluation }, this.httpOptions)
      .pipe(retry(1), catchError(this.errorHandler));
</code>```

getting this error

"Http failure response for
  https://localhost:44304/QAEvaluation/insert?qaEval=%7B%22qaevaluationid%22:-1,%22agentid%22:1,%22callerid%22:%221234%22,%22calledon%22:%2202/13/2020%2010:38:14%20AM%22,%22duration%22:%22304%22,%22overallfeedback%22:%22adasdasd%22,%22isfatal%22:false
  ……. This goes on and on : 404 OK"

答:
You most probably need to proxy your URLs to your api. Angular uses a specific port to host in your development environment, in your case 44304.

Check: https://angular.io/guide/build

You can use the proxying support in the webpack dev server to divert certain URLs to a backend server, by passing a file to the --proxy-config build option. For example, to divert all calls for http://localhost:4200/api to a server running on http://localhost:3000/api, take the following steps.

Create a file proxy.conf.json in your project's src/ folder.

Add the following content to the new proxy file:

```<code>{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false
  }
}
</code>```

In the CLI configuration file, angular.json, add the proxyConfig option to the serve target:

```<code>"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },
</code>```

Run by serve

Body:
i am new to angular, trying to make parameters of my object Model, whenever i stringify my object it makes a large string that API does not accept. What should i do..?

here is the object that i want to convert to parameters.

{
    "qaevaluationid": 1,
    "agentid": 1,
    "callerid": "1234",
    "calledon": "02/13/2020 10:38:14 AM",
    "duration": "304",
    "overallfeedback": "adasdasd",
    "isfatal": false,
    "fatalcallreasonid": "3",
    "evaluationtypeid": "1",
    "callratings": [{
        "callratingid": 1,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 8,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "7"
    }, {
        "callratingid": 2,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 9,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "6"
    }, {
        "callratingid": 3,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 10,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "8"
    }],
    "createdby": 1,
    "createdbyname": "John",
    "createdon": null,
    "modifiedby": -1,
    "modifiedbyname": null,
    "modifiedon": null,
    "is_deleted": "F"
}

and in TypeScript i am doing like this

this.httpOptions.params = new HttpParams();

this.httpOptions.params = this.httpOptions.params.set('qaEval', JSON.stringify(qaevaluation));

return this._httpClient.post<APIResponse<QAEvaluation>>(this.myAppUrl + 'QAEvaluation/insert', { qaEval: qaevaluation }, this.httpOptions)
      .pipe(retry(1), catchError(this.errorHandler));

getting this error

"Http failure response for
  https://localhost:44304/QAEvaluation/insert?qaEval=%7B%22qaevaluationid%22:-1,%22agentid%22:1,%22callerid%22:%221234%22,%22calledon%22:%2202/13/2020%2010:38:14%20AM%22,%22duration%22:%22304%22,%22overallfeedback%22:%22adasdasd%22,%22isfatal%22:false
  ……. This goes on and on : 404 OK"

Body:
You most probably need to proxy your URLs to your api. Angular uses a specific port to host in your development environment, in your case 44304.

Check: https://angular.io/guide/build

You can use the proxying support in the webpack dev server to divert certain URLs to a backend server, by passing a file to the --proxy-config build option. For example, to divert all calls for http://localhost:4200/api to a server running on http://localhost:3000/api, take the following steps.

Create a file proxy.conf.json in your project's src/ folder.

Add the following content to the new proxy file:

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false
  }
}

In the CLI configuration file, angular.json, add the proxyConfig option to the serve target:

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },

Run by serve


来源: stackexchange

问:
Android Studio Manifest merger error in package name

What went wrong:
Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : Package name ' ' at position AndroidManifest.xml:3:5-40 should contain at least one '.' (dot) character

package="com.example.myapplication"

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Tabeeb"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".flipview"/>
        <activity android:name=".user_row" />
        <activity android:name=".Chat" />
        <activity android:name=".doclist" />
        <activity android:name=".chat_items" />
        <activity
            android:name=".Forgotpassword"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
        <activity
            android:name=".SignUp"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
        <activity
            android:name=".Login"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:scheme="http"
                    android:host="www.tabeeb-app.com"
                    android:pathPrefix="/tabeeb" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" />
    </application>

</manifest>
</code>```

答:
in your project build gradle

```<code>dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What went wrong:
Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : Package name ' ' at position AndroidManifest.xml:3:5-40 should contain at least one '.' (dot) character

package="com.example.myapplication"

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Tabeeb"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".flipview"/>
        <activity android:name=".user_row" />
        <activity android:name=".Chat" />
        <activity android:name=".doclist" />
        <activity android:name=".chat_items" />
        <activity
            android:name=".Forgotpassword"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
        <activity
            android:name=".SignUp"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
        <activity
            android:name=".Login"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:scheme="http"
                    android:host="www.tabeeb-app.com"
                    android:pathPrefix="/tabeeb" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" />
    </application>

</manifest>

Body:
in your project build gradle

dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
}


问:
How do i get the IP address of ORACLE 11 g DATABASE on windows 10 to remotely connect to it?
I have installed oracle 11g on windows 10 f drive of my laptop. I want know the IP address of the database in order to connect to it using python? How do i find the ip address?

I tried this command:
 select sys_context('USERENV','IP_ADDRESS') from dual;
however it gives me the local host address.

i also tried
SELECT UTL_INADDR.get_host_address from dual;
however this throws an error saying network access denied by access control list

how do i find out the IP address?

答:
There is no IP Address assigned to the Oracle database. In your case, The database is installed on your own machine so the IP ADDRESS of the database is the same as the IP ADDRESS of your own machine.

```<code>select sys_context('USERENV','IP_ADDRESS') from dual;
</code>```

The aforementioned query gives the IP ADDRESS of the client which is connected to the database. I think you are misunderstood by this one - It is not the database' IP ADDRESS.

If you need the HOST_NAME of the database then you can use the following query. Note that HOAST_NAME can be used to connect to the database in the connection string or in TNS_NAMES.ora

```<code>SQL> SELECT INSTANCE_NAME, HOST_NAME FROM V$INSTANCE;

INSTANCE_N HOST_NAME
---------- --------------------
orcl       DESKTOP-0******

SQL>
</code>```

I hope it will clear all your doubts.

Cheers!!

Body:
There is no IP Address assigned to the Oracle database. In your case, The database is installed on your own machine so the IP ADDRESS of the database is the same as the IP ADDRESS of your own machine.

select sys_context('USERENV','IP_ADDRESS') from dual;

The aforementioned query gives the IP ADDRESS of the client which is connected to the database. I think you are misunderstood by this one - It is not the database' IP ADDRESS.

If you need the HOST_NAME of the database then you can use the following query. Note that HOAST_NAME can be used to connect to the database in the connection string or in TNS_NAMES.ora

SQL> SELECT INSTANCE_NAME, HOST_NAME FROM V$INSTANCE;

INSTANCE_N HOST_NAME
---------- --------------------
orcl       DESKTOP-0******

SQL>

I hope it will clear all your doubts.

Cheers!!


问:
Is it possible to update a field of type map in firestore from firebase cloud functions node.js?
When I do this in my node.js in firebase cloud functions:

```<code> var my_map = new Map();
 my_map.set('name','foo');
 my_map.set('description','helloworld');

 //update the firestore document
 let updateDocument = documentRef.update({
                some_field: my_map
                });
</code>```

I get the following error in the logs:

failed to query incidents Error: Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Value for argument "dataOrField" is not a valid Firestore document. Input is not a plain JavaScript object (found in field "some_field").

I have checked the documentation here https://firebase.google.com/docs/firestore/manage-data/add-data but the only map-related example given seems to deal with updating nested fields. I want to create a map and easily set a field in a firestore document to the contents of this map.

I am new to both node.js and firestore. Thanks in advance for the assistance.

答:
The Firestore SDK for node doesn't support ES6 Map objects.  You need to use a normal JavaScript object to build a Firestore map type field.</p>

```<code>const o = {
    name: 'foo',
    description 'helloworld'
}

documentRef.update({
    some_field: o
});
</code>```

Body:
When I do this in my node.js in firebase cloud functions:

 var my_map = new Map();
 my_map.set('name','foo');
 my_map.set('description','helloworld');

 //update the firestore document
 let updateDocument = documentRef.update({
                some_field: my_map
                });

I get the following error in the logs:

failed to query incidents Error: Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Value for argument "dataOrField" is not a valid Firestore document. Input is not a plain JavaScript object (found in field "some_field").

I have checked the documentation here https://firebase.google.com/docs/firestore/manage-data/add-data but the only map-related example given seems to deal with updating nested fields. I want to create a map and easily set a field in a firestore document to the contents of this map.

I am new to both node.js and firestore. Thanks in advance for the assistance.

Body:
The Firestore SDK for node doesn't support ES6 Map objects.  You need to use a normal JavaScript object to build a Firestore map type field.

const o = {
    name: 'foo',
    description 'helloworld'
}

documentRef.update({
    some_field: o
});


问:
How to add list [index] value to another list using method reference..?
This is my list value [a,b,c,d] ,  I tried to add list[1] index value b  to another list.. If am using lambda! am able to achieve this, any methods or ways was there to achieve same thing using method reference?.
Below code i tried

```<code>List<String> list1 = new ArrayList<>();
//list1 values are like [a,b,c,d]
List<String> list2 = new ArrayList<>();
list1.forEach(x-> {
    list2.add(x.get(1));
});
</code>```

How to achieve same thing using ::

```<code>list1.foreach(list1::add);
</code>```

答:
So if you think about the actual lambda, it is a Consumer<T> meaning that is can be reference by any method that takes a type of T and returns void. So in this example since you are looking for an something that uses a method reference I gave this. It isn't pretty but I want you to understand the point that List<T>.forEach((T t) -> {}) is just List<T>.forEach(Consumer<T>) || List<T>.forEach(<some method reference that takes type T as a single argument and returns void>)

Here is a simple example.

```<code>package org.stackoverflow.thread_safe_account;

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

public class Main {

    private static List<String> knownList = new ArrayList<>();

    public static void main(String[] args) {
        //list1 values are like [a,b,c,d]
        List<String> createdList = new ArrayList<>();
        createdList.add("this");
        createdList.add("is");
        createdList.add("zoo");
        createdList.add("stackoverflow");

        createdList.forEach(Main::itemConsumer);

        if (!knownList.get(0).equals("t")) {
            throw new RuntimeException("failed");
        }

        if (!knownList.get(1).equals("i")) {
            throw new RuntimeException("failed");
        }

        if (!knownList.get(2).equals("z")) {
            throw new RuntimeException("failed");
        }

        if (!knownList.get(3).equals("s")) {
            throw new RuntimeException("failed");
        }
    }

    public static void itemConsumer(String item) {
        if (item.length() < 1) knownList.add("");
        else knownList.add(item.substring(0, 1));
    }
}
</code>```

Body:
This is my list value [a,b,c,d] ,  I tried to add list[1] index value b  to another list.. If am using lambda! am able to achieve this, any methods or ways was there to achieve same thing using method reference?.
Below code i tried

List<String> list1 = new ArrayList<>();
//list1 values are like [a,b,c,d]
List<String> list2 = new ArrayList<>();
list1.forEach(x-> {
    list2.add(x.get(1));
});

How to achieve same thing using ::

list1.foreach(list1::add);

Body:
So if you think about the actual lambda, it is a Consumer<T> meaning that is can be reference by any method that takes a type of T and returns void. So in this example since you are looking for an something that uses a method reference I gave this. It isn't pretty but I want you to understand the point that List<T>.forEach((T t) -> {}) is just List<T>.forEach(Consumer<T>) || List<T>.forEach(<some method reference that takes type T as a single argument and returns void>)

Here is a simple example.

package org.stackoverflow.thread_safe_account;

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

public class Main {

    private static List<String> knownList = new ArrayList<>();

    public static void main(String[] args) {
        //list1 values are like [a,b,c,d]
        List<String> createdList = new ArrayList<>();
        createdList.add("this");
        createdList.add("is");
        createdList.add("zoo");
        createdList.add("stackoverflow");

        createdList.forEach(Main::itemConsumer);

        if (!knownList.get(0).equals("t")) {
            throw new RuntimeException("failed");
        }

        if (!knownList.get(1).equals("i")) {
            throw new RuntimeException("failed");
        }

        if (!knownList.get(2).equals("z")) {
            throw new RuntimeException("failed");
        }

        if (!knownList.get(3).equals("s")) {
            throw new RuntimeException("failed");
        }
    }

    public static void itemConsumer(String item) {
        if (item.length() < 1) knownList.add("");
        else knownList.add(item.substring(0, 1));
    }
}


问:
Adding function parameters using a single variable in jQuery
I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

```<code>function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);
</code>```

Problem demo

Thanks in advance

答:
You could pass your parameters as an array ..  </p>

```<code> function Func (a){
     alert(a[0]+' | '+a[1]);
    }
    var Parameters = new Array(0,1);
    var Function = Func;

    $('button').click(Function(Parameters));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);

Problem demo

Thanks in advance

Body:
You could pass your parameters as an array ..

 function Func (a){
     alert(a[0]+' | '+a[1]);
    }
    var Parameters = new Array(0,1);
    var Function = Func;

    $('button').click(Function(Parameters));


问:
How to force iframe to use https already embed on other https websites?
I had website without https i.e. SSL. Other websites embed the page of my website using iframe.

```<code><iframe src="http://mywebsite.com/app" ... />
</code>```

That worked fine until their website was http only. Now their website is https and does not load iframe because it is only http. Now i have added SSL.  without contacting the other website how to make iframe work on their website?

Please help.

答:
... without contacting the other website

Impossible. The browser will not even try to contact your site since it is a HTTP resource included inside HTTPS. The URL has to be changed in embedding site and this can only be done by the maintainer of the embedding site.

Body:
I had website without https i.e. SSL. Other websites embed the page of my website using iframe.

That worked fine until their website was http only. Now their website is https and does not load iframe because it is only http. Now i have added SSL.  without contacting the other website how to make iframe work on their website?

Please help.


问:
How to group GLTF element and drag and drop in 3js
Single GLTF element i can drag and drop. but group of element i can't drag. I am using following code

var loader = new THREE.GLTFLoader();
                loader.load( 'W3030/W3030.gltf', ( gltf ) => {

                    gltf.scene.traverse( function( child ) {
                        if(child.type === "Group")
                        {
                            newObject = true;
                            GLTFobjects.push(child);
                        }
                        if ( child.isMesh ) {
                            child.receiveShadow = true;
                            child.castShadow = true;
                            child.material.transparent = true;
                            child.material.opacity = 1;
                        }

                    });
                     scene.add(GLTFobjects);
                     gltf.scene.scale.set(1, 1, 1);

                });
```

答:
Hi Thanks for your support. Now i drag.
Use following code to drag multi mesh GLTF. It is Work for me.

```<code> var dragobjects =[];
 //add following code in init function
 var gltfobject = addGLTFObjectIntoScene();
 scene.add(gltfobject);

dragControls = new THREE.DragControls(dragobjects, camera, renderer.domElement);
dragControls.addEventListener('dragstart', onDragStart, false);
dragControls.addEventListener('drag', onDrag , false);
dragControls.addEventListener('dragend', onDragEnd, false);
</code>```

//end init function code
//add following function after or before init function

```<code> function drawBox(objectwidth,objectheight,objectdepth){
 var geometry, material, box;
 geometry = new THREE.BoxGeometry(objectwidth,objectheight,objectdepth);
 material = new THREE.MeshBasicMaterial({color: 0xffff00, transparent: true, opacity: 0,depthTest:false});
 box = new THREE.Mesh(geometry, material);
 dragobjects.push(box);
 box.position.set(0, 0, 0);
 return box;
};
function addGLTFObjectIntoScene(){
 group = new THREE.Group();
 var loader = new THREE.GLTFLoader();
 loader.load( 'W1230/W1230.gltf', ( gltf ) => {
    mesh = gltf.scene;
    mesh.scale.set( 30, 30, 30);
    var gltfbox = new THREE.Box3().setFromObject( mesh );
    var objectwidth = Math.floor(gltfbox.getSize().x);
    var objectheight = Math.floor(gltfbox.getSize().y);
    var objectdepth = Math.floor(gltfbox.getSize().z);
    objectwidth = objectwidth + parseInt(2);
    objectheight = objectheight + parseInt(2);
    objectdepth  = objectdepth + parseInt(1);
    mesh.position.set(0, -objectheight/2, 0);
    box  = drawBox(objectwidth,objectheight,objectdepth);
    group.add(box);
    group.name = "quadrant";
    console.log(mesh);
    box.add( mesh);
 });
 return group;
};
</code>```

Body:
Hi Thanks for your support. Now i drag.
Use following code to drag multi mesh GLTF. It is Work for me.

 var dragobjects =[];
 //add following code in init function
 var gltfobject = addGLTFObjectIntoScene();
 scene.add(gltfobject);

dragControls = new THREE.DragControls(dragobjects, camera, renderer.domElement);
dragControls.addEventListener('dragstart', onDragStart, false);
dragControls.addEventListener('drag', onDrag , false);
dragControls.addEventListener('dragend', onDragEnd, false);

//end init function code
//add following function after or before init function

 function drawBox(objectwidth,objectheight,objectdepth){
 var geometry, material, box;
 geometry = new THREE.BoxGeometry(objectwidth,objectheight,objectdepth);
 material = new THREE.MeshBasicMaterial({color: 0xffff00, transparent: true, opacity: 0,depthTest:false});
 box = new THREE.Mesh(geometry, material);
 dragobjects.push(box);
 box.position.set(0, 0, 0);
 return box;
};
function addGLTFObjectIntoScene(){
 group = new THREE.Group();
 var loader = new THREE.GLTFLoader();
 loader.load( 'W1230/W1230.gltf', ( gltf ) => {
    mesh = gltf.scene;
    mesh.scale.set( 30, 30, 30);
    var gltfbox = new THREE.Box3().setFromObject( mesh );
    var objectwidth = Math.floor(gltfbox.getSize().x);
    var objectheight = Math.floor(gltfbox.getSize().y);
    var objectdepth = Math.floor(gltfbox.getSize().z);
    objectwidth = objectwidth + parseInt(2);
    objectheight = objectheight + parseInt(2);
    objectdepth  = objectdepth + parseInt(1);
    mesh.position.set(0, -objectheight/2, 0);
    box  = drawBox(objectwidth,objectheight,objectdepth);
    group.add(box);
    group.name = "quadrant";
    console.log(mesh);
    box.add( mesh);
 });
 return group;
};


问:
How can i convert this sql query in a eloquent laravel command?
in sql query this commando do exactly i wanted:

```<code>SELECT
    v.id,
    (
        SELECT sv.status_id
        FROM status_viagem sv
        WHERE sv.viagem_id = v.id
        ORDER BY sv.created_at DESC LIMIT 1 ) AS status_id
FROM viagens v
</code>```

Here is the sql results:

But i have no idea how can i do this using Laravel eloquent

Basically, a viagem entry can has a lot of status, but i need to get each viagem and their last status entry from status_viagem table (the pivot table)

by the way viagem/viagens means travel.

My class mapping:

```<code>class Viagem extends Model
{
  ...
  public function status()
  {
        return $this->belongsToMany('App\Status')->withTimestamps();
  }
  ...
}

class Status extends Model
{

    public function viagens()
    {
        return $this->belongsToMany('App\Viagem')->withTimestamps();
    }
}

</code>```

The belongsToMany at both classes gets me a many-to-many:

can someone help me? thanks

---------- Temporary Solution -------

Thanks for all help  guys. In fact i can't find a nice solution using only eloquent.

Step 1/3 - To bypass this situation i first execute the above sql to grab only the viagens under the desired status_id (last status_viagem entry):

$viagens_ids = DB::select(
            "SELECT viagem_id FROM (
                SELECT
                    v.id AS viagem_id,
                    (
                        SELECT sv.status_id
                        FROM status_viagem sv
                        WHERE sv.viagem_id = v.id
                        ORDER BY sv.id DESC LIMIT 1 ) AS status_id
                FROM viagens v
            ) AS tt

            WHERE tt.status_id = {$status->id}"
        );
```

<p>Step 2/3 - then i used the array_map to organize my viagens ids</p>

<pre class="lang-php prettyprint-override"><code>$a = array_map(
                function($obj) { return $obj->viagem_id; },
                $viagens_ids
            );
</code>```

Step 3/3 - And at last i used elequent whereIn to fetch my viagens:

 Viagem::with( 'status')->whereIn('id', $a)->get();
```

In fact i have solved the problem by a-old-sashion-way but i not happy with it because i wish i learn how to do it using eloquent. what bad to me.

答:
There are many ways to query in laravel. I have created a test project for you to try. The gist are:

1. Eloquent ORM

Eloquent ORM is Laravel's magic which have some limitations in eager loading - which i just come across while contemplating your question for hours. It wont play nicely with first(), last(), and some more functions in the constrained eager loading closure.

In your case, our almost there can be fixed:

```<code>   App\Models\Viagem::with(['status' => function($query){
          return $query->orderBy('pivot_created_at', 'desc');
         }])
        ->get()
</code>```

It will return entire field for Viagem and Status including its pivot table (the status_viagem).

However, if you wanted to retrieve only viagem.id and status_viagem.status_id, you can map() it as such:

```<code>   App\Models\Viagem::with(['status' => function($query){
           return $query->orderBy('pivot_created_at', 'desc');
         }])
        ->get()
        ->map(function($data){
           $o = new stdClass();
           $o->id = $data->id;
           $o->status_id = $data->status->first()->id;
           return $o;
        });
</code>```

Please take note that the statement above require sql query to be ran twice. Eager loading basically works by querying all the Viagem first then queries the Status and map them in memory based on the foreign keys. You can observe that replacing get with toSql will only give you the first query. Please enable Query Logging to see the second query.

2. Query Builder

Embarking from Ryan Adhitama Putra answer, you could do something like:

```<code>   App\Models\Viagem::join('status_viagem', 'viagens.id', '=', 'status_viagem.viagem_id')
       ->orderBy('status_viagem.created_at', 'desc')
       ->groupBy(['status_viagem.status_id', 'viagens.id'])
       ->select(['viagens.id', 'status_viagem.status_id'])
       ->get();
</code>```

This query builder approach guaranteed to be ran only once, you can replace the get() with toSql() to see the resulting query.

3. Raw Queries

Throwing DB::raw() can help sometime, but i really did not want to mention it.

Body:
in sql query this commando do exactly i wanted:

SELECT
    v.id,
    (
        SELECT sv.status_id
        FROM status_viagem sv
        WHERE sv.viagem_id = v.id
        ORDER BY sv.created_at DESC LIMIT 1 ) AS status_id
FROM viagens v

Here is the sql results:

But i have no idea how can i do this using Laravel eloquent

Basically, a viagem entry can has a lot of status, but i need to get each viagem and their last status entry from status_viagem table (the pivot table)

by the way viagem/viagens means travel.

My class mapping:

class Viagem extends Model
{
  ...
  public function status()
  {
        return $this->belongsToMany('App\Status')->withTimestamps();
  }
  ...
}

class Status extends Model
{

    public function viagens()
    {
        return $this->belongsToMany('App\Viagem')->withTimestamps();
    }
}

The belongsToMany at both classes gets me a many-to-many:

can someone help me? thanks

---------- Temporary Solution -------

Thanks for all help  guys. In fact i can't find a nice solution using only eloquent.

Step 1/3 - To bypass this situation i first execute the above sql to grab only the viagens under the desired status_id (last status_viagem entry):

$viagens_ids = DB::select(
            "SELECT viagem_id FROM (
                SELECT
                    v.id AS viagem_id,
                    (
                        SELECT sv.status_id
                        FROM status_viagem sv
                        WHERE sv.viagem_id = v.id
                        ORDER BY sv.id DESC LIMIT 1 ) AS status_id
                FROM viagens v
            ) AS tt

            WHERE tt.status_id = {$status->id}"
        );

Step 2/3 - then i used the array_map to organize my viagens ids

$a = array_map(
                function($obj) { return $obj->viagem_id; },
                $viagens_ids
            );

Step 3/3 - And at last i used elequent whereIn to fetch my viagens:

 Viagem::with( 'status')->whereIn('id', $a)->get();

In fact i have solved the problem by a-old-sashion-way but i not happy with it because i wish i learn how to do it using eloquent. what bad to me.

Body:
There are many ways to query in laravel. I have created a test project for you to try. The gist are:

1. Eloquent ORM

Eloquent ORM is Laravel's magic which have some limitations in eager loading - which i just come across while contemplating your question for hours. It wont play nicely with first(), last(), and some more functions in the constrained eager loading closure.

In your case, our almost there can be fixed:

   App\Models\Viagem::with(['status' => function($query){
          return $query->orderBy('pivot_created_at', 'desc');
         }])
        ->get()

It will return entire field for Viagem and Status including its pivot table (the status_viagem).

However, if you wanted to retrieve only viagem.id and status_viagem.status_id, you can map() it as such:

   App\Models\Viagem::with(['status' => function($query){
           return $query->orderBy('pivot_created_at', 'desc');
         }])
        ->get()
        ->map(function($data){
           $o = new stdClass();
           $o->id = $data->id;
           $o->status_id = $data->status->first()->id;
           return $o;
        });

Please take note that the statement above require sql query to be ran twice. Eager loading basically works by querying all the Viagem first then queries the Status and map them in memory based on the foreign keys. You can observe that replacing get with toSql will only give you the first query. Please enable Query Logging to see the second query.

2. Query Builder

Embarking from Ryan Adhitama Putra answer, you could do something like:

   App\Models\Viagem::join('status_viagem', 'viagens.id', '=', 'status_viagem.viagem_id')
       ->orderBy('status_viagem.created_at', 'desc')
       ->groupBy(['status_viagem.status_id', 'viagens.id'])
       ->select(['viagens.id', 'status_viagem.status_id'])
       ->get();

This query builder approach guaranteed to be ran only once, you can replace the get() with toSql() to see the resulting query.

3. Raw Queries

Throwing DB::raw() can help sometime, but i really did not want to mention it.


问:
How to implement usage of multiple strategies at runtime
I need to process a list of records returned from a service.

However the processing algorithm for a record changes completely based on a certain field on the record.

To implement this , I have defined an IProcessor interface which has just one method :

```<code>public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}
</code>```

And I have two concrete implementations of IProcessor for the different types of processing.

The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing:

```<code>public class Engine
{
    public void ProcessRecords(IService service)
    {
        var records = service.GetRecords();
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

        IProcessor processor1 = new Type1Processor();
        processor.Process(type1Records);

        IProcessor processor2 = new Type2Processor();
        processor.Process(type2Records);
    }
}
</code>```

This is what I'm doing at present .. and it doesn't look nice and clean.

Any ideas as to how I could improve this design .. using IoC perhaps ?

答:
Personally I would probably make one IProcessor implementation that handles the different record types. Something like

```<code>public class ProcessorImpl : IProcessor
{
    // Either create them here or get them from some constructor injection or whatever.
    private readonly Type1Processor type1 = new Type1Processor();
    private readonly Type2Processor type2 = new Type2Processor();

    public ICollection<OutputEntity> Process(ICollection<InputEntity>> entities)
    {
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();
        var result = new List<OutputEntity>();

        result.AddRange(type1.Process(type1Records));
        result.AddRange(type2.Process(type2Records));

        return result;
    }
}
</code>```

Then you can pass all you input entities to the Process method without worrying which record types it contains.

This implementation lacks some extendability, so if that's needed it has to be extended (see Komet's answer). The basic idea is to have one separate service responsible for choosing process implementation.

Body:
I need to process a list of records returned from a service.

However the processing algorithm for a record changes completely based on a certain field on the record.

To implement this , I have defined an IProcessor interface which has just one method :

public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}

And I have two concrete implementations of IProcessor for the different types of processing.

The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing:

public class Engine
{
    public void ProcessRecords(IService service)
    {
        var records = service.GetRecords();
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

        IProcessor processor1 = new Type1Processor();
        processor.Process(type1Records);

        IProcessor processor2 = new Type2Processor();
        processor.Process(type2Records);
    }
}

This is what I'm doing at present .. and it doesn't look nice and clean.

Any ideas as to how I could improve this design .. using IoC perhaps ?

Body:
Personally I would probably make one IProcessor implementation that handles the different record types. Something like

public class ProcessorImpl : IProcessor
{
    // Either create them here or get them from some constructor injection or whatever.
    private readonly Type1Processor type1 = new Type1Processor();
    private readonly Type2Processor type2 = new Type2Processor();

    public ICollection<OutputEntity> Process(ICollection<InputEntity>> entities)
    {
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();
        var result = new List<OutputEntity>();

        result.AddRange(type1.Process(type1Records));
        result.AddRange(type2.Process(type2Records));

        return result;
    }
}

Then you can pass all you input entities to the Process method without worrying which record types it contains.

This implementation lacks some extendability, so if that's needed it has to be extended (see Komet's answer). The basic idea is to have one separate service responsible for choosing process implementation.


问:
Starting WinAppDriver.exe programmatically
Before starting test execution, I have to manually start this WinAppDriver.exe.

I want to automate this task when I start executing my test cases it should start this exe and after finish it will close it.

I have tried in Java with below code but I'm not success:

```<code>Runtime runTime = Runtime.getRuntime();

String executablePath = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe";

Process process = runTime.exec(executablePath);
</code>```

Note: I required to run it with 'Run As Administrator'

答:
Both worked for me without staring eclipse as Admin .

```<code> Runtime.getRuntime().exec("C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe");
</code>```

Also the Sukhangad singh's answer.

```<code> String command = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe";
    ProcessBuilder builder = new ProcessBuilder(command).inheritIO();
    builder.start();
</code>```

Body:
Before starting test execution, I have to manually start this WinAppDriver.exe.

I want to automate this task when I start executing my test cases it should start this exe and after finish it will close it.

I have tried in Java with below code but I'm not success:

Runtime runTime = Runtime.getRuntime();

String executablePath = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe";

Process process = runTime.exec(executablePath);

Note: I required to run it with 'Run As Administrator'

Body:
Both worked for me without staring eclipse as Admin .

 Runtime.getRuntime().exec("C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe");

Also the Sukhangad singh's answer.

 String command = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe";
    ProcessBuilder builder = new ProcessBuilder(command).inheritIO();
    builder.start();


问:
MySQL query suddenly takes forever to finish
I'm having a problem with an old Symfony 2 application. Suddenly, when the user clicks on the Orders tab, it takes 5+ minutes to display the list, when it used to take no more than 3 seconds before. This is the query with its execution plan:

```<code>EXPLAIN
SELECT DISTINCT s0_.id AS id0
              , SUM(s1_.price * s1_.amount) AS sclr1
              , SUM(s1_.price * s1_.amount * s1_.tax) AS sclr2
              , SUM(s1_.price * s1_.amount * s1_.retax) AS sclr3
              , s0_.id AS id4
           FROM stncrp_order s0_
           JOIN stncrp_store s2_
             ON s0_.store_id = s2_.id
           LEFT
           JOIN stncrp_orderline s1_
             ON s0_.id = s1_.order_id
            AND s1_.rejected = 0
           LEFT
           JOIN stncrp_order_provider_warn s3_
             ON s0_.id = s3_.order_id
          WHERE s0_.state >= 3
          GROUP
             BY s0_.id
              , s0_.date
              , s0_.shipment_limit_date
              , s0_.state
              , s0_.state_changed_date
              , s0_.received
              , s0_.shipment_cost
              , s0_.username
              , s0_.notes
              , s0_.user_id
              , s0_.store_id
              , s0_.storedata_id
              , s3_.id
              , s3_.createdDate
              , s3_.comments
              , s3_.order_id
          ORDER
             BY s0_.id DESC
          LIMIT 10
         OFFSET 0;
+----+-------------+-------+--------+----------------------+----------------------+---------+---------------------+-------+----------------------------------------------+
| id | select_type | table | type   | possible_keys        | key                  | key_len | ref                 | rows  | Extra                                        |
+----+-------------+-------+--------+----------------------+----------------------+---------+---------------------+-------+----------------------------------------------+
|  1 | SIMPLE      | s0_   | ALL    | IDX_F4A5D9B092A811   | NULL                 | NULL    | NULL                | 19633 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | s2_   | eq_ref | PRIMARY              | PRIMARY              | 4       | est_db.s0_.store_id |     1 | Using index                                  |
|  1 | SIMPLE      | s1_   | ref    | IDX_252BF9D78D9F6D38 | IDX_252BF9D78D9F6D38 | 5       | est_db.s0_.id       |     3 |                                              |
|  1 | SIMPLE      | s3_   | ref    | IDX_20FC41F28D9F6D38 | IDX_20FC41F28D9F6D38 | 5       | est_db.s0_.id       |     1 |                                              |
+----+-------------+-------+--------+----------------------+----------------------+---------+---------------------+-------+----------------------------------------------+
</code>```

Here's the process list on the server right now:

```<code>mysql> show processlist;
+-----+------+-----------------+--------+---------+------+---------------------+------------------------------------------------------------------------------------------------------+
| Id  | User | Host            | db     | Command | Time | State               | Info                                                                                |
+-----+------+-----------------+--------+---------+------+---------------------+------------------------------------------------------------------------------------------------------+
| 185 | root | localhost:52066 | est_db | Sleep   | 4877 |                     | NULL                                                                                |
| 186 | root | localhost:52068 | est_db | Sleep   | 4885 |                     | NULL                                                                                |
| 209 | root | localhost:52176 | est_db | Sleep   |   31 |                     | NULL                                                                                |
| 242 | root | localhost       | est_db | Query   |    0 | NULL                | show processlist                                                                                |
| 248 | root | localhost:52368 | est_db | Query   | 1525 | Removing duplicates | SELECT DISTINCT s0_.id AS id0, SUM(s1_.price * s1_.amount) AS sclr1, SUM(s1_.price * s1_.amount * s1 |
+-----+------+-----------------+--------+---------+------+---------------------+------------------------------------------------------------------------------------------------------+
</code>```

The query is generated "magically" by the following method:

```<code>/**
 * @Route("/admin/order/index", name="mainbundle_admin_orderentity")
 * @Template()
 */
public function orderAjaxListAction()
{
    $searchform = $this->searchForm(
        $this->createForm(new OrderEntitySearchType())
    );
    $em    = $this->getDoctrine()->getManager();
    $qb = $em->getRepository('StoreBundle:OrderEntity')->findByCriteria($searchform->getData());
    return $this->index('OrderEntity', $qb, $searchform, 't.id', 'DESC');
}
</code>```

Nobody has changed anything in the application code or the database and it was working perfectly fine up to last friday... What could be the reason?

Thanks in advance,

答: Most probably on the View side if you have tried to query the entity with the associations, lazy loading will create an additional request for each iteration, so it will be really slow if you have more data.</p>

Body:
I'm having a problem with an old Symfony 2 application. Suddenly, when the user clicks on the Orders tab, it takes 5+ minutes to display the list, when it used to take no more than 3 seconds before. This is the query with its execution plan:

EXPLAIN
SELECT DISTINCT s0_.id AS id0
              , SUM(s1_.price * s1_.amount) AS sclr1
              , SUM(s1_.price * s1_.amount * s1_.tax) AS sclr2
              , SUM(s1_.price * s1_.amount * s1_.retax) AS sclr3
              , s0_.id AS id4
           FROM stncrp_order s0_
           JOIN stncrp_store s2_
             ON s0_.store_id = s2_.id
           LEFT
           JOIN stncrp_orderline s1_
             ON s0_.id = s1_.order_id
            AND s1_.rejected = 0
           LEFT
           JOIN stncrp_order_provider_warn s3_
             ON s0_.id = s3_.order_id
          WHERE s0_.state >= 3
          GROUP
             BY s0_.id
              , s0_.date
              , s0_.shipment_limit_date
              , s0_.state
              , s0_.state_changed_date
              , s0_.received
              , s0_.shipment_cost
              , s0_.username
              , s0_.notes
              , s0_.user_id
              , s0_.store_id
              , s0_.storedata_id
              , s3_.id
              , s3_.createdDate
              , s3_.comments
              , s3_.order_id
          ORDER
             BY s0_.id DESC
          LIMIT 10
         OFFSET 0;
+----+-------------+-------+--------+----------------------+----------------------+---------+---------------------+-------+----------------------------------------------+
| id | select_type | table | type   | possible_keys        | key                  | key_len | ref                 | rows  | Extra                                        |
+----+-------------+-------+--------+----------------------+----------------------+---------+---------------------+-------+----------------------------------------------+
|  1 | SIMPLE      | s0_   | ALL    | IDX_F4A5D9B092A811   | NULL                 | NULL    | NULL                | 19633 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | s2_   | eq_ref | PRIMARY              | PRIMARY              | 4       | est_db.s0_.store_id |     1 | Using index                                  |
|  1 | SIMPLE      | s1_   | ref    | IDX_252BF9D78D9F6D38 | IDX_252BF9D78D9F6D38 | 5       | est_db.s0_.id       |     3 |                                              |
|  1 | SIMPLE      | s3_   | ref    | IDX_20FC41F28D9F6D38 | IDX_20FC41F28D9F6D38 | 5       | est_db.s0_.id       |     1 |                                              |
+----+-------------+-------+--------+----------------------+----------------------+---------+---------------------+-------+----------------------------------------------+

Here's the process list on the server right now:

mysql> show processlist;
+-----+------+-----------------+--------+---------+------+---------------------+------------------------------------------------------------------------------------------------------+
| Id  | User | Host            | db     | Command | Time | State               | Info                                                                                |
+-----+------+-----------------+--------+---------+------+---------------------+------------------------------------------------------------------------------------------------------+
| 185 | root | localhost:52066 | est_db | Sleep   | 4877 |                     | NULL                                                                                |
| 186 | root | localhost:52068 | est_db | Sleep   | 4885 |                     | NULL                                                                                |
| 209 | root | localhost:52176 | est_db | Sleep   |   31 |                     | NULL                                                                                |
| 242 | root | localhost       | est_db | Query   |    0 | NULL                | show processlist                                                                                |
| 248 | root | localhost:52368 | est_db | Query   | 1525 | Removing duplicates | SELECT DISTINCT s0_.id AS id0, SUM(s1_.price * s1_.amount) AS sclr1, SUM(s1_.price * s1_.amount * s1 |
+-----+------+-----------------+--------+---------+------+---------------------+------------------------------------------------------------------------------------------------------+

The query is generated "magically" by the following method:

/**
 * @Route("/admin/order/index", name="mainbundle_admin_orderentity")
 * @Template()
 */
public function orderAjaxListAction()
{
    $searchform = $this->searchForm(
        $this->createForm(new OrderEntitySearchType())
    );
    $em    = $this->getDoctrine()->getManager();
    $qb = $em->getRepository('StoreBundle:OrderEntity')->findByCriteria($searchform->getData());
    return $this->index('OrderEntity', $qb, $searchform, 't.id', 'DESC');
}

Nobody has changed anything in the application code or the database and it was working perfectly fine up to last friday... What could be the reason?

Thanks in advance,


问:
EF Core MySQL Database First?
I have a MySQL database sitting in Amazon Cloud (RDS). It is a tiny database with only one table.

I want to use EF Core, Database First. I know that the Pomelo.EntityFrameworkCore.MySql package is popular, but I cannot see any information on how to achieve a scaffolding of the Db Context via that package.

I followed the instructions here whilst replacing MySql.Data.EntityFrameworkCore.Design with Pomelo.EntityFrameworkCore.MySql but when I ran the command below in Package Manager Console:

```<code>Scaffold-DbContext "Server=my-db.rds.amazonaws.com;database=TestDb;uid=blah;pwd=blah;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -f
</code>```

I just got the error:

The specified framework version '2.0' could not be parsed

What am I missing? Here's how my dummy solution looks

答:
In 2020 with .net core 3 released a lot of things changed, this is what working as of now :)

Make sure you have all these packages

```<code><PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" />
</code>```

Now dotnet ef is a global tool that needs to be installed, reference

```<code>dotnet tool install --global dotnet-ef
</code>```

Then run this command, reference

```<code>dotnet ef dbcontext scaffold "Server=localhost;Database=ef;User=root;Password=123456;TreatTinyAsBoolean=true;" "Pomelo.EntityFrameworkCore.MySql"
</code>```

For scaffolding in a different path, you can use --output-dir

```<code>dotnet ef dbcontext scaffold server=localhost;port=3306;database=palle2patnam;uid=root;password=password" "Pomelo.EntityFrameworkCore.MySql" --output-dir Models
</code>```

For forcing to get new fields from database u can add --force

```<code>dotnet ef dbcontext scaffold "server=localhost;port=3306;database=palle2patnam;uid=root;password=password" "Pomelo.EntityFrameworkCore.MySql" --output-dir Models --force
</code>```

Title: EF Core MySQL Database First?

Body:
I have a MySQL database sitting in Amazon Cloud (RDS). It is a tiny database with only one table.

I want to use EF Core, Database First. I know that the Pomelo.EntityFrameworkCore.MySql package is popular, but I cannot see any information on how to achieve a scaffolding of the Db Context via that package.

I followed the instructions here whilst replacing MySql.Data.EntityFrameworkCore.Design with Pomelo.EntityFrameworkCore.MySql but when I ran the command below in Package Manager Console:

Scaffold-DbContext "Server=my-db.rds.amazonaws.com;database=TestDb;uid=blah;pwd=blah;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -f

I just got the error:

The specified framework version '2.0' could not be parsed

What am I missing? Here's how my dummy solution looks

Body:
In 2020 with .net core 3 released a lot of things changed, this is what working as of now :)

Make sure you have all these packages

<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" />

Now dotnet ef is a global tool that needs to be installed, reference

dotnet tool install --global dotnet-ef

Then run this command, reference

dotnet ef dbcontext scaffold "Server=localhost;Database=ef;User=root;Password=123456;TreatTinyAsBoolean=true;" "Pomelo.EntityFrameworkCore.MySql"

For scaffolding in a different path, you can use --output-dir

dotnet ef dbcontext scaffold server=localhost;port=3306;database=palle2patnam;uid=root;password=password" "Pomelo.EntityFrameworkCore.MySql" --output-dir Models

For forcing to get new fields from database u can add --force

dotnet ef dbcontext scaffold "server=localhost;port=3306;database=palle2patnam;uid=root;password=password" "Pomelo.EntityFrameworkCore.MySql" --output-dir Models --force


问:
What is the proper way to use branching or separate repositories to maintain multiple versions of code that are not backward compatible?
I write add-ins for Revit.  These add-ins depend on the Revit API libraries.  These libraries change with each new version of Revit (2018, 2019, 2020, etc).  Unfortunately they are not backward compatible so I can't use my add-in from 2018 with 2020.  This means that I maintain separate repositories of my own code for 2018, 2019, and 2020.  I'm currently using pull requests so that if I make a change in 2018 I can move it across to 2019 and 2020.  The problem is that when the request comes across it updates my 2019/2020 libraries back to reference the 2018 libraries.  Then I have to go back in and make sure that it references the correct library.

How should I be doing this to avoid this issue every time that I need to push a change to other versions?

答:
Are you sure that your 2018 add-in cannot be used in Revit 2020?

In many cases, if not most, the opposite is true.

In general, you can use an add-in compiled for a previous version of Revit in later versions as well.

If you are making calls to Revit API functionality that changed between the versions, you can handle that by compiling for the earlier version of Revit and adding .NET runtime functionality to check at runtime whether to call the old or new version of the Revit API. The calls that changed can be updated dynamically for the new version at runtime.

Look at The Building Coder Multi-Version Add-in for a full implementation sample.

That said, I still totally agree with your question per se; in many cases, you will want a separate clean updated version of your add-in for each version of Revit, to avoid complexity and enhance code readability. For that, I totally agree with Ôrel on maintaining a separate branch for each version and merging updates into other branches.


问:
Validating a textbox entry if duplicate display error message microsoft access
i have searched around and cant find an answer, so i am using Microsoft Access Office 2019 and cant seem to validate my textbox for a duplicate entry. The user will add a record and enter a short text primary key (which in this case is the new employee's ID) Field - [EMPID] in the [EMPDETAILS] table. The below code has worked for validating my Autonumber primary key but doesnt seem to work for a custom short text primary key and i am getting this error

"The expression you entered as a query parameter produced this error :
  'VS123'

<= this is the Employee ID which is a custom short text primary key :

```<code>Private Sub unqidd_BeforeUpdate(Cancel As Integer)

On Error GoTo Err_Handler

Dim strMessage As String
'PartNum is the name of a textbox that contains the primary key, the rest are text to display.
strMessage = "Employee ID" & Me!unqidd & " already exists."

' confirm that part number doesn't already exist.
If (DLookup("[empid]", "[empdetails]", "[empID] = " & Forms![driverdetails]![unqidd])) Then
    MsgBox strMessage, vbInformation, "Invalid Operation"
    Cancel = True
End If
Exit_Here:
Exit Sub

Err_Handler:
MsgBox Err.Description
Resume Exit_Here

End Sub
</code>```

答:
The solution is as below :

1) Create an unbound textbox (Text1616) and set its control source as

```<code>=DLookUp("[empid]","[empdetails]","[empID] = '" & [Forms]![Driverdetails]![unqidd] & "'")
</code>```

2) The textbox (Unqidd) that will need to be validated, on its beforeupdate property set the event procedure code as below :

```<code>Private Sub unqidd_BeforeUpdate(Cancel As Integer)

On Error GoTo Err_Handler

Dim strMessage As String
'PartNum is the name of a textbox that contains the primary key, the rest are text to
display.
strMessage = "Employee ID" & Me!unqidd & " already exists."

' confirm that part number doesn't already exist.
If Me.unqidd.Value = Me.Text1616 Then
    MsgBox strMessage, vbInformation, "Invalid Operation"
    Cancel = True
End If

Exit_Here:
Exit Sub

Err_Handler:
MsgBox Err.Description
Resume Exit_Here

End Sub

'References :
'Table Name        : empdetails
'Table primary key : empid (Short text)
'Form Name         : Driverdetails
'Textbox 1         : unqidd (no formats, control source : empid)
'Textbox 2         : Text1616 (Unbound Textbox)
</code>```

Body:
i have searched around and cant find an answer, so i am using Microsoft Access Office 2019 and cant seem to validate my textbox for a duplicate entry. The user will add a record and enter a short text primary key (which in this case is the new employee's ID) Field - [EMPID] in the [EMPDETAILS] table. The below code has worked for validating my Autonumber primary key but doesnt seem to work for a custom short text primary key and i am getting this error

"The expression you entered as a query parameter produced this error :
  'VS123'

<= this is the Employee ID which is a custom short text primary key :

Private Sub unqidd_BeforeUpdate(Cancel As Integer)

On Error GoTo Err_Handler

Dim strMessage As String
'PartNum is the name of a textbox that contains the primary key, the rest are text to display.
strMessage = "Employee ID" & Me!unqidd & " already exists."

' confirm that part number doesn't already exist.
If (DLookup("[empid]", "[empdetails]", "[empID] = " & Forms![driverdetails]![unqidd])) Then
    MsgBox strMessage, vbInformation, "Invalid Operation"
    Cancel = True
End If
Exit_Here:
Exit Sub

Err_Handler:
MsgBox Err.Description
Resume Exit_Here

End Sub

Body:
The solution is as below :

1) Create an unbound textbox (Text1616) and set its control source as

=DLookUp("[empid]","[empdetails]","[empID] = '" & [Forms]![Driverdetails]![unqidd] & "'")

2) The textbox (Unqidd) that will need to be validated, on its beforeupdate property set the event procedure code as below :

Private Sub unqidd_BeforeUpdate(Cancel As Integer)

On Error GoTo Err_Handler

Dim strMessage As String
'PartNum is the name of a textbox that contains the primary key, the rest are text to
display.
strMessage = "Employee ID" & Me!unqidd & " already exists."

' confirm that part number doesn't already exist.
If Me.unqidd.Value = Me.Text1616 Then
    MsgBox strMessage, vbInformation, "Invalid Operation"
    Cancel = True
End If

Exit_Here:
Exit Sub

Err_Handler:
MsgBox Err.Description
Resume Exit_Here

End Sub

'References :
'Table Name        : empdetails
'Table primary key : empid (Short text)
'Form Name         : Driverdetails
'Textbox 1         : unqidd (no formats, control source : empid)
'Textbox 2         : Text1616 (Unbound Textbox)


问:
How do I "clean" a String in PHP using regex?
For example suppose I have

```<code>$blah = "C$#@#.a534&";
</code>```

I wish to filter the string so that only letters, numbers and "." remain yielding "C.a534"

How do I do this?

答:
been answered lots of times but:</p>

```<code>function cleanit($input){
    return preg_replace('/[^a-zA-Z0-9.]/s', '', $input);
}

$blah = cleanit("C$#@#.a534&");
</code>```

Body:
For example suppose I have

$blah = "C$#@#.a534&";

I wish to filter the string so that only letters, numbers and "." remain yielding "C.a534"

How do I do this?

Body:
been answered lots of times but:

function cleanit($input){
    return preg_replace('/[^a-zA-Z0-9.]/s', '', $input);
}

$blah = cleanit("C$#@#.a534&");


问:
Why variable value is not refreshing in flutter?
The variable value is not refreshing in flutter(which I created outside the class). The following way I have added.So in button press am setting different value. So if I come back to that screen again it is not showing 1. May I know why it is happening?</p>

```<code>int _currVal = 1;

class AskFragment extends StatefulWidget {
  static const String routeName = "//";
  static const
  int currState = -1;

  @override
  HomeScreenState createState() => HomeScreenState();
}
</code>```

答:
To update the values, use Stateful Widget and initialise values inside that Widget only, for any updates in the values of variables mention that in setState((){}) method to notify the change in the values.

See this for documentation of stateful widgets

See this for documentation of setState((){}) method

```<code>setState(() { _myVariable = newValue });
</code>```

Note:- Never initialise changing values in build method they will not get updated instead they will be reinitialised with same values again and again

Body:
The variable value is not refreshing in flutter(which I created outside the class). The following way I have added.So in button press am setting different value. So if I come back to that screen again it is not showing 1. May I know why it is happening?

int _currVal = 1;

class AskFragment extends StatefulWidget {
  static const String routeName = "//";
  static const
  int currState = -1;

  @override
  HomeScreenState createState() => HomeScreenState();
}

Body:
To update the values, use Stateful Widget and initialise values inside that Widget only, for any updates in the values of variables mention that in setState((){}) method to notify the change in the values.

See this for documentation of stateful widgets

See this for documentation of setState((){}) method

setState(() { _myVariable = newValue });

Note:- Never initialise changing values in build method they will not get updated instead they will be reinitialised with same values again and again


问:
Angular 8 ngStyle sometimes does not work inside a loop
I have the following code in Angular 8.

```<code><mat-grid-list cols="5" rowHeight="16:9" gutterSize="1%">
    <mat-grid-tile *ngFor="let m of media; index as i">
        <div class="media-cards" [ngStyle]="{'background-image': 'url(' + m.thumbnail + ')'}"></div>
    </mat-grid-tile>
</mat-grid-list>
</code>```

For some strange and unknown reason, it does not add background-image style in some of the elements generated in the loop. m.thumbnail is a valid URL and available for each element of the media object.

This is how it looks (background image missing):

This is how the generated code looks like:

You can see in the image above that background-image style is missing for the second element.

Why is it happening like this? Where is the problem?

答:
It turns out some of the URLs have parentheses (... Fitness%20(10).JPG ...). So, when when I use the style 'background-image': 'url(__the_url__)', it breaks because of the parentheses. It looks like Angular might be validating the styles before it adds to the element. As these rules don't validate due to the parentheses, those are not added to the elements.

So, I wrapped the URLs in single quotes to make it a string literal so that the parentheses won't create an issue and it will work properly. And it worked.

{'background-image': 'url(\'' + m.thumbnail + '\')'}

Body:
I have the following code in Angular 8.

<mat-grid-list cols="5" rowHeight="16:9" gutterSize="1%">
    <mat-grid-tile *ngFor="let m of media; index as i">

    </mat-grid-tile>
</mat-grid-list>

For some strange and unknown reason, it does not add background-image style in some of the elements generated in the loop. m.thumbnail is a valid URL and available for each element of the media object.

This is how it looks (background image missing):

This is how the generated code looks like:

You can see in the image above that background-image style is missing for the second element.

Why is it happening like this? Where is the problem?


问:
Merging values from 2 different datasets within a certain time interval into a single dataset (R)
I have two separate datasets: df1 and df2. I would like to create a new dataset, df3 that would match the endtime column of df1 with the sent column of df2 if the datetimes are within 20 seconds of each other.

```<code> df1

 endtime                     ID

 1/7/2020  1:35:08 AM         A
 1/7/2020  1:39:00 AM         B
 1/20/2020 1:45:00 AM         C

 df2

sent                         ID

1/7/2020  1:35:20 AM          E
1/7/2020  1:42:00 AM          F
1/20/2020 1:55:00 AM          G
1/20/2020 2:00:00 AM          E
</code>```

This is my desired output for df3. There is only one row, because there are only two values that match the condition of being within 20 seconds of the endtime and sent columns.

```<code>endtime                  sent

1/7/2020 1:35:08 AM      1/7/2020  1:35:20 AM
</code>```

Here is the dput:

```<code>df1

structure(list(endtime = structure(c(2L, 3L, 1L), .Label = c("1/10/2020 1:45:00 AM",
"1/7/2020 1:35:08 AM", "1/7/2020 1:39:00 AM"), class = "factor"),
ID = structure(1:3, .Label = c("A", "B", "C"), class = "factor")), class = "data.frame", row.names =   c(NA,
 -3L))

 df2

 structure(list(sent = structure(c(3L, 4L, 1L, 2L), .Label = c("1/20/2020 1:55:00 AM",
 "1/20/2020 2:00:00 AM", "1/7/2020 1:35:20 AM", "1/7/2020 1:42:00 AM"
 ), class = "factor"), ID = structure(c(1L, 2L, 3L, 1L), .Label = c("E",
"F", "G"), class = "factor")), class = "data.frame", row.names = c(NA,
-4L))
</code>```

This is what I have tried:

I am thinking of performing a left join and matching the values, or I can use merge(), but the tricky part is matching the values with the conditional statement. Any suggestion is appreciated.

```<code>library(dplyr)
left_join(df1, df2)
</code>```

答:
You can also do it like this if your datasets are too big to make the cartesian product:

df1 %>%
    split(1:NROW(.)) %>%
    map( ~merge(.x,
                df2[ abs(difftime(df2$sent, .x$endtime, units='s')) < 20, ],
                by=NULL) ) %>%
    bind_rows()
```

<h2>EDIT</h2>

<p><em>TLDR</em></p>

<p>Use the non-equi join from data.table, it has the best performance overall.</p>

<pre class="lang-r prettyprint-override"><code>dt1 = as.data.table(df1)
dt2 = as.data.table(df2)

dt1[, `:=`(endtime_min = endtime - 20, endtime_max = endtime + 20) ]
dt1[dt2,
    .(ID, ID1, endtime, sent),
    on = .(endtime_min < sent, endtime_max > sent), nomatch = 0L, allow.cartesian=T]
</code>```

Longer version

The answer I posted would be better in scenarios where the data frames are too big, since doing the cross join first yields a data frame with as many rows as the product of the number of rows from both data frames. By first filtering and after joining, it avoids the unnecessary memory allocation. However, it has the overhead of for each row of df1, checking if there are any rows to match in the df2.

Another use case where this answer would be better is when one of the data frames is much smaller than the other, even if they aren't that big. I ran some benchmarks to check this.

However, after coming across this answer, and making the version of the solution in data.table for the question presented by the OP, none of the answers compares to the performance of this implementation.

The tests I ran used the datasets given by the OP, where to simulate a larger dataset I simply replicated those datasets a certain amount of times. There were 2 tests that I did:

Replicated both datasets the same amount of times

Fixed the size of df1 and replicated df2

For each test, I measured the median execution time for the accepted answer (merge_filter), my original answer (filter_merge) and the data.table solution (datatable).

Prior to running the tests, I prepared both df1 and df2 to have the right datatypes, and renamed the column ID from df1 to ID1. For the data.table solution, I converted both data frames into their data.tables counterparts, dt1 and dt2.

Regarding each method, I have to do some changes, mainly using merge(..., by=NULL) instead of crossing(...) since the last one doesn't support cross joining with duplicate rows, removing all the duplicate rows from the resulting dataset.

Here is the code I used to run the tests:

library(tidyverse)
library(data.table)

run_test = function(n, n1=n, n2=n) {
    df1 = bind_rows(rep(list(df1_op), n1))
    df2 = bind_rows(rep(list(df1_op), n2))
    dt1 = as.data.table(df1)
    dt2 = as.data.table(df2)

    microbenchmark::microbenchmark(
        merge_filter = df1 %>%
            merge(df2, by=NULL) %>%
            filter(abs(difftime(sent, endtime, 'secs')) < 20),

        filter_merge = df1 %>%
            split(1:NROW(.)) %>%
            map(~merge( .x,
                        df2[ abs(difftime(df2$sent, .x$endtime, units='s')) < 20, ],
                        by=NULL) ) %>%
            bind_rows(),

        datatable={
            dt1[, `:=`(endtime_min = endtime - 20, endtime_max = endtime + 20) ]
            dt1[dt2,
                .(ID, ID1, endtime, sent),
                on = .(endtime_min < sent, endtime_max > sent), nomatch = 0L, allow.cartesian=T]
        }
    )
}

test_1_list = list()
for( n in c(1, 2, 5, 10, 20, 50, 100, 200, 500) ) {
    test_1_list[[ toString(n) ]] <- run_test(n)
}

test_2_list = list()
for( n in c(1, 2, 5, 10, 20, 50, 100, 200, 500,
            1000, 2000, 5000, 10000, 20000, 50000) ) {
    test_2_list[[ toString(n) ]] <- run_test(n, n1=1)
}
```

<p>And here are the results for test 1 and 2 respectively:</p>

<p><img src="https://i.stack.imgur.com/284Pw.png" alt="enter image description here"></p>

<p><img src="https://i.stack.imgur.com/LHd84.png" alt="enter image description here"></p>

<h2>EDIT 2</h2>

<p>You can do a non-equi left join like this:</p>

<p><code>filter_merge</code></p>

<pre class="lang-r prettyprint-override"><code>df1 %>%
    split(1:NROW(.)) %>%
    map( ~merge(mutate(.x, k=1),
                df2 %>%
                    filter( abs(difftime(df2$sent, .x$endtime, units='s')) < 20 ) %>%
                    mutate(k=1),
                by="k",
                all.x=T) %>%
            select(-k) ) %>%
    bind_rows() %>%
    select(ID1, endtime, ID, sent)

#   ID1             endtime   ID                sent
# 1   A 2020-01-07 01:35:08    E 2020-01-07 01:35:20
# 2   B 2020-01-07 01:39:00 <NA>                <NA>
# 3   C 2020-01-10 01:45:00 <NA>                <NA>
</code>```

datatable

dt1[, `:=`(endtime_min = endtime - 20, endtime_max = endtime + 20) ]
dt2[dt1,
    .(i.ID1, i.endtime, x.ID, x.sent),
    on = .(sent > endtime_min, sent < endtime_max), allow.cartesian=T]

#    i.ID1           i.endtime x.ID              x.sent
# 1:     A 2020-01-07 01:35:08    E 2020-01-07 01:35:20
# 2:     B 2020-01-07 01:39:00 <NA>                <NA>
# 3:     C 2020-01-10 01:45:00 <NA>                <NA>
```

Body:
I have two separate datasets: df1 and df2. I would like to create a new dataset, df3 that would match the endtime column of df1 with the sent column of df2 if the datetimes are within 20 seconds of each other.

 df1

 endtime                     ID

 1/7/2020  1:35:08 AM         A
 1/7/2020  1:39:00 AM         B
 1/20/2020 1:45:00 AM         C

 df2

sent                         ID

1/7/2020  1:35:20 AM          E
1/7/2020  1:42:00 AM          F
1/20/2020 1:55:00 AM          G
1/20/2020 2:00:00 AM          E

This is my desired output for df3. There is only one row, because there are only two values that match the condition of being within 20 seconds of the endtime and sent columns.

endtime                  sent

1/7/2020 1:35:08 AM      1/7/2020  1:35:20 AM

Here is the dput:

df1

structure(list(endtime = structure(c(2L, 3L, 1L), .Label = c("1/10/2020 1:45:00 AM",
"1/7/2020 1:35:08 AM", "1/7/2020 1:39:00 AM"), class = "factor"),
ID = structure(1:3, .Label = c("A", "B", "C"), class = "factor")), class = "data.frame", row.names =   c(NA,
 -3L))

 df2

 structure(list(sent = structure(c(3L, 4L, 1L, 2L), .Label = c("1/20/2020 1:55:00 AM",
 "1/20/2020 2:00:00 AM", "1/7/2020 1:35:20 AM", "1/7/2020 1:42:00 AM"
 ), class = "factor"), ID = structure(c(1L, 2L, 3L, 1L), .Label = c("E",
"F", "G"), class = "factor")), class = "data.frame", row.names = c(NA,
-4L))

This is what I have tried:

I am thinking of performing a left join and matching the values, or I can use merge(), but the tricky part is matching the values with the conditional statement. Any suggestion is appreciated.

library(dplyr)
left_join(df1, df2)

Body:
You can also do it like this if your datasets are too big to make the cartesian product:

df1 %>%
    split(1:NROW(.)) %>%
    map( ~merge(.x,
                df2[ abs(difftime(df2$sent, .x$endtime, units='s')) < 20, ],
                by=NULL) ) %>%
    bind_rows()

EDIT

TLDR

Use the non-equi join from data.table, it has the best performance overall.

dt1 = as.data.table(df1)
dt2 = as.data.table(df2)

dt1[, `:=`(endtime_min = endtime - 20, endtime_max = endtime + 20) ]
dt1[dt2,
    .(ID, ID1, endtime, sent),
    on = .(endtime_min < sent, endtime_max > sent), nomatch = 0L, allow.cartesian=T]

Longer version

The answer I posted would be better in scenarios where the data frames are too big, since doing the cross join first yields a data frame with as many rows as the product of the number of rows from both data frames. By first filtering and after joining, it avoids the unnecessary memory allocation. However, it has the overhead of for each row of df1, checking if there are any rows to match in the df2.

Another use case where this answer would be better is when one of the data frames is much smaller than the other, even if they aren't that big. I ran some benchmarks to check this.

However, after coming across this answer, and making the version of the solution in data.table for the question presented by the OP, none of the answers compares to the performance of this implementation.

The tests I ran used the datasets given by the OP, where to simulate a larger dataset I simply replicated those datasets a certain amount of times. There were 2 tests that I did:

Replicated both datasets the same amount of times

Fixed the size of df1 and replicated df2

For each test, I measured the median execution time for the accepted answer (merge_filter), my original answer (filter_merge) and the data.table solution (datatable).

Prior to running the tests, I prepared both df1 and df2 to have the right datatypes, and renamed the column ID from df1 to ID1. For the data.table solution, I converted both data frames into their data.tables counterparts, dt1 and dt2.

Regarding each method, I have to do some changes, mainly using merge(..., by=NULL) instead of crossing(...) since the last one doesn't support cross joining with duplicate rows, removing all the duplicate rows from the resulting dataset.

Here is the code I used to run the tests:

library(tidyverse)
library(data.table)

run_test = function(n, n1=n, n2=n) {
    df1 = bind_rows(rep(list(df1_op), n1))
    df2 = bind_rows(rep(list(df1_op), n2))
    dt1 = as.data.table(df1)
    dt2 = as.data.table(df2)

    microbenchmark::microbenchmark(
        merge_filter = df1 %>%
            merge(df2, by=NULL) %>%
            filter(abs(difftime(sent, endtime, 'secs')) < 20),

        filter_merge = df1 %>%
            split(1:NROW(.)) %>%
            map(~merge( .x,
                        df2[ abs(difftime(df2$sent, .x$endtime, units='s')) < 20, ],
                        by=NULL) ) %>%
            bind_rows(),

        datatable={
            dt1[, `:=`(endtime_min = endtime - 20, endtime_max = endtime + 20) ]
            dt1[dt2,
                .(ID, ID1, endtime, sent),
                on = .(endtime_min < sent, endtime_max > sent), nomatch = 0L, allow.cartesian=T]
        }
    )
}

test_1_list = list()
for( n in c(1, 2, 5, 10, 20, 50, 100, 200, 500) ) {
    test_1_list[[ toString(n) ]] <- run_test(n)
}

test_2_list = list()
for( n in c(1, 2, 5, 10, 20, 50, 100, 200, 500,
            1000, 2000, 5000, 10000, 20000, 50000) ) {
    test_2_list[[ toString(n) ]] <- run_test(n, n1=1)
}

And here are the results for test 1 and 2 respectively:

EDIT 2

You can do a non-equi left join like this:

filter_merge

df1 %>%
    split(1:NROW(.)) %>%
    map( ~merge(mutate(.x, k=1),
                df2 %>%
                    filter( abs(difftime(df2$sent, .x$endtime, units='s')) < 20 ) %>%
                    mutate(k=1),
                by="k",
                all.x=T) %>%
            select(-k) ) %>%
    bind_rows() %>%
    select(ID1, endtime, ID, sent)

#   ID1             endtime   ID                sent
# 1   A 2020-01-07 01:35:08    E 2020-01-07 01:35:20
# 2   B 2020-01-07 01:39:00 <NA>                <NA>
# 3   C 2020-01-10 01:45:00 <NA>                <NA>

datatable

dt1[, `:=`(endtime_min = endtime - 20, endtime_max = endtime + 20) ]
dt2[dt1,
    .(i.ID1, i.endtime, x.ID, x.sent),
    on = .(sent > endtime_min, sent < endtime_max), allow.cartesian=T]

#    i.ID1           i.endtime x.ID              x.sent
# 1:     A 2020-01-07 01:35:08    E 2020-01-07 01:35:20
# 2:     B 2020-01-07 01:39:00 <NA>                <NA>
# 3:     C 2020-01-10 01:45:00 <NA>                <NA>