问:
Child model class - best practice on how to structure it so that same object gets used for insert and select - MyBatis
I am using MyBatis in a Spring object, that has all the queries and mapping in XML files.
I am facing a scenario for which I am not certain what would be considered a "best practice" or optimal solution.

I have a child table "Child" that contains 2 FKs. Whenever I do an **insert **for this Child, I will only need to have the FKs of the parents as fields in the object that will be used by the XML file to do the insert (has some other fields as well).

I can use the following POJO for this (INSERT):

```<code>class Child {
    private Long id;
    private Long firstParentID; // FK_1
    private Long secondParentID; // FK_2
    // other fields
}
</code>```

However, when doing SELECTs, I will want to do a retrieval of some of the fields that SecondParent contains.
Lets say that SecondParent is the following:

```<code>class SecondParent {
    private Long id;
    private Long firstname;
    private Long lastname;
}
</code>```

Meaning when **selecting **children objects (In the app I will retrieve the FirstParent, with the list of Child, where each Child will need to contain some of the data that the SecondParent table has), I will need to have the following data in each Child POJO:

OPTION 1:

```<code>class Child {
    private Long id;
    private Long firstParentID; // FK_1

    private Long secondParentID; // FK_2
    private String secondParentFirstname; // data that is contained in the SecondParent table
    private String secondParentLastname; // data that is contained in the SecondParent table
}
</code>```

Would using the above object be considered fine? It may seem like a DTO rather than a model (since it contains fields that are not part of the Child table: secondParentFirstname, secondParentLastname). When inserting obviously the fields secondParentFirstname, **secondParentLastname **would be irrelevant.

Would something like the below object be more appropriate:
OPTION 2:

```<code>class Child {
    private Long id;
    private Long firstParentID; // FK_1

    private Long secondParentID; // FK_2 - for insert might be easier to have it also outside the SecondParent object
    private SecondParent secondParent;
}
</code>```

The SecondParent object is very big, and in this case I would only need a few of the column values of its table.

Personally, I would find the first option (the flat Child POJO -- OPTION 1) to be easier for both insert and select, since the converters in service layer would also be simpler.
But is the fact that it also contains fields that represent columns of the parent table, considered a bad practice ?

Body:
I am using MyBatis in a Spring object, that has all the queries and mapping in XML files.
I am facing a scenario for which I am not certain what would be considered a "best practice" or optimal solution.

I have a child table "Child" that contains 2 FKs. Whenever I do an **insert **for this Child, I will only need to have the FKs of the parents as fields in the object that will be used by the XML file to do the insert (has some other fields as well).

I can use the following POJO for this (INSERT):

class Child {
    private Long id;
    private Long firstParentID; // FK_1
    private Long secondParentID; // FK_2
    // other fields
}

However, when doing SELECTs, I will want to do a retrieval of some of the fields that SecondParent contains.
Lets say that SecondParent is the following:

class SecondParent {
    private Long id;
    private Long firstname;
    private Long lastname;
}

Meaning when **selecting **children objects (In the app I will retrieve the FirstParent, with the list of Child, where each Child will need to contain some of the data that the SecondParent table has), I will need to have the following data in each Child POJO:

OPTION 1:

class Child {
    private Long id;
    private Long firstParentID; // FK_1

    private Long secondParentID; // FK_2
    private String secondParentFirstname; // data that is contained in the SecondParent table
    private String secondParentLastname; // data that is contained in the SecondParent table
}

Would using the above object be considered fine? It may seem like a DTO rather than a model (since it contains fields that are not part of the Child table: secondParentFirstname, secondParentLastname). When inserting obviously the fields secondParentFirstname, **secondParentLastname **would be irrelevant.

Would something like the below object be more appropriate:
OPTION 2:

class Child {
    private Long id;
    private Long firstParentID; // FK_1

    private Long secondParentID; // FK_2 - for insert might be easier to have it also outside the SecondParent object
    private SecondParent secondParent;
}

The SecondParent object is very big, and in this case I would only need a few of the column values of its table.

Personally, I would find the first option (the flat Child POJO -- OPTION 1) to be easier for both insert and select, since the converters in service layer would also be simpler.
But is the fact that it also contains fields that represent columns of the parent table, considered a bad practice ?


来源: stackexchange

问:
Key error while creating Auto Scaling groups in AWS EC2
I'm trying to write an Ansible playbook that creates a Launch Template in AWS. For some reason, i'm getting an error of KeyError: 'launch_config_name' while creating the Auto Scaling groups. I find it super weird, since i don't have a param of Launch Configuration.

In addition, i see in AWS consul that the new Launch Template is associated is added to the Autoscaling Group, and everything seems to be working properly. What could be the issue?

Ansible core version: 2.12.9

```<code>- name: create launch template
  community.aws.ec2_launch_template:
    name: "{{ service }}-lt-{{ date.stdout }}"
    state: present
    region:  "{{ region }}"
    image_id: "{{ image_id }}"
    key_name: "{{ key_name }}"
    security_group_ids: "{{ sg }}"
    instance_type: "{{ instance_type }}"
    iam_instance_profile: "{{ iam_instance_profile }}"

  - name: create auto scaling group
    community.aws.ec2_asg:
      name: "{{ service }}"
      state: present
      region: "{{ region }}"
      load_balancers: "{{  service +'-lb' }}"
      target_group_arns:
        - "{{ service_target_group_arn }}"
      launch_template:
        launch_template_name: "{{ service }}-lt-{{ date.stdout }}"
      health_check_period: "{{ health_check_period }}"
      health_check_type: "{{ health_check_type }}"
      metrics_collection: yes
      replace_all_instances: yes
      replace_batch_size: "{{ max_size|int - desired_capacity|int }}"
      min_size: "{{ min_size }}"
      max_size: "{{ max_size }}"
      desired_capacity: "{{ desired_capacity }}"
      vpc_zone_identifier:
        - "{{ p1 }}"
        - "{{ p2 }}"
      wait_for_instances: true
      wait_timeout: "{{ wait_timeout }}"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write an Ansible playbook that creates a Launch Template in AWS. For some reason, i'm getting an error of KeyError: 'launch_config_name' while creating the Auto Scaling groups. I find it super weird, since i don't have a param of Launch Configuration.

In addition, i see in AWS consul that the new Launch Template is associated is added to the Autoscaling Group, and everything seems to be working properly. What could be the issue?

Ansible core version: 2.12.9

- name: create launch template
  community.aws.ec2_launch_template:
    name: "{{ service }}-lt-{{ date.stdout }}"
    state: present
    region:  "{{ region }}"
    image_id: "{{ image_id }}"
    key_name: "{{ key_name }}"
    security_group_ids: "{{ sg }}"
    instance_type: "{{ instance_type }}"
    iam_instance_profile: "{{ iam_instance_profile }}"

  - name: create auto scaling group
    community.aws.ec2_asg:
      name: "{{ service }}"
      state: present
      region: "{{ region }}"
      load_balancers: "{{  service +'-lb' }}"
      target_group_arns:
        - "{{ service_target_group_arn }}"
      launch_template:
        launch_template_name: "{{ service }}-lt-{{ date.stdout }}"
      health_check_period: "{{ health_check_period }}"
      health_check_type: "{{ health_check_type }}"
      metrics_collection: yes
      replace_all_instances: yes
      replace_batch_size: "{{ max_size|int - desired_capacity|int }}"
      min_size: "{{ min_size }}"
      max_size: "{{ max_size }}"
      desired_capacity: "{{ desired_capacity }}"
      vpc_zone_identifier:
        - "{{ p1 }}"
        - "{{ p2 }}"
      wait_for_instances: true
      wait_timeout: "{{ wait_timeout }}"


问:
Setting up clientwebsocket with TLS v 1.3
I have a service which supports tls 1.3.

Upon research I found that clientwebsocket only supports tls 1.2

I tried to use Clientwebsocket with http2:

```<code>using SocketsHttpHandler handler = new();
Socket.ConnectAsync(Host, new HttpMessageInvoker(handler), CancellationToken.None).Wait();
</code>```

But that one does not let me set certificates:

```<code>ArgumentException: UseDefaultCredentials, Credentials, Proxy,
ClientCertificates, RemoteCertificateValidationCallback and Cookies
must not be set on ClientWebSocketOptions when an HttpMessageInvoker
instance is also specified. These options should be set on the
HttpMessageInvoker's underlying HttpMessageHandler instead.
(Parameter 'options')
</code>```

I have not found reference on microsoft on how to set these options. Id be happy if you either could show an example f how to bring the "classic" clientwebsocket to tls 1.3 or how to specify the options on the httpmessagehandler with http2

Body:
I have a service which supports tls 1.3.

Upon research I found that clientwebsocket only supports tls 1.2

I tried to use Clientwebsocket with http2:

using SocketsHttpHandler handler = new();
Socket.ConnectAsync(Host, new HttpMessageInvoker(handler), CancellationToken.None).Wait();

But that one does not let me set certificates:

ArgumentException: UseDefaultCredentials, Credentials, Proxy,
ClientCertificates, RemoteCertificateValidationCallback and Cookies
must not be set on ClientWebSocketOptions when an HttpMessageInvoker
instance is also specified. These options should be set on the
HttpMessageInvoker's underlying HttpMessageHandler instead.
(Parameter 'options')

I have not found reference on microsoft on how to set these options. Id be happy if you either could show an example f how to bring the "classic" clientwebsocket to tls 1.3 or how to specify the options on the httpmessagehandler with http2


问:
Flutter App - Sign In with Apple not returning Name to Firebase. Why?
I have a Flutter app that uses the sign in with Apple package with Firebase, however I'm unable to return the user's name. How can I return the Apple user name? Any help would be appreciated.

Here is the code I have so far. Any thoughts to what I'm missing?

```<code>
Future<UserCredential> appleSignIn() async {
  if (kIsWeb) {
    final provider = OAuthProvider("apple.com")
      ..addScope('email')
      ..addScope('name');

    // Sign in the user with Firebase.
    return await FirebaseAuth.instance.signInWithPopup(provider);
  }

  final rawNonce = generateNonce();
  final nonce = sha256ofString(rawNonce);

  // Request credential for the currently signed in Apple account.
  final appleCredential = await SignInWithApple.getAppleIDCredential(
    scopes: [
      AppleIDAuthorizationScopes.email,
      AppleIDAuthorizationScopes.fullName,
    ],
    nonce: nonce,
  );

  // Create an `OAuthCredential` from the credential returned by Apple.
  final oauthCredential = OAuthProvider("apple.com").credential(
    idToken: appleCredential.identityToken,
    rawNonce: rawNonce,
  );

  // Sign in the user with Firebase. If the nonce we generated earlier does
  // not match the nonce in `appleCredential.identityToken`, sign in will fail.
  return await FirebaseAuth.instance.signInWithCredential(oauthCredential);
}

Future<User?> signInWithApple(BuildContext context) =>
    signInOrCreateAccount(context, appleSignIn, 'APPLE');
</code>```

Body:
I have a Flutter app that uses the sign in with Apple package with Firebase, however I'm unable to return the user's name. How can I return the Apple user name? Any help would be appreciated.

Here is the code I have so far. Any thoughts to what I'm missing?

Future<UserCredential> appleSignIn() async {
  if (kIsWeb) {
    final provider = OAuthProvider("apple.com")
      ..addScope('email')
      ..addScope('name');

    // Sign in the user with Firebase.
    return await FirebaseAuth.instance.signInWithPopup(provider);
  }

  final rawNonce = generateNonce();
  final nonce = sha256ofString(rawNonce);

  // Request credential for the currently signed in Apple account.
  final appleCredential = await SignInWithApple.getAppleIDCredential(
    scopes: [
      AppleIDAuthorizationScopes.email,
      AppleIDAuthorizationScopes.fullName,
    ],
    nonce: nonce,
  );

  // Create an `OAuthCredential` from the credential returned by Apple.
  final oauthCredential = OAuthProvider("apple.com").credential(
    idToken: appleCredential.identityToken,
    rawNonce: rawNonce,
  );

  // Sign in the user with Firebase. If the nonce we generated earlier does
  // not match the nonce in `appleCredential.identityToken`, sign in will fail.
  return await FirebaseAuth.instance.signInWithCredential(oauthCredential);
}

Future<User?> signInWithApple(BuildContext context) =>
    signInOrCreateAccount(context, appleSignIn, 'APPLE');


问:
Add a character to end of every line in VBA code
I've a VBA code, which takes values from excel spreadsheet and imports them into a txt file in a certain view. What I need is to add a character "||" at the end of every row in the output file, but since I'm very new to coding, don't find the right "code wording".

Current code:

```<code>Sub OutputToTextFile()
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
    Dim FileName As String, LineText As String
    Dim MyRange As Range, i, j

    FileName = "C:\data\output.txt"

    Open FileName For Output As #1

    Set MyRange = Range("A1:G20")
    For i = 1 To MyRange.Rows.Count
        For j = 1 To MyRange.Columns.Count
            LineText = IIf(j = 1, "", LineText & " | ") & MyRange.Cells(i, j)
        Next j
        Print #1, LineText
    Next i

    Close #1

End Sub
</code>```

Current output (single example only):

IBAN311 | Apple | IBAN123123 | BIC | BGN | IBAN311 | INV-12343
```

What I need is to have an additional "||" character after the "INV-12343" and same for every row in the range. How can I add that in the above code?

Body:
I've a VBA code, which takes values from excel spreadsheet and imports them into a txt file in a certain view. What I need is to add a character "||" at the end of every row in the output file, but since I'm very new to coding, don't find the right "code wording".

Current code:

Sub OutputToTextFile()
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
    Dim FileName As String, LineText As String
    Dim MyRange As Range, i, j

    FileName = "C:\data\output.txt"

    Open FileName For Output As #1

    Set MyRange = Range("A1:G20")
    For i = 1 To MyRange.Rows.Count
        For j = 1 To MyRange.Columns.Count
            LineText = IIf(j = 1, "", LineText & " | ") & MyRange.Cells(i, j)
        Next j
        Print #1, LineText
    Next i

    Close #1

End Sub

Current output (single example only):

IBAN311 | Apple | IBAN123123 | BIC | BGN | IBAN311 | INV-12343

What I need is to have an additional "||" character after the "INV-12343" and same for every row in the range. How can I add that in the above code?


Title: How can I average separate variables by minute

Body:
I want to find the average value of Var1, Var2, and Var3 by minute.

Here is the structure of my data:

> dput(df)
structure(list(Date_Time = structure(c(1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602780, 1609602780, 1609602780, 1609602780, 1609602780, 1609602780,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602840, 1609602840,
1609602840, 1609602840, 1609602840, 1609602840, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, 1609602900, 1609602900, 1609602900, 1609602900, 1609602900,
1609602900, NA), class = c("POSIXct", "POSIXt"), tzone = ""),
    Var1 = c(3, 3, 3, 3, 3, 3, 15, 3, 4, 3, 3, 3, 3, 3, 3, 3,
    2, 3, 3, 3, 3, 3, 3, 3, 1.4, 3, 3, 3, 3, 3, 3, 2.7, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 1.3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 1.7, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 2.7, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, NA), Var2 = c(1.3, 1.3, 1.3, 1.3, 1.3, 0, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 3, 1.3, 1.3, 1.3, 1.3,
    2, 1.6, 1.3, 1.3, 1.3, 5.6, 1.3, 1.1, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 4, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    5.1, 1.3, 1.3, 1.3, 1.3, 1.3, 2.8, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3,
    NA), Var3 = c(4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 1.3, 4.5, 4.5,
    4.5, 4.5, 4.5, 1.2, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 7.9, 4.5, 4.5, 4.5, 4.5, 4.5, 3.3, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 3.3,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.3, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 1.3,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 8.3, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 5, 4.5, 4.5, 4.5, 4.5,
    4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,
    NA)), row.names = c(NA, -226L), class = "data.frame")

Also, my Date_Time variable is indeed a date/time variable, but it looks like when I use dput() it converts it to a numeric string. Please let me know if I need to fix this.

In case the Date_Time variable from dput() does not work, please use this instead:

> print(df$Date_Time)
  [1] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
  [4] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
  [7] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [10] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [13] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [16] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [19] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [22] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [25] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [28] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [31] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [34] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [37] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [40] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [43] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [46] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [49] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [52] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST"
 [55] "2021-01-02 07:53:00 PST" "2021-01-02 07:53:00 PST" "2021-01-02 07:54:00 PST"
 [58] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [61] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [64] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [67] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [70] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [73] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [76] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [79] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [82] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [85] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [88] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [91] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [94] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
 [97] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
[100] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
[103] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
[106] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
[109] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
[112] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
[115] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
[118] "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST" "2021-01-02 07:54:00 PST"
[121] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[124] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[127] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[130] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[133] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[136] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[139] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[142] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[145] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[148] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[151] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[154] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[157] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[160] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[163] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[166] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[169] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[172] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[175] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[178] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[181] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[184] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[187] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[190] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[193] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[196] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[199] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[202] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[205] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[208] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[211] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[214] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[217] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[220] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"
[223] "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST" "2021-01-02 07:55:00 PST"


问:
How to deploy multiple Android/IOS app builds with same codebase on flutterflow?
I'm starting a new project that will sell "white label" apps, all with the same funcionality, just changing some resources and colors.
There is any way to build an app in flutterflow and have multiple builds, each one with a config file for that specific build
The intention is everytime I update the app code and funcionality, all my clients will receive the updated version, each one with their custom name/skin.
Thanks

I didnt find any way to do this in flutterflow, the apps have a single output for each platform and cloned projects stay obsolete when I update the main app.


问:
Why does my state variable from Context return "Uncaught SyntaxError: ambiguous indirect export: ThemeContext"?
I have been trying to create a simple theme changing functionality for my React app and I use DaisyUI's dataTheme to switch between premade themes.

I have set up a context for Themes and try to use a variable from it in my App.jsx but it always gives error "Uncaught SyntaxError: ambiguous indirect export: ThemeContext".

I have tried moving my import out of {} such as "import { ThemeContext, ThemeProvider } from "./context/theme/ThemeContext"

but this time I encountered "Uncaught TypeError: useContext(...) is undefined". I don't know why I cannot use "useContext" in my App.jsx. I can use it in other components.

Here are the code blocks:

ThemeContext.jsx

```<code>import { createContext, useState } from "react";

const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState("synthwave");

  const setDark = () => {
    setTheme("dark");
  };

  const setCyberpunk = () => {
    setTheme("cyberpunk");
  };

  const setRetro = () => {
    setTheme("retro");
  };

  return (
    <ThemeContext.Provider
      value={{
        theme,
        setDark,
        setCyberpunk,
        setRetro,
      }}
    >
      {children}
    </ThemeContext.Provider>
  );
};

export default ThemeContext;

</code>```

App.jsx

```<code>import "./App.css";
import { Theme, Button } from "react-daisyui";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Navbar from "./components/layout/NavBar";
import Footer from "./components/layout/Footer";
import Alert from "./components/layout/Alert";
import Home from "./pages/Home";
import About from "./pages/About";
import Notfound from "./pages/Notfound";
import User from "./components/users/User";
import { GithubProvider } from "./context/github/GithubContext";
import { AlertProvider } from "./context/alert/AlertContext";

import { ThemeContext, ThemeProvider } from "./context/theme/ThemeContext";
import { useContext } from "react";

function App() {
  const { theme } = useContext(ThemeContext);
  return (
    <ThemeProvider>
      <GithubProvider>
        <AlertProvider>
          <Theme dataTheme={theme}>
            <Router>
              <div className="min-h-screen flex flex-col justify-between">
                <Navbar />
                <main className="container mx-auto px-3 pb-12 ">
                  <Alert />

                  <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/about" elemen t={<About />} />
                    <Route path="/user/:login" element={<User />} />
                    <Route path="/notfound" element={<Notfound />} />
                    <Route path="/*" element={<Notfound />} />
                  </Routes>
                </main>

                <Footer />
              </div>
            </Router>
          </Theme>
        </AlertProvider>
      </GithubProvider>
    </ThemeProvider>
  );
}

export default App;

</code>```

ThemeDrop.jsx (a dropdown that I store in my navbar for easy access, everything works just fine in this one)

```<code>import React from "react";
import { useContext } from "react";
import ThemeContext from "../../context/theme/ThemeContext";

function ThemeDrop() {
  const { theme, setDark, setCyberpunk, setRetro } = useContext(ThemeContext);
  return (
    <div className="dropdown">
      <label tabIndex={0} className="btn btn-ghost btn-sm rounded-btn ">
        Click
      </label>
      <ul
        tabIndex={0}
        className="dropdown-content menu p-2 shadow bg-base-content rounded-box w-52"
      >
        <li>
          <button onClick={setDark}>Dark Theme</button>
        </li>
        <li>
          <a onClick={setCyberpunk}>Cyberpunk THeme</a>
        </li>
        <li>
          <a onClick={setRetro}>Retro THeme</a>
          <a>{theme}</a>
        </li>
      </ul>
    </div>
  );
}

export default ThemeDrop;

</code>```

NavBar.jsx (where I put my dropdown)

```<code>import React from "react";
import { FaGithub } from "react-icons/fa";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import ThemeDrop from "./ThemeDrop";

function Navbar({ title }) {
  return (
    <nav className="navbar mb-12 bg-neutral text-neutral-content">
      <div className="container mx-auto">
        <div className="flex-none px-2 mx-2">
          <FaGithub className="inline pr-2 text-3xl" />
          <Link
            to="/"
            className="text-lg font-bold align-middle hover:bg-neutral-focus"
          >
            {title}
          </Link>
        </div>
        <div className="flex-1 px-2 mx-2">
          <div className="flex justify-end">
            <Link to="/" className="btn btn-ghost btn-sm rounded-btn">
              Home
            </Link>
            <Link to="/about" className="btn btn-ghost btn-sm rounded-btn">
              About
            </Link>
            <ThemeDrop />
          </div>
        </div>
      </div>
    </nav>
  );
}

Navbar.defaultProps = {
  title: "Github Finder",
};

Navbar.propTypes = {
  title: PropTypes.string,
};

export default Navbar;

</code>```

I hope it was clear and I can get some guidance on this one. I must have made a very rookie mistake somewhere. I am able to achieve theme changing through state management but I am eager to use context api for this!

Appreciate any help

Body:
I have been trying to create a simple theme changing functionality for my React app and I use DaisyUI's dataTheme to switch between premade themes.

I have set up a context for Themes and try to use a variable from it in my App.jsx but it always gives error "Uncaught SyntaxError: ambiguous indirect export: ThemeContext".

I have tried moving my import out of {} such as "import { ThemeContext, ThemeProvider } from "./context/theme/ThemeContext"

but this time I encountered "Uncaught TypeError: useContext(...) is undefined". I don't know why I cannot use "useContext" in my App.jsx. I can use it in other components.

Here are the code blocks:

ThemeContext.jsx

import { createContext, useState } from "react";

const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState("synthwave");

  const setDark = () => {
    setTheme("dark");
  };

  const setCyberpunk = () => {
    setTheme("cyberpunk");
  };

  const setRetro = () => {
    setTheme("retro");
  };

  return (
    <ThemeContext.Provider
      value={{
        theme,
        setDark,
        setCyberpunk,
        setRetro,
      }}
    >
      {children}
    </ThemeContext.Provider>
  );
};

export default ThemeContext;

App.jsx

import "./App.css";
import { Theme, Button } from "react-daisyui";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Navbar from "./components/layout/NavBar";
import Footer from "./components/layout/Footer";
import Alert from "./components/layout/Alert";
import Home from "./pages/Home";
import About from "./pages/About";
import Notfound from "./pages/Notfound";
import User from "./components/users/User";
import { GithubProvider } from "./context/github/GithubContext";
import { AlertProvider } from "./context/alert/AlertContext";

import { ThemeContext, ThemeProvider } from "./context/theme/ThemeContext";
import { useContext } from "react";

function App() {
  const { theme } = useContext(ThemeContext);
  return (
    <ThemeProvider>
      <GithubProvider>
        <AlertProvider>
          <Theme dataTheme={theme}>
            <Router>

                <Navbar />

                  <Alert />

                  <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/about" elemen t={<About />} />
                    <Route path="/user/:login" element={<User />} />
                    <Route path="/notfound" element={<Notfound />} />
                    <Route path="/*" element={<Notfound />} />
                  </Routes>

            </Router>
          </Theme>
        </AlertProvider>
      </GithubProvider>
    </ThemeProvider>
  );
}

export default App;

ThemeDrop.jsx (a dropdown that I store in my navbar for easy access, everything works just fine in this one)

import React from "react";
import { useContext } from "react";
import ThemeContext from "../../context/theme/ThemeContext";

function ThemeDrop() {
  const { theme, setDark, setCyberpunk, setRetro } = useContext(ThemeContext);
  return (

        Click

          <button onClick={setDark}>Dark Theme</button>

          Cyberpunk THeme

          Retro THeme
          {theme}

  );
}

export default ThemeDrop;

NavBar.jsx (where I put my dropdown)

import React from "react";
import { FaGithub } from "react-icons/fa";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import ThemeDrop from "./ThemeDrop";

function Navbar({ title }) {
  return (

          <FaGithub className="inline pr-2 text-3xl" />
          <Link
            to="/"
            className="text-lg font-bold align-middle hover:bg-neutral-focus"
          >
            {title}
          </Link>

            <Link to="/" className="btn btn-ghost btn-sm rounded-btn">
              Home
            </Link>
            <Link to="/about" className="btn btn-ghost btn-sm rounded-btn">
              About
            </Link>
            <ThemeDrop />

  );
}

Navbar.defaultProps = {
  title: "Github Finder",
};

Navbar.propTypes = {
  title: PropTypes.string,
};

export default Navbar;

I hope it was clear and I can get some guidance on this one. I must have made a very rookie mistake somewhere. I am able to achieve theme changing through state management but I am eager to use context api for this!

Appreciate any help


问:
In simple form: how can I define a different class for boolean inputs?
I have the following in a simple_form initializer:

  config.wrappers :default, tag: "div", class: "my-form-group", error_class: "has-error" do |b|
    b.use :html5
    b.use :placeholder
    b.use :label, class: "my-label"
    b.use :input, class: "my-input"
    b.use :error, wrap_with: { tag: "span", class: "help-inline" }
    b.use :hint,  wrap_with: { tag: "p", class: "help-block" }
  end
```
<p>This generates the HTML I am hoping for:</p>
<pre class="lang-html prettyprint-override"><code><div class="my-form-group string optional software_instance_status">
  <label class="my-label string optional" for="software_instance_status">Status</label>
  <input class="my-input string optional" type="text" name="software_instance[status]" id="software_instance_status">
</div>
</code>```

Except, that I do not want this styling to apply to boolean fields (e.g. checkboxes).

How do I restrict this styling to inputs that are not boolean fields and/or how do apply a separate set of rules (specifically the input class) for boolean fields?

Body:
I have the following in a simple_form initializer:

  config.wrappers :default, tag: "div", class: "my-form-group", error_class: "has-error" do |b|
    b.use :html5
    b.use :placeholder
    b.use :label, class: "my-label"
    b.use :input, class: "my-input"
    b.use :error, wrap_with: { tag: "span", class: "help-inline" }
    b.use :hint,  wrap_with: { tag: "p", class: "help-block" }
  end

This generates the HTML I am hoping for:

  Status
  <input class="my-input string optional" type="text" name="software_instance[status]" id="software_instance_status">

Except, that I do not want this styling to apply to boolean fields (e.g. checkboxes).

How do I restrict this styling to inputs that are not boolean fields and/or how do apply a separate set of rules (specifically the input class) for boolean fields?


问:
Detection of a coordinate (long and lat) inside an ellipses area generated by another coordinate (long and lat)a
I have two CSV files, let's call it File 1 and File 2 and they have the following information

File 1:
*Unit is the machine ID and then its location by Latitude and Longitude

Unit
Latitude
Longitude

1
41.165382
-94.254983

2
41.167991
-94.262962

3
41.165627
-94.291968

4
41.165379
-94.296693

5
41.167441
-94.316156

File 2:
*These are lightning strikes occurred in the vicinity area around the Units from File 1. Each lightning strike (1 row) has date, latitude, longitude and the generation of an ellipse area from the longitude and latitude of the strike defined by the following columns:
error_elipse_angle / error_elipse_semi_major / error_elipse_semi_minor
In other words, each lightning strike generates an ellipse area.

The representation of the ellipse from the strike location is  here Ellipse Representation.

Event
dateUTC
latitude
longitude
elipse_angle
elipse_semi_major
elipse_semi_minor

1
10-03-21 8:48
42.0949
-94.5073
2.6
0.2
0.2

2
03-05-21 9:01
41.8341
-94.3017
68.2
0.2
0.2

3
08-05-21 23:23
42.3909
-94.2536
33.7
0.2
0.2

4
08-05-21 23:25
42.3651
-94.4082
151.3
0.9
0.4

5
08-05-21 23:25
42.3725
-94.4174
175
0.2
0.2

The exercise here is to detect if in any of the ellipse areas generated by the lightning strikes from File 2 , it can be found Units from File 1. The identification of a Unit based on latitude and longidute from File 1 inside of a lightning strike ellipse area from File 2 means that most likely the lightning strike impacted in the Unit. If the Unit is outside of the lightning strike ellipse area, there is a low probability the lightning impacted on the unit.

Having said above, I would like to get a table like the File 2 the results by with the agregation of two columns such as:

Ellipse_into_unit: Basically a binary result by 0 or 1 where :
*0 is NO and it means that no Unit locations were found inside the ellipse areas generated by the lightning strikes
*1 is YES and it means that unit locations were found inside the ellipse areas generated by the lightning strikes

Affected_Unit : The Unit Id from File 1 listed in case there has been Units detected inside lightning strike ellipse areas.

Just as example if there were Units detected on lightning strikes 1 4 and 5, the result table would be:

Event
dateUTC
latitude
longitude
elipse_angle
elipse_semi_major
elipse_semi_minor
Ellipse_into_unit
Affected_Unit

1
10-03-21 8:48
42.0949
-94.5073
2.6
0.2
0.2
1
1-2-3

2
03-05-21 9:01
41.8341
-94.3017
68.2
0.2
0.2
0

3
08-05-21 23:23
42.3909
-94.2536
33.7
0.2
0.2
0

4
08-05-21 23:25
42.3651
-94.4082
151.3
0.9
0.4
1
1-2

5
08-05-21 23:25
42.3725
-94.4174
175
0.2
0.2
1
3

Visualization of the Event 1

I was having a hard time trying to develop this and I haven't had success. I would appreciate if you can help or guide me on this please, THAN YOU SO MUCH.

Do you think is possible to also show a map or graph for the results? (see the lightning strikes ellipse areas and the unit locations?


问:
Conditionally handling .net6 exceptions based on if the error occurs on an ajax call
I am trying to configure error handling in progam.cs to handle errors based on whether or not the error occurred in an ajax function. If the error occurred during an AJAX call, I want to write

await context.Response.WriteAsJsonAsync(problem);

otherwise I want to redirect the user to an error page.

I can successfully determine if the error was generated in an ajax call as such:

```<code>app.UseExceptionHandler(e =>
        {

            e.Run(async context =>
            {

                bool isAjaxCall = context.Request.Headers["x-requested-with"] == "XMLHttpRequest";

                var feature = context.Features.Get<IExceptionHandlerPathFeature>();
                var error = feature?.Error;

                var problem = new ProblemDetails
                {

                    Status = context.Response.StatusCode,
                    Title = error?.Message,
                    Type = isAjaxCall ? "Ajax" : "Unhandled Exception",
                };

                if (isDevelopment)
                    problem.Extensions.Add("stack", error?.StackTrace);

                problem.Extensions.Add("Path", feature == null ? String.Empty : feature?.Endpoint?.DisplayName);

                string? userName = "Anonymous";
                if (context.User != null && context.User.Identity != null && context.User.Identity.IsAuthenticated)
                    userName = context?.User?.Identity?.Name;

                problem.Extensions.Add("User", userName);

                if (isAjaxCall)
                    await context.Response.WriteAsJsonAsync(problem);
                else
                    await [What do I do here to redirect?]

            });
        });
</code>```

Or am I using the wrong approach?

Body:
I am trying to configure error handling in progam.cs to handle errors based on whether or not the error occurred in an ajax function. If the error occurred during an AJAX call, I want to write

await context.Response.WriteAsJsonAsync(problem);

otherwise I want to redirect the user to an error page.

I can successfully determine if the error was generated in an ajax call as such:

app.UseExceptionHandler(e =>
        {

            e.Run(async context =>
            {

                bool isAjaxCall = context.Request.Headers["x-requested-with"] == "XMLHttpRequest";

                var feature = context.Features.Get<IExceptionHandlerPathFeature>();
                var error = feature?.Error;

                var problem = new ProblemDetails
                {

                    Status = context.Response.StatusCode,
                    Title = error?.Message,
                    Type = isAjaxCall ? "Ajax" : "Unhandled Exception",
                };

                if (isDevelopment)
                    problem.Extensions.Add("stack", error?.StackTrace);

                problem.Extensions.Add("Path", feature == null ? String.Empty : feature?.Endpoint?.DisplayName);

                string? userName = "Anonymous";
                if (context.User != null && context.User.Identity != null && context.User.Identity.IsAuthenticated)
                    userName = context?.User?.Identity?.Name;

                problem.Extensions.Add("User", userName);

                if (isAjaxCall)
                    await context.Response.WriteAsJsonAsync(problem);
                else
                    await [What do I do here to redirect?]

            });
        });

Or am I using the wrong approach?


问:
how should I compare two strings case-insensitively
I am making a little rock paper scissors game in rust as a little mini-project while I learn the language. I have made the code below, but it seems that no matter what I do, it always prints "Invalid Response."

My current code:

fn start_next() {
    thread::sleep(time::Duration::from_secs(3));
    rps();
}

fn rps() {
    let rk = String::from("rock");
    let pp = String::from("paper");
    let sc = String::from("scissors");
    let end = String::from("end");

    let mut guess = String::new();
    println!("Choose one (\"end\" to quit):\n- rock\n- paper\n- scissors");

    io::stdin().read_line(&mut guess).expect("Unable to read line");
    let aichoice = ["rock", "paper", "scissors"][(rand::random::<u8>() % 3) as usize];

    // debug
    println!("\nAI chose {}", aichoice);
    println!("You chose {}", guess);

    if guess.eq_ignore_ascii_case(&rk) {
        match aichoice {
            "rock" => {
                println!("Your moves canceled out.");
            }
            "paper" => {
                println!("Paper defated your rock.");
            }
            "scissors" => {
                println!("You defeated scissors");
            }
            _ => {}
        }

        start_next();
        return;
    }
     if guess.eq_ignore_ascii_case(&pp) {
        match aichoice {
            "rock" => {
                println!("You defeated rock.");
            }
            "paper" => {
                println!("Your moves canceled out.");
            }
            "scissors" => {
                println!("Scissors defeated your paper.");
            }
            _ => {}
        }

        start_next();
        return;
    }
    if guess.eq_ignore_ascii_case(&sc) {
        match aichoice {
            "rock" => {
                println!("Rock defeated your scissors.");
            }
            "paper" => {
                println!("You defeated paper.");
            }
            "scissors" => {
                println!("Your moves canceled out.");
            }
            _ => {}
        }

        start_next();
        return;
    }
    if guess.eq_ignore_ascii_case(&end) {
        return;
    }

    println!("Invalid response");
    start_next();
}
```
<p>(yes, ik this if chaining kind of sucks, but I am trying this because it wouldn't work with string.to_lowercase() and match)</p>
<p>I had previously, like I mentioned, tried to use a match case statement to do it, but it had the same results.</p>
<p>My previous code was something like this:</p>
<pre class="lang-rust prettyprint-override"><code>let mut guess = String::new();
println!("Choose one (\"end\" to quit):\n- rock\n- paper\n- scissors");

io::stdin().read_line(&mut guess).expect("Unable to read line");

let aichoice = ["rock", "paper", "scissors"][(rand::random::<u8>() % 3) as usize];
let guess2: &str = &*guess.to_lowercase();

match guess2 {
    case "rock" => {
        ...
    }

    case "paper" => {
        ...
    }

    case "scissors" => {
        ...
    }

    case "end" => {
        return;
    }

    case _ => {
        println!("Invalid Response");
    }
}

thread::sleep(time::Duration::from_secs(3));
rps();
</code>```

My guess is I either made some random mistake both times or have something wrong with my Rust installation.

I also tested with my previous code and to_lowercase() was working, just something with comparing strings that I don't understand.

Body:
I am making a little rock paper scissors game in rust as a little mini-project while I learn the language. I have made the code below, but it seems that no matter what I do, it always prints "Invalid Response."

My current code:

fn start_next() {
    thread::sleep(time::Duration::from_secs(3));
    rps();
}

fn rps() {
    let rk = String::from("rock");
    let pp = String::from("paper");
    let sc = String::from("scissors");
    let end = String::from("end");

    let mut guess = String::new();
    println!("Choose one (\"end\" to quit):\n- rock\n- paper\n- scissors");

    io::stdin().read_line(&mut guess).expect("Unable to read line");
    let aichoice = ["rock", "paper", "scissors"][(rand::random::<u8>() % 3) as usize];

    // debug
    println!("\nAI chose {}", aichoice);
    println!("You chose {}", guess);

    if guess.eq_ignore_ascii_case(&rk) {
        match aichoice {
            "rock" => {
                println!("Your moves canceled out.");
            }
            "paper" => {
                println!("Paper defated your rock.");
            }
            "scissors" => {
                println!("You defeated scissors");
            }
            _ => {}
        }

        start_next();
        return;
    }
     if guess.eq_ignore_ascii_case(&pp) {
        match aichoice {
            "rock" => {
                println!("You defeated rock.");
            }
            "paper" => {
                println!("Your moves canceled out.");
            }
            "scissors" => {
                println!("Scissors defeated your paper.");
            }
            _ => {}
        }

        start_next();
        return;
    }
    if guess.eq_ignore_ascii_case(&sc) {
        match aichoice {
            "rock" => {
                println!("Rock defeated your scissors.");
            }
            "paper" => {
                println!("You defeated paper.");
            }
            "scissors" => {
                println!("Your moves canceled out.");
            }
            _ => {}
        }

        start_next();
        return;
    }
    if guess.eq_ignore_ascii_case(&end) {
        return;
    }

    println!("Invalid response");
    start_next();
}

(yes, ik this if chaining kind of sucks, but I am trying this because it wouldn't work with string.to_lowercase() and match)

I had previously, like I mentioned, tried to use a match case statement to do it, but it had the same results.

My previous code was something like this:

let mut guess = String::new();
println!("Choose one (\"end\" to quit):\n- rock\n- paper\n- scissors");

io::stdin().read_line(&mut guess).expect("Unable to read line");

let aichoice = ["rock", "paper", "scissors"][(rand::random::<u8>() % 3) as usize];
let guess2: &str = &*guess.to_lowercase();

match guess2 {
    case "rock" => {
        ...
    }

    case "paper" => {
        ...
    }

    case "scissors" => {
        ...
    }

    case "end" => {
        return;
    }

    case _ => {
        println!("Invalid Response");
    }
}

thread::sleep(time::Duration::from_secs(3));
rps();

My guess is I either made some random mistake both times or have something wrong with my Rust installation.

I also tested with my previous code and to_lowercase() was working, just something with comparing strings that I don't understand.


问:
How do I put pre-plotted plots into one big grid?
I have plotted several plots and saved them in my envoriment as plot1 plot2 etc. (18 plots in total) I want to put them in the same grid so that they are all shown as one image side by side (6 in a row with 3 rows) Unfortunately I am unable to re-plot them inside a plt.subplot function since plotting them takes a lot of time.

I tried assigning axises as my plots like this:

```<code>fig, axs = plt.subplots(3, 6)

axs[0, 0].enter = plot1

axs[0, 1] = plot2
</code>```

but doesnt work. I also considered putting them in an image grid but that doesnt work eighter since they are plots and not images. the code below doesnt work for example:

```<code>
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, [plot1, plot2, plot3, plot4]):
    # Iterating over the grid returns the Axes.
    ax.imshow(im)

plt.show()
</code>```

Body:
I have plotted several plots and saved them in my envoriment as plot1 plot2 etc. (18 plots in total) I want to put them in the same grid so that they are all shown as one image side by side (6 in a row with 3 rows) Unfortunately I am unable to re-plot them inside a plt.subplot function since plotting them takes a lot of time.

I tried assigning axises as my plots like this:

fig, axs = plt.subplots(3, 6)

axs[0, 0].enter = plot1

axs[0, 1] = plot2

but doesnt work. I also considered putting them in an image grid but that doesnt work eighter since they are plots and not images. the code below doesnt work for example:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, [plot1, plot2, plot3, plot4]):
    # Iterating over the grid returns the Axes.
    ax.imshow(im)

plt.show()


问:
How to align Formly form-fields horizontally when using JSON Schema?
I use Formly form JSON schema to render my view. This way the inputs appear below the labels, yet I want the inputs to be displayed beside the labels.

I know that form-field-horizontal can be used to render horizontal inputs if the fields are explicitly defined with a wrapper. But how can I render the inputs horizontally using JSON schema and model?

I retrieve the fields via formlyJsonschema.toFieldConfig(schema).

For more information about the JSON schema I use, check out the following link: https://formly.dev/docs/examples/advanced/json-schema.


问:
How can I create an .exe file of a code (using python) that need a variable file path to work?
I’m new in IT field and I need some advice for how can I solve this problem, using python. It’s a volunteer work for a Non-Profit Organization.

My script is done, but in the code there is reference to specific file path that only will work in my PC. I need to convert the script to .exe (pyinstaller), but it won’t work in other PCs, because the path will create an error.

My code use data from a xlsx and it also use an image .png, and both files are referenced in the code with the path that they are saved in my PC. How can I convert to .exe in a way that the program still working in other PCs? I need a way to pack both files and the script in the .exe (in this case, what do I put to replace the path in my code for a reference to this "packed file"?) or insert a variable path instead the specific path related only with mt PC. What are the ways to solve that?

Edit:
In resume, I need that this line of code work in other PCs after I convert the .py to an .exe file, using for that the pyinstaller:

```<code>import pandas as pd
dados = pd.read_excel(r"/Users/lucas/Documents/UDV/NE/Dados.xlsx")
</code>```

As the path is only related with my PC, if I try to convert to exe and open in other machine, it will result in a error message.

Thanks!
Obs: The .exe will be used for normal users, so I expected that in the final the person only will click on the .exe and it will do the job without hard commands by the user.

Body:
I’m new in IT field and I need some advice for how can I solve this problem, using python. It’s a volunteer work for a Non-Profit Organization.

My script is done, but in the code there is reference to specific file path that only will work in my PC. I need to convert the script to .exe (pyinstaller), but it won’t work in other PCs, because the path will create an error.

My code use data from a xlsx and it also use an image .png, and both files are referenced in the code with the path that they are saved in my PC. How can I convert to .exe in a way that the program still working in other PCs? I need a way to pack both files and the script in the .exe (in this case, what do I put to replace the path in my code for a reference to this "packed file"?) or insert a variable path instead the specific path related only with mt PC. What are the ways to solve that?

Edit:
In resume, I need that this line of code work in other PCs after I convert the .py to an .exe file, using for that the pyinstaller:

import pandas as pd
dados = pd.read_excel(r"/Users/lucas/Documents/UDV/NE/Dados.xlsx")

As the path is only related with my PC, if I try to convert to exe and open in other machine, it will result in a error message.

Thanks!
Obs: The .exe will be used for normal users, so I expected that in the final the person only will click on the .exe and it will do the job without hard commands by the user.


问:
Trying to make CommentVote functionality on comments
I am making a feature Request app (if page reloads I make fetch request to backend to get singleFeature and its component i.e. Comments)
Now what my problem is I want to get if comment is already liked or not?
if it is already liked then Heart icon will be red

If it is not already liked i.e. liked = false so i can like it.

I am trying to create a component and sending data from props -

My likeButton component -

```<code>import React from "react";
import { getCookie } from "../../api/auth";
import { voteComment } from "../../api/comment";

const LikeButton = ({ id, type, liked }) => {
  const token = getCookie("token");
  const handleLike = (e) => {
    e.preventDefault();
    console.log("Test");
    if (type === "comment") {
      voteComment(id, token).then((data) => {
        if (data.error) {
          console.log(data.error);
        } else if (data.success === true) {
          liked(true);
        } else if (data.success === false) {
          liked(false);
        }
      });
    }
  };

  return (
    <div className="mt-1">
      <input type="checkbox" id="checkbox" onChange={handleLike} />
      <label for="checkbox">
        <svg
          id="heart-svg"
          viewBox="467 392 58 57"
          xmlns="http://www.w3.org/2000/svg"
          // onClick={() => console.log("ABC")}
        >
          <g
            id="Group"
            fill="none"
            fill-rule="evenodd"
            transform="translate(467 392)"
          >
            <path
              d="M29.144 20.773c-.063-.13-4.227-8.67-11.44-2.59C7.63 28.795 28.94 43.256 29.143 43.394c.204-.138 21.513-14.6 11.44-25.213-7.214-6.08-11.377 2.46-11.44 2.59z"
              id="heart"
              fill="#AAB8C2"
            />
            <circle
              id="main-circ"
              fill="#E2264D"
              opacity="0"
              cx="29.5"
              cy="29.5"
              r="1.5"
            />

            <g id="grp7" opacity="0" transform="translate(7 6)">
              <circle id="oval1" fill="#9CD8C3" cx="2" cy="6" r="2" />
              <circle id="oval2" fill="#8CE8C3" cx="5" cy="2" r="2" />
            </g>

            <g id="grp6" opacity="0" transform="translate(0 28)">
              <circle id="oval1" fill="#CC8EF5" cx="2" cy="7" r="2" />
              <circle id="oval2" fill="#91D2FA" cx="3" cy="2" r="2" />
            </g>

            <g id="grp3" opacity="0" transform="translate(52 28)">
              <circle id="oval2" fill="#9CD8C3" cx="2" cy="7" r="2" />
              <circle id="oval1" fill="#8CE8C3" cx="4" cy="2" r="2" />
            </g>

            <g id="grp2" opacity="0" transform="translate(44 6)">
              <circle id="oval2" fill="#CC8EF5" cx="5" cy="6" r="2" />
              <circle id="oval1" fill="#CC8EF5" cx="2" cy="2" r="2" />
            </g>

            <g id="grp5" opacity="0" transform="translate(14 50)">
              <circle id="oval1" fill="#91D2FA" cx="6" cy="5" r="2" />
              <circle id="oval2" fill="#91D2FA" cx="2" cy="2" r="2" />
            </g>

            <g id="grp4" opacity="0" transform="translate(35 50)">
              <circle id="oval1" fill="#F48EA7" cx="6" cy="5" r="2" />
              <circle id="oval2" fill="#F48EA7" cx="2" cy="2" r="2" />
            </g>

            <g id="grp1" opacity="0" transform="translate(24)">
              <circle id="oval1" fill="#9FC7FA" cx="2.5" cy="3" r="2" />
              <circle id="oval2" fill="#9FC7FA" cx="7.5" cy="2" r="2" />
            </g>
          </g>
        </svg>
      </label>
    </div>
  );
};

export default LikeButton;
</code>```

Here id= commentId, type="comment, liked= true/ false based on the comment is liked or not
I have no idea how to create this functionality on backend and frontend
Please help.

My comment controller for votes-

```<code>exports.voteComment = (req, res) => {
  const { commentId } = req.params;
  if (!ObjectId.isValid(commentId)) {
    return res.status(400).send({
      error: "Comment ID not valid",
    });
  }
  CommentVote.findOneAndUpdate(
    {
      comment: commentId,
      // abhi loggedin user khud ke comment pe vote kar pa rha hai
      "comment.postedBy": { $ne: req.auth._id },
      "votes.postedBy": { $ne: req.auth._id },
    },
    { $push: { votes: { postedBy: req.auth._id } } },
    { new: true }
  ).exec((err, result) => {
    if (err) {
      console.log("abc", err);
      return res.status(400).json({
        error: "Could not vote on that comment",
      });
    }
    console.log(result);
    if (result === null) {
      const dislikeComment = CommentVote.findOneAndUpdate(
        {
          comment: commentId,
          postedBy: { $ne: req.auth._id },

        },
        {
          $pull: { votes: { postedBy: req.auth._id } },
        },
        { new: true }
      ).exec();

      if (dislikeComment) {
        console.log("double tap");
        return res.send({ success: false });
      }

    }
    res.send({ success: true });
  });
};
</code>```

my single comment frontend-

```<code> {isAuth() && !editing && (
                <div className="d-inline-flex float-right align-items-center">

                  {isAuth() && !(isAuth()._id === comment.postedBy._id) && (
                    <LikeButton
                      id={comment._id}
                      type="comment"
                      liked={(value) => {}}
                    />
                  )}

**my getComments controller below -**

</code>```
```<code>exports.getComments = (req, res) => {
  const { featureId } = req.params;
  console.log(featureId);
  Comment.find({ feature: featureId })
    .populate("postedBy", "_id username")
    .sort({ createdAt: -1 })
    .exec((err, comments) => {
      if (err) {
        // console.log(err);
        return res.status(400).send({
          error: errorHandler(err),
        });
      }
      return res.status(200).json(comments);
    });
}
</code>```

also is their any other way to do this?

Body:
I am making a feature Request app (if page reloads I make fetch request to backend to get singleFeature and its component i.e. Comments)
Now what my problem is I want to get if comment is already liked or not?
if it is already liked then Heart icon will be red

If it is not already liked i.e. liked = false so i can like it.

I am trying to create a component and sending data from props -

My likeButton component -

import React from "react";
import { getCookie } from "../../api/auth";
import { voteComment } from "../../api/comment";

const LikeButton = ({ id, type, liked }) => {
  const token = getCookie("token");
  const handleLike = (e) => {
    e.preventDefault();
    console.log("Test");
    if (type === "comment") {
      voteComment(id, token).then((data) => {
        if (data.error) {
          console.log(data.error);
        } else if (data.success === true) {
          liked(true);
        } else if (data.success === false) {
          liked(false);
        }
      });
    }
  };

  return (

      <input type="checkbox" id="checkbox" onChange={handleLike} />

        <svg
          id="heart-svg"
          viewBox="467 392 58 57"
          xmlns="http://www.w3.org/2000/svg"
          // onClick={() => console.log("ABC")}
        >
          <g
            id="Group"
            fill="none"
            fill-rule="evenodd"
            transform="translate(467 392)"
          >
            <path
              d="M29.144 20.773c-.063-.13-4.227-8.67-11.44-2.59C7.63 28.795 28.94 43.256 29.143 43.394c.204-.138 21.513-14.6 11.44-25.213-7.214-6.08-11.377 2.46-11.44 2.59z"
              id="heart"
              fill="#AAB8C2"
            />
            <circle
              id="main-circ"
              fill="#E2264D"
              opacity="0"
              cx="29.5"
              cy="29.5"
              r="1.5"
            />

            <g id="grp7" opacity="0" transform="translate(7 6)">
              <circle id="oval1" fill="#9CD8C3" cx="2" cy="6" r="2" />
              <circle id="oval2" fill="#8CE8C3" cx="5" cy="2" r="2" />
            </g>

            <g id="grp6" opacity="0" transform="translate(0 28)">
              <circle id="oval1" fill="#CC8EF5" cx="2" cy="7" r="2" />
              <circle id="oval2" fill="#91D2FA" cx="3" cy="2" r="2" />
            </g>

            <g id="grp3" opacity="0" transform="translate(52 28)">
              <circle id="oval2" fill="#9CD8C3" cx="2" cy="7" r="2" />
              <circle id="oval1" fill="#8CE8C3" cx="4" cy="2" r="2" />
            </g>

            <g id="grp2" opacity="0" transform="translate(44 6)">
              <circle id="oval2" fill="#CC8EF5" cx="5" cy="6" r="2" />
              <circle id="oval1" fill="#CC8EF5" cx="2" cy="2" r="2" />
            </g>

            <g id="grp5" opacity="0" transform="translate(14 50)">
              <circle id="oval1" fill="#91D2FA" cx="6" cy="5" r="2" />
              <circle id="oval2" fill="#91D2FA" cx="2" cy="2" r="2" />
            </g>

            <g id="grp4" opacity="0" transform="translate(35 50)">
              <circle id="oval1" fill="#F48EA7" cx="6" cy="5" r="2" />
              <circle id="oval2" fill="#F48EA7" cx="2" cy="2" r="2" />
            </g>

            <g id="grp1" opacity="0" transform="translate(24)">
              <circle id="oval1" fill="#9FC7FA" cx="2.5" cy="3" r="2" />
              <circle id="oval2" fill="#9FC7FA" cx="7.5" cy="2" r="2" />
            </g>
          </g>
        </svg>

  );
};

export default LikeButton;

Here id= commentId, type="comment, liked= true/ false based on the comment is liked or not
I have no idea how to create this functionality on backend and frontend
Please help.

My comment controller for votes-

exports.voteComment = (req, res) => {
  const { commentId } = req.params;
  if (!ObjectId.isValid(commentId)) {
    return res.status(400).send({
      error: "Comment ID not valid",
    });
  }
  CommentVote.findOneAndUpdate(
    {
      comment: commentId,
      // abhi loggedin user khud ke comment pe vote kar pa rha hai
      "comment.postedBy": { $ne: req.auth._id },
      "votes.postedBy": { $ne: req.auth._id },
    },
    { $push: { votes: { postedBy: req.auth._id } } },
    { new: true }
  ).exec((err, result) => {
    if (err) {
      console.log("abc", err);
      return res.status(400).json({
        error: "Could not vote on that comment",
      });
    }
    console.log(result);
    if (result === null) {
      const dislikeComment = CommentVote.findOneAndUpdate(
        {
          comment: commentId,
          postedBy: { $ne: req.auth._id },

        },
        {
          $pull: { votes: { postedBy: req.auth._id } },
        },
        { new: true }
      ).exec();

      if (dislikeComment) {
        console.log("double tap");
        return res.send({ success: false });
      }

    }
    res.send({ success: true });
  });
};

my single comment frontend-

 {isAuth() && !editing && (

                  {isAuth() && !(isAuth()._id === comment.postedBy._id) && (
                    <LikeButton
                      id={comment._id}
                      type="comment"
                      liked={(value) => {}}
                    />
                  )}

**my getComments controller below -**

exports.getComments = (req, res) => {
  const { featureId } = req.params;
  console.log(featureId);
  Comment.find({ feature: featureId })
    .populate("postedBy", "_id username")
    .sort({ createdAt: -1 })
    .exec((err, comments) => {
      if (err) {
        // console.log(err);
        return res.status(400).send({
          error: errorHandler(err),
        });
      }
      return res.status(200).json(comments);
    });
}

also is their any other way to do this?


问:
get the input text in react search select package
I am using react select search as a part of the selection input in one of my forms.I need to obtain the on change text from the search provided is there any way to achieve this.

my components with their props are:

```<code><SelectSearch options={selectSearchOptionsDepartment}
                  search={true}
                  name='department'
                  placeholder='Department'
                  value={updatedRoleDep?updatedRoleDep:deptValues}
                  onChange={(e,option)=>{onChangeSelectSearchDepartment(e)
                    HandelChange(option)
                  }}
                  emptyMessage={preCompile.newDepartmentAdd}
              />
</code>```

Body:
I am using react select search as a part of the selection input in one of my forms.I need to obtain the on change text from the search provided is there any way to achieve this.

my components with their props are:

<SelectSearch options={selectSearchOptionsDepartment}
                  search={true}
                  name='department'
                  placeholder='Department'
                  value={updatedRoleDep?updatedRoleDep:deptValues}
                  onChange={(e,option)=>{onChangeSelectSearchDepartment(e)
                    HandelChange(option)
                  }}
                  emptyMessage={preCompile.newDepartmentAdd}
              />


问:
How can I use GitHub Actions to update a .csv file within a repo?
I am trying to build an app that involves updating a dataset every X days. I know that you can schedule automation in GitHub Actions with YAML, but I don't know how to write the code so that the files I download (using Selenium and API calls via Python) will go straight to GitHub, rather than my personal computer. I have no experience with either YAML or GitHub Actions, so I was hoping to get some guidance on where to start.

Here is an example of what I'm doing in Selenium, I just want the final file to go straight to a repo instead of my downloads folder.

```<code>today = date.today()
d1 = today.strftime("%d/%m/%Y")

driver.get("https://acleddata.com/data-export-tool/")
driver.find_element(By.NAME, "key").send_keys("[api key]")
driver.find_element(By.NAME, "email").send_keys(r"[my email]")
driver.find_element(By.NAME, "event_date_from").send_keys(r"01/11/2020")
driver.find_element(By.NAME, "event_date_to").send_keys(d1)
driver.find_element(By.NAME, "country_typing").send_keys("Ethiopia")
driver.find_element(By.XPATH, "//input[@data-check='mc-ethiopia']").click()
driver.find_element(By.XPATH, "//button[normalize-space()='Accept']").click()
driver.find_element(By.XPATH, "//input[@value='Export']").click()
</code>```

Body:
I am trying to build an app that involves updating a dataset every X days. I know that you can schedule automation in GitHub Actions with YAML, but I don't know how to write the code so that the files I download (using Selenium and API calls via Python) will go straight to GitHub, rather than my personal computer. I have no experience with either YAML or GitHub Actions, so I was hoping to get some guidance on where to start.

Here is an example of what I'm doing in Selenium, I just want the final file to go straight to a repo instead of my downloads folder.

today = date.today()
d1 = today.strftime("%d/%m/%Y")

driver.get("https://acleddata.com/data-export-tool/")
driver.find_element(By.NAME, "key").send_keys("[api key]")
driver.find_element(By.NAME, "email").send_keys(r"[my email]")
driver.find_element(By.NAME, "event_date_from").send_keys(r"01/11/2020")
driver.find_element(By.NAME, "event_date_to").send_keys(d1)
driver.find_element(By.NAME, "country_typing").send_keys("Ethiopia")
driver.find_element(By.XPATH, "//input[@data-check='mc-ethiopia']").click()
driver.find_element(By.XPATH, "//button[normalize-space()='Accept']").click()
driver.find_element(By.XPATH, "//input[@value='Export']").click()


问:
Mongo DB TypeInitializationException
I am trying to fetch data from inside mongodb.

I am getting the following exception:
System.TypeInitializationException: 'The type initializer for 'MongoDB.Bson.Serialization.BsonClassMap' threw an exception.'

ArgumentNullException: Value cannot be null. Arg_ParamName_Name

```<code>public IQueryable<IssueDto> FetchCollection(string databaseName, string collectionName)
{
    var dbClient =
        new MongoClient("mongo connection string here");

    var database = dbClient.GetDatabase(databaseName);
    var collection = database.GetCollection<IssueDto>(collectionName);

    return collection.AsQueryable();
}
</code>```

Json inside mongo:

```<code>{
"_id":{"$oid":"63920bcf14ab25ab93444804"},
"name":"This is a task",
"completed": true,
"issueId":1234
}
</code>```

The model class is as follows:
public class IssueDto

```<code>{
    [BsonElement("_id")]
    public ObjectId Id { get; set; }
    [BsonElement("issueId")]
    public int IssueId { get; set; }
    [BsonElement("name")]
    public string Name { get; set; }
    [BsonElement("completed")]
    public bool Completed { get; set; }
}
</code>```

Can anyone spot what is going wrong?

Other info: .NET6, MongoDB.Driver 2.8.0

Title: Mongo DB TypeInitializationException

Body:
I am trying to fetch data from inside mongodb.

I am getting the following exception:
System.TypeInitializationException: 'The type initializer for 'MongoDB.Bson.Serialization.BsonClassMap' threw an exception.'

ArgumentNullException: Value cannot be null. Arg_ParamName_Name

public IQueryable<IssueDto> FetchCollection(string databaseName, string collectionName)
{
    var dbClient =
        new MongoClient("mongo connection string here");

    var database = dbClient.GetDatabase(databaseName);
    var collection = database.GetCollection<IssueDto>(collectionName);

    return collection.AsQueryable();
}

Json inside mongo:

{
"_id":{"$oid":"63920bcf14ab25ab93444804"},
"name":"This is a task",
"completed": true,
"issueId":1234
}

The model class is as follows:
public class IssueDto

{
    [BsonElement("_id")]
    public ObjectId Id { get; set; }
    [BsonElement("issueId")]
    public int IssueId { get; set; }
    [BsonElement("name")]
    public string Name { get; set; }
    [BsonElement("completed")]
    public bool Completed { get; set; }
}

Can anyone spot what is going wrong?

Other info: .NET6, MongoDB.Driver 2.8.0


问:
sending Action Mailer emails with Sidekiq and without Active Job
i'm interested in running a rails app with sidekiq, and without active job. i find that if active job is there, people get confused if they should use active job apis or sidekiqs, and i want to use sidekiq's apis exclusively for performance reasons.

does current versions of sidekiq (i.e. version 7) support active mailer without active job's deliver_later? i think the historical way to do this was through "delayed extensions" but i see now this has been removed in sidekiq 7:

Delayed extensions provide a very easy and simple way to make method calls asynchronous. By default, all class methods and ActionMailer deliveries can be performed asynchronously.
They were disabled in Sidekiq 5 and removed in Sidekiq 7.

https://github.com/mperham/sidekiq/wiki/Delayed-Extensions

so given that, is there a recommended way to use action mailer with sidekiq and without active job these days?


问:
Easiest way to parallelize Camel routes
Currently I have a camel route that makes a few API rest calls and puts the results in a database, and does this serially:

Enter route

Setup task

Call/insert 1

Call/insert 2

Call/insert 3

Finalizing task

I would like to make these calls happen in parallel.

Enter route

Setup task

Make external calls in parallel manner:

Call/insert 1

Call/insert 2

Call/insert 3

Finalizing task

Each step in the serial mode is currently its own camel route, so things are already fairly modular. My two main questions are:

best way to call the call/insert routes in a parallel manner?

I have seen examples that split up the body and send each part to a different thread, but that's not what I need here.

I have also seen setting up using .multicast().parallelProcessing().to("direct:id1", "direct:id2");; Is it as easy as that? Can I just specify the separates routes to parallelize? Is this best practice? Anything to know or note about this?

How to wait for all the threads to finish? Error handling?

Currently each external call route goes to the next. Where should they go when they are made parallel? Can I just not specify the next step?

How to handle potential errors that occur in one or more of the threads? How can I make sure these are handled? Currently each step error-checks and goes to a generic error-handler

Title: Easiest way to parallelize Camel routes


问:
How to send a lot of data to a remote MySQL database
I found here (Send data from android to server via JSON) that I can send local Android database data to a remote MySQL database.
So I tried to do that and when I send just a row it works good, but when I try to sync the 2 databases sending all rows (~200) from a local table to the remote one,  just few rows are stored.

Perhaps the Apache server can't receive too much requests, and however I need to send a row at time, wait for the remote server answer, send the following row, wait for the server answer and so on.

How I can be sure to send a request at a time and wait the server answer before sending the following request?

ContentLicense: CC BY-SA 3.0


问:
Is Smart Recovery data available via ecobee API?
Is the following data available via the ecobee API?

Whether Smart Recovery is enabled/disabled on the thermostat

When Smart Recovery is active just before a schedule transition

I'm not seeing it in the Settings, Runtime or ExtendedRuntime objects.


问:
is there a way to check if user is currently "signed in with apple" in flutter app?
I have a flutter app with 2 authentication methods:

Based on device id (associated with account during account creation)

Sign in with apple
I need to know whether user is currently signed in with apple on each app launch.

Why I need that:
When device id is not found in my back end, I send user to registration page, where user has 2 options to register:

regular registration

sign in with apple

The problem is that device id can be changed on ios upgrade, app reinstall etc. Therefore if user signed in with apple first time, but then his device id has changed, I want to remove sign in with apple button. Because for that particular case user is supposed to go through regular sign in method where he needs to enter phone number he entered during the registration and if he confirms SMS code, then account is linked to new device id and access is restored. I don't want them to click sign in with apple again, because during regular sign ins I only get tokens from apple and can't get apple id email anymore.

Hopefully that makes sense.

Thank you


问:
Creating a webpage to load audio file and then display spectrogram of the audio file using web audio
I am creating a webpage to load an audio file from my local drive and then display a spectrogram of the audio file. I am trying to do this using web audio API. However, my code does not run and I always get the following error message.

Any suggestion or solution that you could give is highly appreciated.

Thank you!

```<code>   <!DOCTYPE html>
<html>
<head>
  <title>Spectrogram</title>
</head>
<body>
  <h1>Spectrogram</h1>

  <form>
    <label for="file-input">Select an audio file:</label>
    <input type="file" id="file-input" accept="audio/*" />
    <input type="submit" value="Submit" />
  </form>

  <canvas id="spectrogram" width="500" height="200"></canvas>

  <script>
    const fileInput = document.getElementById('file-input');
    const spectrogramCanvas = document.getElementById('spectrogram');

    // Listen for file selection
    fileInput.addEventListener('change', function() {
      // Get the selected file
      const file = fileInput.files[0];

      // Create a FileReader object
      const reader = new FileReader();

      // Listen for the file to be loaded
      reader.addEventListener('load', function() {
        // Create an audio context
        const context = new AudioContext();

        // Create an audio buffer from the audio file
        context.decodeAudioData(reader.result, function(buffer) {
          // Create a spectrogram
          const spectrogram = createSpectrogram(buffer, context);

          // Draw the spectrogram on the canvas
          drawSpectrogram(spectrogram, spectrogramCanvas);
        });
      });

      // Read the file as an array buffer
      reader.readAsArrayBuffer(file);
    });

    // Create a spectrogram from an audio buffer
    function createSpectrogram(buffer, context) {
      // Create an offline audio context
      const offlineContext = new OfflineAudioContext(buffer.numberOfChannels, buffer.length, buffer.sampleRate);

      // Create a source node from the audio buffer
      const source = offlineContext.createBufferSource();
      source.buffer = buffer;

      // Create a analyser node
      const analyser = offlineContext.createAnalyser();

      // Connect the source and analyser nodes
      source.connect(analyser);
      analyser.connect(offlineContext.destination);

      // Start the source node
      source.start(0);

      // Render the audio
      return offlineContext.startRendering();
    }

    // Draw a spectrogram on a canvas
    function drawSpectrogram(spectrogram, canvas) {
      // Get the canvas context
      const context = canvas.getContext('2d');

      // Get the image data for the spectrogram
      const imageData = context.createImageData(spectrogram.width, spectrogram.height);

      // Draw the spectrogram on the image data
      spectrogram.forEach((value, i) => {
        const j = i * 4;
        imageData.data[j] = value;
        imageData.data[j + 1] = value;
        imageData.data[j + 2] = value;
        imageData.data[j + 3] = 255;
      });

      // Draw the image data on the canvas
      context.putImageData(imageData, 0, 0);
}
</script>

</body>
</html>
</code>```

Body:
I am creating a webpage to load an audio file from my local drive and then display a spectrogram of the audio file. I am trying to do this using web audio API. However, my code does not run and I always get the following error message.

Any suggestion or solution that you could give is highly appreciated.

Thank you!

   <!DOCTYPE html>

  <title>Spectrogram</title>

Spectrogram

  <form>
    Select an audio file:
    <input type="file" id="file-input" accept="audio/*" />
    <input type="submit" value="Submit" />
  </form>

  <canvas id="spectrogram" width="500" height="200"></canvas>


问:
How to pass a Rust function to onclick inside html button tag?
I want to pass a rust function for the onClick in my button tag. I know how to pass a variable but a function not.

Below is my rust file where I call the routes:

```<code>use rocket_dyn_templates::{context, Template};
use serde::Serialize;

#[derive(Serialize)]
struct Context {
    prompt: String,
}

#[macro_use]
extern crate rocket;

fn submit(prompt: String) {
    println!("value is {prompt}");
}

#[get("/")]
fn index() -> Template {
    let prompt: String = "".to_string();
    Template::render("index", context! { field: prompt })
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![index])
        .attach(Template::fairing())
}
</code>```

My html file:

```<code><head>
  <style type="text/css">
    <title>Generator Image</title>body {
      background: #1a6875;
      font-family: Arial, Helvetica, sans-serif;
    }

    .container-prompt {
      height: 10em;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .submit-prompt {
      margin: 0;
    }
  </style>
</head>

<body>
  <div class="container-submit">
    <div class="submit-prompt">
      <input method="text" name="prompt" id="prompt"/>
      <button onClick="">Submit</button>
    </div>
  </div>
</body>
</code>```

At the end, I would like to use the variable prompt used in the input tag on the rust function as a parameter when the button is clicked.

Thanks.

Body:
I want to pass a rust function for the onClick in my button tag. I know how to pass a variable but a function not.

Below is my rust file where I call the routes:

use rocket_dyn_templates::{context, Template};
use serde::Serialize;

#[derive(Serialize)]
struct Context {
    prompt: String,
}

#[macro_use]
extern crate rocket;

fn submit(prompt: String) {
    println!("value is {prompt}");
}

#[get("/")]
fn index() -> Template {
    let prompt: String = "".to_string();
    Template::render("index", context! { field: prompt })
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![index])
        .attach(Template::fairing())
}

My html file:

      <input method="text" name="prompt" id="prompt"/>
      <button onClick="">Submit</button>

At the end, I would like to use the variable prompt used in the input tag on the rust function as a parameter when the button is clicked.

Thanks.


问:
How to calculate sum from user input inside while loop
I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..

My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.

Here is my code:

```<code>import java.util.Scanner;
import java.util.ArrayList;

public class DailyExpensesMain {

    public static void main(String[] args) {

        ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
        Scanner sc = new Scanner(System.in);
        boolean isRunning = true;

        System.out.println("Enter the date for which you want to record the expenses : ");
        String date = sc.nextLine();

        while(isRunning) {
            System.out.println("Enter category: (quit to exit)");
            String category = sc.nextLine();
            if(category.equalsIgnoreCase("quit")) {
                 break;
            }

            System.out.println("Enter price: ");
            double price = sc.nextDouble();

            sc.nextLine();

            System.out.println("Enter details: ");
            String detail = sc.nextLine();

            DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
            expenses.add(newExpense);
        }

        sc.close();
        for(DailyExpenses u: newExpense) {
            System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
                " Detail: " + u.getExpenseDetail());
        }
    }
}
</code>```

I still clueless on the situation

Body:
I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..

My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.

Here is my code:

import java.util.Scanner;
import java.util.ArrayList;

public class DailyExpensesMain {

    public static void main(String[] args) {

        ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
        Scanner sc = new Scanner(System.in);
        boolean isRunning = true;

        System.out.println("Enter the date for which you want to record the expenses : ");
        String date = sc.nextLine();

        while(isRunning) {
            System.out.println("Enter category: (quit to exit)");
            String category = sc.nextLine();
            if(category.equalsIgnoreCase("quit")) {
                 break;
            }

            System.out.println("Enter price: ");
            double price = sc.nextDouble();

            sc.nextLine();

            System.out.println("Enter details: ");
            String detail = sc.nextLine();

            DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
            expenses.add(newExpense);
        }

        sc.close();
        for(DailyExpenses u: newExpense) {
            System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
                " Detail: " + u.getExpenseDetail());
        }
    }
}

I still clueless on the situation


问:
Calling Matlab function from .net(C#) by using MLApp.Feval()
I tried to use Matlab function from my .net project

```<code>function [HR] = getHR(signal)
    Fs = 200;
    index = pan_tompkin(signal,Fs);
    index = index(2:end-1);

    idx_dur = (index(end) - index(1))/Fs;
    idx_cnt = length(index)-1;
    idx_int = idx_dur/idx_cnt;
    HR = round(60/idx_int);

end
</code>```

This is my Matlab code

```<code>MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(@"cd C:\Users\User\Desktop");
object result = null;
matlab.Feval("getHR", 1, out result,input_Data);
object[] res = result as object[];
tmp_HR = Convert.ToInt32(res[0]);
</code>```

And this is part of my .net code where calling Matlab function
input_Data is 2000x1 double array

When I run this program, error is occur that "Undefined function 'getHR' for input arguments of type 'double'." on Matlab.Feval line

Someone advised me to 'varargin' to solve this problem, but I can not find the answer(I don't think it is necessary)

How can I revise my code to fix this problem?

I can not use the way to use Matlab compiler SDK or Matlab coder
maybe have to use only MLApp to solve this problem

Body:
I tried to use Matlab function from my .net project

function [HR] = getHR(signal)
    Fs = 200;
    index = pan_tompkin(signal,Fs);
    index = index(2:end-1);

    idx_dur = (index(end) - index(1))/Fs;
    idx_cnt = length(index)-1;
    idx_int = idx_dur/idx_cnt;
    HR = round(60/idx_int);

end

This is my Matlab code

MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(@"cd C:\Users\User\Desktop");
object result = null;
matlab.Feval("getHR", 1, out result,input_Data);
object[] res = result as object[];
tmp_HR = Convert.ToInt32(res[0]);

And this is part of my .net code where calling Matlab function
input_Data is 2000x1 double array

When I run this program, error is occur that "Undefined function 'getHR' for input arguments of type 'double'." on Matlab.Feval line

Someone advised me to 'varargin' to solve this problem, but I can not find the answer(I don't think it is necessary)

How can I revise my code to fix this problem?

I can not use the way to use Matlab compiler SDK or Matlab coder
maybe have to use only MLApp to solve this problem


问:
Converting an image stream from a socket to a video object in MT4J in real time
I've been working on this problem for a while now.  I'm working on a project where I recieve a stream of images which have been processed by OpenCV on a socket, and I need to display these feeds in MT4J.  We are transferring the images inside of a Google Protocol Buffer message.  In my current (and naive) approach, I grab images off of the socket and simply set them as a the texture in an overloaded draw method from MTRectangle.  While this works, if I attempt to display more than 3 feeds at a time, the frame rate drops to an unacceptable rate (<1 fps), and it takes up ~70-80% of my CPU.

A co-worker managed to use GStreamer/Xuggler to display about 20 videos in MT4J, but was using static files instead of a real-time stream.  Because of this, I attempted to find a tool in MT4J or Xuggler which would allow me to convert the images to a video stream on the fly, but everything seems to simply be converting a collection of images on the disk to a stream, or vice-versa, but not in real time.

So at this point I see two possible solutions.  First, is there a more efficient way to set/draw textures in MT4J?  Secondly, is there some tool that exists/some library in GStreamer or Xuggler which would do the image to video conversion in real time?

MT4J website for people who don't know what it is:
http://www.mt4j.org

Thanks in advance, and let me know if there is any information which I left out.