问:
rundeck configuration email notifications job in docker
I'd like to configure an email notification for a job done in rundeck with docker.

I've this docker-compose.yaml and but it doesn't work.

```<code>version: '3'

services:
  rundeck:
    image: ${RUNDECK_IMAGE:-rundeck/rundeck:SNAPSHOT}
    links:
      - postgres
    environment:
      RUNDECK_DATABASE_DRIVER: org.postgresql.Driver
      RUNDECK_DATABASE_USERNAME: rundeck
      RUNDECK_DATABASE_PASSWORD: rundeck
      RUNDECK_DATABASE_URL: jdbc:postgresql://postgres/rundeck?autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
      RUNDECK_GRAILS_MAIL_HOST: smtp.gmail.com
      RUNDECK_GRAILS_MAIL_USERNAME: email@gmail.com
      RUNDECK_GRAILS_MAIL_PORT: 587
      RUNDECK_GRAILS_MAIL_PASSWORD: qwqw
    volumes:
      - ${RUNDECK_LICENSE_FILE:-/dev/null}:/home/rundeck/etc/rundeckpro-license.key
    ports:
      - 4440:4440

  postgres:
    image: postgres
    expose:
      - 5432
    environment:
      - POSTGRES_DB=rundeck
      - POSTGRES_USER=rundeck
      - POSTGRES_PASSWORD=rundeck
    volumes:
      - dbdata:/var/lib/postgresql/data

volumes:
  dbdata:
</code>```

答:
Gmail configuration needs the extended parameters, in the past, an extra file named rundeck-config.groovy was needed with these extended params in the mail config (props section):

```<code>grails {
  mail {
    host = "smtp.gmail.com"
    username = "username@gmail.com"
    port = 587
    password = "example"
    props = ["mail.smtp.starttls.enable":"true","mail.smtp.auth":"true","mail.smtp.socketFactory.port":"587","mail.smtp.socketFactory.fallback":"false"]
  }
}
grails.mail.default.from = "username@gmail.com"
</code>```

Now, these params are available in the email docker configuration using an env var, take a look at the RUNDECK_MAIL_PROPS docker env var:

RUNDECK_MAIL_PROPS=["mail.smtp.starttls.enable":"true","mail.smtp.auth":"true","mail.smtp.socketFactory.port":"587","mail.smtp.socketFactory.fallback":"false"

Both ways (groovy file and env var) work well.

Body:
I'd like to configure an email notification for a job done in rundeck with docker.

I've this docker-compose.yaml and but it doesn't work.

version: '3'

services:
  rundeck:
    image: ${RUNDECK_IMAGE:-rundeck/rundeck:SNAPSHOT}
    links:
      - postgres
    environment:
      RUNDECK_DATABASE_DRIVER: org.postgresql.Driver
      RUNDECK_DATABASE_USERNAME: rundeck
      RUNDECK_DATABASE_PASSWORD: rundeck
      RUNDECK_DATABASE_URL: jdbc:postgresql://postgres/rundeck?autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
      RUNDECK_GRAILS_MAIL_HOST: smtp.gmail.com
      RUNDECK_GRAILS_MAIL_USERNAME: email@gmail.com
      RUNDECK_GRAILS_MAIL_PORT: 587
      RUNDECK_GRAILS_MAIL_PASSWORD: qwqw
    volumes:
      - ${RUNDECK_LICENSE_FILE:-/dev/null}:/home/rundeck/etc/rundeckpro-license.key
    ports:
      - 4440:4440

  postgres:
    image: postgres
    expose:
      - 5432
    environment:
      - POSTGRES_DB=rundeck
      - POSTGRES_USER=rundeck
      - POSTGRES_PASSWORD=rundeck
    volumes:
      - dbdata:/var/lib/postgresql/data

volumes:
  dbdata:

Body:
Gmail configuration needs the extended parameters, in the past, an extra file named rundeck-config.groovy was needed with these extended params in the mail config (props section):

grails {
  mail {
    host = "smtp.gmail.com"
    username = "username@gmail.com"
    port = 587
    password = "example"
    props = ["mail.smtp.starttls.enable":"true","mail.smtp.auth":"true","mail.smtp.socketFactory.port":"587","mail.smtp.socketFactory.fallback":"false"]
  }
}
grails.mail.default.from = "username@gmail.com"

Now, these params are available in the email docker configuration using an env var, take a look at the RUNDECK_MAIL_PROPS docker env var:

RUNDECK_MAIL_PROPS=["mail.smtp.starttls.enable":"true","mail.smtp.auth":"true","mail.smtp.socketFactory.port":"587","mail.smtp.socketFactory.fallback":"false"

Both ways (groovy file and env var) work well.


来源: stackexchange

问:
how to create ios testflight without MAC (visual studio 2019)
Is it possible to create an .ipa file in visual studio 2019 without MAC device.
I have tried this link but it doesn't generate the file since I am not connected to MAC.
My project is Xamarin Form IOS and Visual Studio 2019. I have apple developer account.</p>

答: Without Mac it is impossible. You can also use Mac on cloud service.</p>

ContentLicense: CC BY-SA 4.0


问:
how to update the existing record once the user clicks on something?
I'm using symfony 1.4 doctrine and I was having a problem on my project. How to update a existing record in symfony?

Here's a my scenario.  On my backend application of my project, the admin(who handles the backend application) can recieved info/record when the user send his/her reservation form to the backend(my project is conference room reservation system). the admin will notify him/her through email if his/her request is approved or not which I got all right =). The problem is I have no Idea since I'm new to symfony on how to change from the "pending request"(from the request approval) into approved if the admin clicks on the approved link or vice versa if disapprove button was clicked.

I also have code It can send mails( this code works except for updating the record, just in case you might change something on my code)
Can someone help me? Can you give me some tips? some php code or symfony code?

```<code>apps/backend/modules/reservation/actions/actions.class.php

<?php

require_once dirname(__FILE__).'/../lib/reservationGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/reservationGeneratorHelper.class.php';

class reservationActions extends autoReservationActions
{
     public function executeListApprove(sfWebRequest $request)
  {

    $reservation = $this->getRoute()->getObject();
    $reservation->approve(true);

    $mailer = $this->getMailer()->composeAndSend(
      'supervisor@teleserv.local',
      $reservation->getEmail(),
      'Request Approval',
      '
          Good Day. Hello This is Martin from the tech dept.
       We have received your request.You can now use the
       conference room due to your requested schedule. If
       you have questions of your approval or your request,
       Please contact me within 24 hrs. Thank you.

       Martin
       Junior Programmer
       '
      );

      $this->getUser()->setFlash('notice', 'Sent mail approval:');
      $this->redirect('reservation/index');

  }

     public function executeListDisapprove(sfWebRequest $request)
  {
    $reservation = $this->getRoute()->getObject();
    $reservation->Disapprove(true);

    $mailer = $this->getMailer()->composeAndSend(
      'supervisor@teleserv.local',
       $reservation->getEmail(),
      'Request Disapproval',
      '
          Good Day. Hello This is Martin from the tech dept.
       We have received your request.Unfortunately, We
       can\'t approve your request due:
        1.Conflicts with the schedule.
        2.Invalid request information.
       If you have questions of your disapproval or your
       request, Please contact me within 24 hrs. Thank you

       Martin
       Junior Programmer'
      );

      $this->getUser()->setFlash('notice', 'Sent mail disapproval:');
      $this->redirect('reservation/index');

  }
}
</code>```

答:
Martin!

You should to save object after changes.

```<code>$reservation->save();
</code>```

Tip:

Do not mix controller layer and view layer,

Use configurations (app_yml)

```<code>$reservation = $this->getRoute()->getObject();
$reservation->approve(true);
$reservation->save();

$mailer = $this->getMailer()->composeAndSend(
  sfConfig::get('app_email_sender'),
  $reservation->getEmail(),
  'Request Approval',
  $this->getPartial('email_approve_body')
);

$this->getUser()->setFlash('notice', 'Sent mail approval:');
$this->redirect('reservation/index');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using symfony 1.4 doctrine and I was having a problem on my project. How to update a existing record in symfony?

Here's a my scenario.  On my backend application of my project, the admin(who handles the backend application) can recieved info/record when the user send his/her reservation form to the backend(my project is conference room reservation system). the admin will notify him/her through email if his/her request is approved or not which I got all right =). The problem is I have no Idea since I'm new to symfony on how to change from the "pending request"(from the request approval) into approved if the admin clicks on the approved link or vice versa if disapprove button was clicked.

I also have code It can send mails( this code works except for updating the record, just in case you might change something on my code)
Can someone help me? Can you give me some tips? some php code or symfony code?

apps/backend/modules/reservation/actions/actions.class.php

<?php

require_once dirname(__FILE__).'/../lib/reservationGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/reservationGeneratorHelper.class.php';

class reservationActions extends autoReservationActions
{
     public function executeListApprove(sfWebRequest $request)
  {

    $reservation = $this->getRoute()->getObject();
    $reservation->approve(true);

    $mailer = $this->getMailer()->composeAndSend(
      'supervisor@teleserv.local',
      $reservation->getEmail(),
      'Request Approval',
      '
          Good Day. Hello This is Martin from the tech dept.
       We have received your request.You can now use the
       conference room due to your requested schedule. If
       you have questions of your approval or your request,
       Please contact me within 24 hrs. Thank you.

       Martin
       Junior Programmer
       '
      );

      $this->getUser()->setFlash('notice', 'Sent mail approval:');
      $this->redirect('reservation/index');

  }

     public function executeListDisapprove(sfWebRequest $request)
  {
    $reservation = $this->getRoute()->getObject();
    $reservation->Disapprove(true);

    $mailer = $this->getMailer()->composeAndSend(
      'supervisor@teleserv.local',
       $reservation->getEmail(),
      'Request Disapproval',
      '
          Good Day. Hello This is Martin from the tech dept.
       We have received your request.Unfortunately, We
       can\'t approve your request due:
        1.Conflicts with the schedule.
        2.Invalid request information.
       If you have questions of your disapproval or your
       request, Please contact me within 24 hrs. Thank you

       Martin
       Junior Programmer'
      );

      $this->getUser()->setFlash('notice', 'Sent mail disapproval:');
      $this->redirect('reservation/index');

  }
}

Body:
Martin!

You should to save object after changes.

$reservation->save();

Tip:

Do not mix controller layer and view layer,

Use configurations (app_yml)

$reservation = $this->getRoute()->getObject();
$reservation->approve(true);
$reservation->save();

$mailer = $this->getMailer()->composeAndSend(
  sfConfig::get('app_email_sender'),
  $reservation->getEmail(),
  'Request Approval',
  $this->getPartial('email_approve_body')
);

$this->getUser()->setFlash('notice', 'Sent mail approval:');
$this->redirect('reservation/index');


问:
Stripe wont intialize paymentsheet
I am trying to implement Stripe to my flutter app, but i am running in to this issue:

```<code>StripeException(error: LocalizedErrorMessage(code: FailureCode.Failed, localizedMessage: No payment sheet has been initialized yet, message: No payment sheet has been initialized yet, stripeErrorCode: null, declineCode: null, type: null))
</code>```

My current code is:

```<code>Future<void> makePayment() async {
    final response = await http.post(
      Uri.parse(
        api_string,
      ),
      headers: {"Content-Type": "application/json; charset=utf-8"},
      body: json.encode({"Amount": "250"}),
    );

    var data = json.decode(response.body);

    await Stripe.instance.initPaymentSheet(
      paymentSheetParameters: SetupPaymentSheetParameters(
        paymentIntentClientSecret: data['clientSecret'],
        merchantDisplayName: 'Flutter test app',
        applePay: true,
        googlePay: true,
        style: ThemeMode.dark,
        testEnv: true,
        merchantCountryCode: 'DK',
      ),
    );
    setState(() {});

    await displayPaymentSheet();
  }

  Future<void> displayPaymentSheet() async {
    try {
      await Stripe.instance.presentPaymentSheet();
    } catch (e) {
      print(e);
    }
  }
</code>```

I have checked the official flutter_stripe documentation, but the example with my API changed gives the same error, and my api return "clientSecret": Secret}

答: As stated in the comment, the fix was to add a merchantId to the Stripe initialization</p>

Title: Stripe wont intialize paymentsheet

Body:
I am trying to implement Stripe to my flutter app, but i am running in to this issue:

StripeException(error: LocalizedErrorMessage(code: FailureCode.Failed, localizedMessage: No payment sheet has been initialized yet, message: No payment sheet has been initialized yet, stripeErrorCode: null, declineCode: null, type: null))

My current code is:

Future<void> makePayment() async {
    final response = await http.post(
      Uri.parse(
        api_string,
      ),
      headers: {"Content-Type": "application/json; charset=utf-8"},
      body: json.encode({"Amount": "250"}),
    );

    var data = json.decode(response.body);

    await Stripe.instance.initPaymentSheet(
      paymentSheetParameters: SetupPaymentSheetParameters(
        paymentIntentClientSecret: data['clientSecret'],
        merchantDisplayName: 'Flutter test app',
        applePay: true,
        googlePay: true,
        style: ThemeMode.dark,
        testEnv: true,
        merchantCountryCode: 'DK',
      ),
    );
    setState(() {});

    await displayPaymentSheet();
  }

  Future<void> displayPaymentSheet() async {
    try {
      await Stripe.instance.presentPaymentSheet();
    } catch (e) {
      print(e);
    }
  }

I have checked the official flutter_stripe documentation, but the example with my API changed gives the same error, and my api return "clientSecret": Secret}


问:
how to say this field has email annotation from outside
```<code>@NotNull(message = "emailAddress is mandatory")
@NotEmpty(message = "emailAddress cannot be empty")
@Email(message = "Invalid Email")
private String emailAddress;
</code>```

I just want to know from outside , emailAdress has Email annotation.
Is there any way that we can say it is an email annotaion?

答:
You can use reflection for this. The following test passes:</p>
```<code> public class MyTest {

    @Test
    public void test() throws NoSuchFieldException {
        HasEmailAddressValidator hasEmailAddressValidator = new HasEmailAddressValidator();
        boolean result = hasEmailAddressValidator.hasEmailAddress(MyClass.class);

        assertTrue(result);
    }

    @NoArgsConstructor
    static
    class HasEmailAddressValidator {
        public boolean hasEmailAddress(Class<?> clazz) throws NoSuchFieldException {
            return clazz.getDeclaredField("email").isAnnotationPresent(Email.class);
        }
    }

    @Data
    static
    class MyClass {
        @Email(message = "this is an email address")
        private String email;
    }
}
</code>```

Body:
@NotNull(message = "emailAddress is mandatory")
@NotEmpty(message = "emailAddress cannot be empty")
@Email(message = "Invalid Email")
private String emailAddress;

I just want to know from outside , emailAdress has Email annotation.
Is there any way that we can say it is an email annotaion?

Body:
You can use reflection for this. The following test passes:

 public class MyTest {

    @Test
    public void test() throws NoSuchFieldException {
        HasEmailAddressValidator hasEmailAddressValidator = new HasEmailAddressValidator();
        boolean result = hasEmailAddressValidator.hasEmailAddress(MyClass.class);

        assertTrue(result);
    }

    @NoArgsConstructor
    static
    class HasEmailAddressValidator {
        public boolean hasEmailAddress(Class<?> clazz) throws NoSuchFieldException {
            return clazz.getDeclaredField("email").isAnnotationPresent(Email.class);
        }
    }

    @Data
    static
    class MyClass {
        @Email(message = "this is an email address")
        private String email;
    }
}


问:
The sum of the columns in the table (input)
I need to make a table with dynamic column sums on a website. Unfortunately, I'm not very good at jQuery. Please help.
[enter image description here][1]

My table in HTML
[1]: https://i.stack.imgur.com/yV2Fo.png

table, td {
  border: 1.25px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <td> NAME</td>
      <td> Name 1 </td>
      <td> Name 2 </td>
      <td> Name 3 </td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td><input type="number"</td>
      <td><input type="number"</td>
      <td><input type="number"</td>
    </tr>
    <tr>
      <td>B</td>
      <td><input type="number"</td>
      <td><input type="number"</td>
      <td><input type="number"</td>
    </tr>
    <tr>
      <td>C</td>
      <td><input type="number"</td>
      <td><input type="number"</td>
      <td><input type="number"</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Total</td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tfoot>
</table></code>```

答:
I'm not sure how your table is set up. There are different ways you could do it, but I think this could be a solution:

I think something like this is what you are looking for?

Column
Total

A
150

B
100

C
50

Total
200

This is how you can accomplish this:

$(document).ready(() => {
  let array = []; // Create an empty array
  let sum = 0; // Set sum to 0 - This is only to set the data type to a number

  /*
   Use Jquery's :nth-child() selector to get target the 2nd cell in the table body
    -- You can use :nth-child(3) for the 3rd cell etc...

    Then use the $each method to perform a function.
    The function will convert this cell's text (Using parseFloat() method) to a number and add (push()) it to our array
  */
  $("table tbody td:nth-child(2)").each(function() {
    array.push(parseFloat($(this).html()));
  });

 // Here we will loop over the array and add each value to the sum variable.
  for (let i = 0; i < array.length; i++) {
    sum += array[i];
  }

// Then append the last child (last table cell) in the table's footer with this sum value || Or if you gave the this cell an id, you can use that instead.
  $('table tfoot td:last-child').html(sum);
});

/* This can be used over many columns by selecting the different nth-child()'s
*/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, td {
  border: 1.25px solid black;
}
td {
  padding: 3px;
  text-align: center;
}

td:last-child {
  font-weight: bolder;
}</code>```

       Column
       Total

      A
      150

      B
      100

      C
      50

      Total

```

Please read the comments in the snippet, this will explain the process.

Body:
I need to make a table with dynamic column sums on a website. Unfortunately, I'm not very good at jQuery. Please help.
[enter image description here][1]

My table in HTML
[1]: https://i.stack.imgur.com/yV2Fo.png

table, td {
  border: 1.25px solid black;
}

       NAME
       Name 1
       Name 2
       Name 3

      A
      <input type="number"
      <input type="number"
      <input type="number"

      B
      <input type="number"
      <input type="number"
      <input type="number"

      C
      <input type="number"
      <input type="number"
      <input type="number"

      Total

Body:
I'm not sure how your table is set up. There are different ways you could do it, but I think this could be a solution:

I think something like this is what you are looking for?

Column
Total

A
150

B
100

C
50

Total
200

This is how you can accomplish this:

$(document).ready(() => {
  let array = []; // Create an empty array
  let sum = 0; // Set sum to 0 - This is only to set the data type to a number

  /*
   Use Jquery's :nth-child() selector to get target the 2nd cell in the table body
    -- You can use :nth-child(3) for the 3rd cell etc...

    Then use the $each method to perform a function.
    The function will convert this cell's text (Using parseFloat() method) to a number and add (push()) it to our array
  */
  $("table tbody td:nth-child(2)").each(function() {
    array.push(parseFloat($(this).html()));
  });

 // Here we will loop over the array and add each value to the sum variable.
  for (let i = 0; i < array.length; i++) {
    sum += array[i];
  }

// Then append the last child (last table cell) in the table's footer with this sum value || Or if you gave the this cell an id, you can use that instead.
  $('table tfoot td:last-child').html(sum);
});

/* This can be used over many columns by selecting the different nth-child()'s
*/

table, td {
  border: 1.25px solid black;
}
td {
  padding: 3px;
  text-align: center;
}

td:last-child {
  font-weight: bolder;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <!-- Table Heading -->
  <thead>
    <tr>
      <td> Column </td>
      <td> Total </td>
    </tr>
  </thead>
  <!-- Table Body -->
  <tbody>
    <tr>
      <td>A</td>
      <td>150</td>
    </tr>
    <tr>
      <td>B</td>
      <td>100</td>
    </tr>
    <tr>
      <td>C</td>
      <td>50</td>
    </tr>
  </tbody>
  <!-- Table Footer -->
  <tfoot>
    <tr>
      <td>Total </td>

      <!-- Add an id to this cell for the total or use my method in the js code-->
      <td id="tableTotal"></td>
    </tr>
  </tfoot>
</table>

Please read the comments in the snippet, this will explain the process.


答:
Create your custome Annotation.

```<code>`import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = EmailValidator.class)
@Documented
public @interface ValidEmail {

    String message() default "Invalid Email";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
</code>```

// Email Validator

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static final Pattern PATTERN = Pattern.compile(EMAIL_PATTERN);

    @Override
    public boolean isValid(final String username, final ConstraintValidatorContext context) {
        return (validateEmail(username));
    }

    private boolean validateEmail(final String email) {
        Matcher matcher = PATTERN.matcher(email);
        return matcher.matches();
    }
}
</code>```

// Now in your DTO and Model

```<code>    @ValidEmail
    @NotNull
    @Size(min = 1, message = "Invalid Email")
    private String email;
</code>```

Title: how to say this field has email annotation from outside

Body:
Create your custome Annotation.

`import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = EmailValidator.class)
@Documented
public @interface ValidEmail {

    String message() default "Invalid Email";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

// Email Validator

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static final Pattern PATTERN = Pattern.compile(EMAIL_PATTERN);

    @Override
    public boolean isValid(final String username, final ConstraintValidatorContext context) {
        return (validateEmail(username));
    }

    private boolean validateEmail(final String email) {
        Matcher matcher = PATTERN.matcher(email);
        return matcher.matches();
    }
}

// Now in your DTO and Model

    @ValidEmail
    @NotNull
    @Size(min = 1, message = "Invalid Email")
    private String email;


问:
WebApi .net core 3.1 - How to customize validation message for null posting?
I have a class which is a parameter of a method in controller which has a required property (mark as [Required]).

When I pass a null value to that property I get a message saying:

```<code> "errors": {
    "testNumber": [
        "Error converting value {null} to type 'System.Int32'. Path 'testNumber', line 21, position 15."
    ]
}
</code>```

Similarly, when I pass a null value to that property I get a message saying:

```<code>"errors": {
    "testNumber": [
        "JSON integer 999999999999999999999999999 is too large or small for an Int32. Path 'testNumber', line 21, position 38."
    ]
}
</code>```

I want to customize the friendly messages saying:

```<code>"errors": {
    "testNumber": [
        "null is not a valid value for TestNumber."
]
</code>```

or

```<code>"errors": {
    "testNumber": [
        "999999999999999999999999999 is not a valid value for TestNumber."
    ]
}
</code>```

My TestClass is very simple:

```<code>public class TestClass
{
     [Required]
     public int TestNumber{ get; set; }
}
</code>```

I have a look at some posts they suggest to use:

```<code>[Required(ErrorMessage="<your value> is not a valid value for TestNumber.")]
public int TestNumber{ get; set; }
</code>```

But by doing this way, I can't get the original value sent from client.
So is this possible to customize the messages like above?

Thank you.

答:
So it's a bit messy but you can use CustomAttributes for this. You're basically rewriting logic, but not the end of the world:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0#custom-attributes

This will be able to perform what you want to do. If you don't like the sound of that, you'll probably want to look at writing middleware or filters in .NET Core:

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0

Someone more learned than me may be able to tell you how to put this together in a nice way (as I don't know), but you'd essentially be replacing the inbuilt .NET Core validation logic with your own.

Body:
I have a class which is a parameter of a method in controller which has a required property (mark as [Required]).

When I pass a null value to that property I get a message saying:

 "errors": {
    "testNumber": [
        "Error converting value {null} to type 'System.Int32'. Path 'testNumber', line 21, position 15."
    ]
}

Similarly, when I pass a null value to that property I get a message saying:

"errors": {
    "testNumber": [
        "JSON integer 999999999999999999999999999 is too large or small for an Int32. Path 'testNumber', line 21, position 38."
    ]
}

I want to customize the friendly messages saying:

"errors": {
    "testNumber": [
        "null is not a valid value for TestNumber."
]

or

"errors": {
    "testNumber": [
        "999999999999999999999999999 is not a valid value for TestNumber."
    ]
}

My TestClass is very simple:

public class TestClass
{
     [Required]
     public int TestNumber{ get; set; }
}

I have a look at some posts they suggest to use:

[Required(ErrorMessage="<your value> is not a valid value for TestNumber.")]
public int TestNumber{ get; set; }

But by doing this way, I can't get the original value sent from client.
So is this possible to customize the messages like above?

Thank you.


问:
Specialising Range or overloading ".."
I have a little library where I can define integer types. These are intended for type-safe indexing into arrays and strings in the kind of algorithms I often write. For example, I can use it to define an offset type, Offset and an index type, Idx such that you can get an Offset by subtracting two Idx, you can get Idx by adding or subtracting Offset, but you cannot for example multiple or add Idx.

let (i,j): (Idx,Idx) = ...;
let offset: Offset = j - i; // Subtracting indices gives an offset
let k: Idx = j + offset; // Adding an offset to an index gives an index
// let _ = i + j; -- You can't add indices
```
<p>I managed (with some difficulty) to implement <code>std::iter::Step</code> so I can also iterate through a range of indices</p>
<pre class="lang-rust prettyprint-override"><code>for k in i .. j { /* ... */ }
</code>```

but now I've set my eyes on a higher goal: I also want to use ranges of these types to slice into sequences

let v: Vec<sometype> = vec![...];
let w: &[sometype] = &v[i..j]; // Slice with a range of Idx
```
<p>This should be a simple matter of implementing <code>std::ops::Index</code> and <code>std::ops::IndexMut</code>, except that the type system won't let me implement</p>
<pre class="lang-rust prettyprint-override"><code>impl<I,T> std::ops::Index<std::ops::Range<I>> for Vec<T>
where I: /* my types */
{ ... }
</code>```

for a wrapper type, or a generic

impl std::ops::Index<std::ops::Range<Wrapper>> for Vec<T>
where I: /* my types */
{ ... }
```
<p>where <code>Wrapper</code> is the type I actually use and <code>I</code> a trait that helps me write generic code.</p>
<p>The problem is that both <code>Index</code> and <code>Range</code> are defined outside of my crate, so this kind of specialisation is not allowed. Or is it?</p>
<p>Is there any way that I can implement a trait for a generic type outside my crate when its generic parameters are from within my crate?</p>
<p>Or, better still, is there any way to tap into the syntactic sugar of the <code>..</code> operator, so I can get a wrapped type? What I <em>really</em> want is to wrap <code>Range</code> to get the same behaviour and then some. I can do that by wrapping <code>Range</code> and implementing <code>Deref</code>, but if I go that route, I lose the syntactic sugar of the <code>..</code> operator.</p>
<p>It is not a big problem, but I can imagine some confusion when you could write</p>
<pre class="lang-rust prettyprint-override"><code>for k in i .. j { /* ... */ }
</code>```

like you can for the built-in types, but you have to use

let w: &[type] = &v[range(i,j)];
```

for slicing. It gets even more cumbersome if I want to allow slices such as i.., ..j to be wrapped. (The .. slice doesn't matter here, it won't get my types anyway). If I did that, I would need constructors for three types of ranges, or some ugly wrapping using Option, I think.

The .. syntactic sugar is really neat, but from what I have explored you just cannot use that much for ranges of your own types. You can define ranges and you can, with some hacking, iterate through them, but you can't index with them.

Tell me I'm wrong, or let me know if there are any tricks that gets the job done, or even half-done. Or, if this is indeed impossible, let me know so I can stop wasting time on it and write a wrapper class and give up on the .. operator.

Update I have put a simplified example in playgrounds

答:
I have a sort-of solution, involving a new Range in my own crate, and a lot of hacking. The full code is in playgrounds. It is a slow compile (lots of type inference, I guess), so you might have to download it to run it. Sorry about that.

There is a bunch of meta-programming to define new index types, but the gist of it is that I use a trait to specify different types and a wrapper to hold the underlying numbers.

// A dummy type to illustrate the types I want to work with
// Different TypeInfo will give me different and incompatible
// types that wrap integers, which is what I want.
trait TypeInfo {
    type WrappedType: num::PrimInt;
}

// A wrapper wraps the type from the TypeInfo trait;
// the TypeInfo trait specifies the type when I define what
// operations I will allow.
#[derive(Debug, Clone, Copy)]
struct Wrapper<T: TypeInfo>(T::WrappedType);
```
<p>Then I have another trait to specify if a given index is allowed to index in a given sequence type.</p>
<pre class="lang-rust prettyprint-override"><code>// Trait that determines which sequences an index can index
trait CanIndex<Seq: ?Sized> {}
</code>```

although I am not sure if this is the right solution for that...

Anyway, for most of Rust's types, I need to use usize for indexing, so I have another trait that specifies if I have such a bugger.

// For indexing... (You get too deeply nested genetics without it)
// Maybe I can get rid of it, but that is for another day...
pub trait IndexType {
    fn as_index(&self) -> usize;
}
impl<TI> IndexType for Wrapper<TI>
where
    TI: TypeInfo<WrappedType = usize>,
{
    fn as_index(&self) -> usize {
        self.0
    }
}
```
<p>While it doesn't make me happy to have to implement <code>Index</code> for every sequence type, at least every generic one, I don't think there is any way around that. For single indices, it is just this:</p>
<pre class="lang-rust prettyprint-override"><code>// Generic index implementation. (The real situation is a bit more
// complicated because I need to specify which types each index type
// is allowed to index, but this is the gist of it)

// Indexing a single element in a vector
impl<TI, T> std::ops::Index<Wrapper<TI>> for Vec<T>
where
    TI: TypeInfo,
    TI: CanIndex<Vec<T>>,
    Wrapper<TI>: IndexType,
{
    type Output = T;
    fn index(&self, i: Wrapper<TI>) -> &Self::Output {
        &self[i.as_index()]
    }
}

// Indexing a single element in a slice
impl<TI, T> std::ops::Index<Wrapper<TI>> for [T]
where
    TI: TypeInfo,
    TI: CanIndex<[T]>,
    Wrapper<TI>: IndexType,
{
    type Output = T;
    fn index(&self, i: Wrapper<TI>) -> &Self::Output {
        &self[i.as_index()]
    }
}
</code>```

For my new Range type, I went with an enum. It will be more convenient for the things I want to do with it.

// My own type of ranges, now that I cannot use the built-in type...
/// Wrapper of Range that we can work with within Rust's type system
#[derive(Clone, Copy)]
pub enum Range<Idx> {
    Closed(Idx, Idx), // start..end
    Left(Idx),        // start..
    Right(Idx),       // ..end
    Full,             // ..
}
```
<p>The type needs a constructor, which is complicated by Rust creating different types when you use the <code>..</code> operator, but you can do it like this:</p>
<pre class="lang-rust prettyprint-override"><code>pub trait GenRange<R, Idx> {
    fn range(r: R) -> Range<Idx>;
}
/*

 Now implement that trait for the different range types.
 Is there a better way?

 */

// Now I can build ranges with this function:
pub fn range<Idx, R: GenRange<R, Idx>>(r: R) -> Range<Idx> {
    R::range(r)
}
</code>```

With this, I can also implement indexing for ranges. I can use CanIndex<> to specify that I can index with ranges for any type that I can index individual items with.

impl<Idx, T> std::ops::Index<Range<Idx>> for Vec<T>
where
    Idx: IndexType,
    Idx: CanIndex<Vec<T>>,
{
    type Output = [T];
    fn index(&self, r: Range<Idx>) -> &Self::Output {
        match r {
            Range::Closed(start, end) => &self[start.as_index()..end.as_index()],
            Range::Left(start) => &self[start.as_index()..],
            Range::Right(end) => &self[..end.as_index()],
            Range::Full => &self[..],
        }
    }
}

impl<Idx, T> std::ops::Index<Range<Idx>> for [T]
where
    Idx: IndexType,
    Idx: CanIndex<[T]>,
{
    type Output = [T];
    fn index(&self, r: Range<Idx>) -> &Self::Output {
        match r {
            Range::Closed(start, end) => &self[start.as_index()..end.as_index()],
            Range::Left(start) => &self[start.as_index()..],
            Range::Right(end) => &self[..end.as_index()],
            Range::Full => &self[..],
        }
    }
}
```

It got rather complicated, so I need to clean it up as much as I can, but at least I am beginning to believe that it can be done. And once that is done, I need to figure out a good way to add the usual std::ops::Range interface to Range. But this will do for today.

Title: Specialising Range or overloading ".."

Body:
I have a little library where I can define integer types. These are intended for type-safe indexing into arrays and strings in the kind of algorithms I often write. For example, I can use it to define an offset type, Offset and an index type, Idx such that you can get an Offset by subtracting two Idx, you can get Idx by adding or subtracting Offset, but you cannot for example multiple or add Idx.

let (i,j): (Idx,Idx) = ...;
let offset: Offset = j - i; // Subtracting indices gives an offset
let k: Idx = j + offset; // Adding an offset to an index gives an index
// let _ = i + j; -- You can't add indices

I managed (with some difficulty) to implement std::iter::Step so I can also iterate through a range of indices

for k in i .. j { /* ... */ }

but now I've set my eyes on a higher goal: I also want to use ranges of these types to slice into sequences

let v: Vec<sometype> = vec![...];
let w: &[sometype] = &v[i..j]; // Slice with a range of Idx

This should be a simple matter of implementing std::ops::Index and std::ops::IndexMut, except that the type system won't let me implement

impl std::ops::Index<std::ops::Range> for Vec<T>
where I: /* my types */
{ ... }

for a wrapper type, or a generic

impl std::ops::Index<std::ops::Range<Wrapper>> for Vec<T>
where I: /* my types */
{ ... }

where Wrapper is the type I actually use and I a trait that helps me write generic code.

The problem is that both Index and Range are defined outside of my crate, so this kind of specialisation is not allowed. Or is it?

Is there any way that I can implement a trait for a generic type outside my crate when its generic parameters are from within my crate?

Or, better still, is there any way to tap into the syntactic sugar of the .. operator, so I can get a wrapped type? What I really want is to wrap Range to get the same behaviour and then some. I can do that by wrapping Range and implementing Deref, but if I go that route, I lose the syntactic sugar of the .. operator.

It is not a big problem, but I can imagine some confusion when you could write

for k in i .. j { /* ... */ }

like you can for the built-in types, but you have to use

let w: &[type] = &v[range(i,j)];

for slicing. It gets even more cumbersome if I want to allow slices such as i.., ..j to be wrapped. (The .. slice doesn't matter here, it won't get my types anyway). If I did that, I would need constructors for three types of ranges, or some ugly wrapping using Option, I think.

The .. syntactic sugar is really neat, but from what I have explored you just cannot use that much for ranges of your own types. You can define ranges and you can, with some hacking, iterate through them, but you can't index with them.

Tell me I'm wrong, or let me know if there are any tricks that gets the job done, or even half-done. Or, if this is indeed impossible, let me know so I can stop wasting time on it and write a wrapper class and give up on the .. operator.

Update I have put a simplified example in playgrounds

Body:
I have a sort-of solution, involving a new Range in my own crate, and a lot of hacking. The full code is in playgrounds. It is a slow compile (lots of type inference, I guess), so you might have to download it to run it. Sorry about that.

There is a bunch of meta-programming to define new index types, but the gist of it is that I use a trait to specify different types and a wrapper to hold the underlying numbers.

// A dummy type to illustrate the types I want to work with
// Different TypeInfo will give me different and incompatible
// types that wrap integers, which is what I want.
trait TypeInfo {
    type WrappedType: num::PrimInt;
}

// A wrapper wraps the type from the TypeInfo trait;
// the TypeInfo trait specifies the type when I define what
// operations I will allow.
#[derive(Debug, Clone, Copy)]
struct Wrapper<T: TypeInfo>(T::WrappedType);

Then I have another trait to specify if a given index is allowed to index in a given sequence type.

// Trait that determines which sequences an index can index
trait CanIndex<Seq: ?Sized> {}

although I am not sure if this is the right solution for that...

Anyway, for most of Rust's types, I need to use usize for indexing, so I have another trait that specifies if I have such a bugger.

// For indexing... (You get too deeply nested genetics without it)
// Maybe I can get rid of it, but that is for another day...
pub trait IndexType {
    fn as_index(&self) -> usize;
}
impl<TI> IndexType for Wrapper<TI>
where
    TI: TypeInfo<WrappedType = usize>,
{
    fn as_index(&self) -> usize {
        self.0
    }
}

While it doesn't make me happy to have to implement Index for every sequence type, at least every generic one, I don't think there is any way around that. For single indices, it is just this:

// Generic index implementation. (The real situation is a bit more
// complicated because I need to specify which types each index type
// is allowed to index, but this is the gist of it)

// Indexing a single element in a vector
impl<TI, T> std::ops::Index<Wrapper<TI>> for Vec<T>
where
    TI: TypeInfo,
    TI: CanIndex<Vec<T>>,
    Wrapper<TI>: IndexType,
{
    type Output = T;
    fn index(&self, i: Wrapper<TI>) -> &Self::Output {
        &self[i.as_index()]
    }
}

// Indexing a single element in a slice
impl<TI, T> std::ops::Index<Wrapper<TI>> for [T]
where
    TI: TypeInfo,
    TI: CanIndex<[T]>,
    Wrapper<TI>: IndexType,
{
    type Output = T;
    fn index(&self, i: Wrapper<TI>) -> &Self::Output {
        &self[i.as_index()]
    }
}

For my new Range type, I went with an enum. It will be more convenient for the things I want to do with it.

// My own type of ranges, now that I cannot use the built-in type...
/// Wrapper of Range that we can work with within Rust's type system
#[derive(Clone, Copy)]
pub enum Range<Idx> {
    Closed(Idx, Idx), // start..end
    Left(Idx),        // start..
    Right(Idx),       // ..end
    Full,             // ..
}

The type needs a constructor, which is complicated by Rust creating different types when you use the .. operator, but you can do it like this:

pub trait GenRange<R, Idx> {
    fn range(r: R) -> Range<Idx>;
}
/*

 Now implement that trait for the different range types.
 Is there a better way?

 */

// Now I can build ranges with this function:
pub fn range<Idx, R: GenRange<R, Idx>>(r: R) -> Range<Idx> {
    R::range(r)
}

With this, I can also implement indexing for ranges. I can use CanIndex<> to specify that I can index with ranges for any type that I can index individual items with.

impl<Idx, T> std::ops::Index<Range<Idx>> for Vec<T>
where
    Idx: IndexType,
    Idx: CanIndex<Vec<T>>,
{
    type Output = [T];
    fn index(&self, r: Range<Idx>) -> &Self::Output {
        match r {
            Range::Closed(start, end) => &self[start.as_index()..end.as_index()],
            Range::Left(start) => &self[start.as_index()..],
            Range::Right(end) => &self[..end.as_index()],
            Range::Full => &self[..],
        }
    }
}

impl<Idx, T> std::ops::Index<Range<Idx>> for [T]
where
    Idx: IndexType,
    Idx: CanIndex<[T]>,
{
    type Output = [T];
    fn index(&self, r: Range<Idx>) -> &Self::Output {
        match r {
            Range::Closed(start, end) => &self[start.as_index()..end.as_index()],
            Range::Left(start) => &self[start.as_index()..],
            Range::Right(end) => &self[..end.as_index()],
            Range::Full => &self[..],
        }
    }
}

It got rather complicated, so I need to clean it up as much as I can, but at least I am beginning to believe that it can be done. And once that is done, I need to figure out a good way to add the usual std::ops::Range interface to Range. But this will do for today.


问:
What can MyPy detect and what can it not?
I just started with MyPy to add more static typing to my python programs. I tried this:

```<code>import sys

def summe (a: int, b: int):
    print (a + b)

def main():
    x: int = 10
    y: int = 20
    z: str = '30'
    summe (x, y)
    summe (x, z)

if __name__ == '__main__':
    sys.exit(main())
</code>```

and this is obviously a type error and crashes at runtime but MyPy says: Success: no issues found in 1 source file

Am I doing something wrong, missed some setting? I have Windows 10, Python 3.10, latest MyPy under Eclipse.

答:
Return value is expressed with ->:

```<code>#                          -> Return value
def summe (a: int, b: int) -> None:
    print (a + b)

#          -> Return value
def main() -> None:
    x: int = 10
    y: int = 20
    z: str = '30'
    summe (x, y)
    summe (x, z)

if __name__ == '__main__':
    sys.exit(main())
</code>```

Body:
I just started with MyPy to add more static typing to my python programs. I tried this:

import sys

def summe (a: int, b: int):
    print (a + b)

def main():
    x: int = 10
    y: int = 20
    z: str = '30'
    summe (x, y)
    summe (x, z)

if __name__ == '__main__':
    sys.exit(main())

and this is obviously a type error and crashes at runtime but MyPy says: Success: no issues found in 1 source file

Am I doing something wrong, missed some setting? I have Windows 10, Python 3.10, latest MyPy under Eclipse.

Body:
Return value is expressed with ->:

#                          -> Return value
def summe (a: int, b: int) -> None:
    print (a + b)

#          -> Return value
def main() -> None:
    x: int = 10
    y: int = 20
    z: str = '30'
    summe (x, y)
    summe (x, z)

if __name__ == '__main__':
    sys.exit(main())


问:
if statement to select a channel in input block with nextflow
I am currently writing my first nextflow pipeline and I need to run different process in function of the parameter.

In fact, I would like, in one process, to select the channel where the input come from.
I've tested like that :

```<code>process foo{

  input:
  if(params.bar && params.bar2)
  {
    file reads from channel1.flatten()
  }
  else
  {
    file reads from channel_2.flatten()
  }

output:
  publishDir "$params.output_dir"
  file "output_file" into channel_3

  """
  my command line
  """

</code>```

I obtain this error and I don't understand why.

```<code>No such variable: reads
</code>```

Is there a way to do something like that ?
Thanks !

答:
It's a bit of a weird error, but basically you just need to make sure your input declaration follows/matches the required syntax:

```<code>input:
  <input qualifier> <input name> [from <source channel>] [attributes]
</code>```

One solution might be to use the ternary operator to replace your if/else branch, for example:

```<code>ch1 = Channel.of( 'hello', 'world' )
ch2 = Channel.of( 1, 3, 5, 7, 9 )

params.foo = false
params.bar = false

process test {

    echo true

    input:
    val myval from ( params.foo && params.bar ? ch1 : ch2 )

    """
    echo -n "${myval}"
    """
}
</code>```

Results:

```<code>$ nextflow run script.nf
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [shrivelled_stone] - revision: 7b3f3a51df
executor >  local (5)
[3b/fafa5e] process > test (2) [100%] 5 of 5 ✔
1
5
9
7
3

</code>```
```<code>$ nextflow run script.nf --foo --bar
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [irreverent_mahavira] - revision: 7b3f3a51df
executor >  local (2)
[d2/09d418] process > test (1) [100%] 2 of 2 ✔
world
hello

</code>```

Note that the new DSL 2 decouples the channel inputs from the process declaration, which might help to keep things readable, especially if the condition or action statements are more complex. For example:

```<code>nextflow.enable.dsl=2

params.foo = false
params.bar = false

process test {

    echo true

    input:
    val myval

    """
    echo -n "${myval}"
    """
}

workflow {

    ch1 = Channel.of( 'hello', 'world' )
    ch2 = Channel.of( 1, 3, 5, 7, 9 )

    if( params.foo && params.bar ) {
        test( ch1 )
    } else {
        test( ch2 )
    }
}
</code>```

Results:

```<code>$ nextflow run script.nf
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [nauseous_pare] - revision: e1c4770ff1
executor >  local (5)
[36/49d8da] process > test (4) [100%] 5 of 5 ✔
9
1
3
5
7

</code>```
```<code>$ nextflow run script.nf --foo --bar
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [goofy_euler] - revision: e1c4770ff1
executor >  local (2)
[56/e635e8] process > test (2) [100%] 2 of 2 ✔
world
hello

</code>```

Body:
I am currently writing my first nextflow pipeline and I need to run different process in function of the parameter.

In fact, I would like, in one process, to select the channel where the input come from.
I've tested like that :

process foo{

  input:
  if(params.bar && params.bar2)
  {
    file reads from channel1.flatten()
  }
  else
  {
    file reads from channel_2.flatten()
  }

output:
  publishDir "$params.output_dir"
  file "output_file" into channel_3

  """
  my command line
  """

I obtain this error and I don't understand why.

No such variable: reads

Is there a way to do something like that ?
Thanks !

Body:
It's a bit of a weird error, but basically you just need to make sure your input declaration follows/matches the required syntax:

input:
  <input qualifier> <input name> [from <source channel>] [attributes]

One solution might be to use the ternary operator to replace your if/else branch, for example:

ch1 = Channel.of( 'hello', 'world' )
ch2 = Channel.of( 1, 3, 5, 7, 9 )

params.foo = false
params.bar = false

process test {

    echo true

    input:
    val myval from ( params.foo && params.bar ? ch1 : ch2 )

    """
    echo -n "${myval}"
    """
}

Results:

$ nextflow run script.nf
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [shrivelled_stone] - revision: 7b3f3a51df
executor >  local (5)
[3b/fafa5e] process > test (2) [100%] 5 of 5 ✔
1
5
9
7
3

$ nextflow run script.nf --foo --bar
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [irreverent_mahavira] - revision: 7b3f3a51df
executor >  local (2)
[d2/09d418] process > test (1) [100%] 2 of 2 ✔
world
hello

Note that the new DSL 2 decouples the channel inputs from the process declaration, which might help to keep things readable, especially if the condition or action statements are more complex. For example:

nextflow.enable.dsl=2

params.foo = false
params.bar = false

process test {

    echo true

    input:
    val myval

    """
    echo -n "${myval}"
    """
}

workflow {

    ch1 = Channel.of( 'hello', 'world' )
    ch2 = Channel.of( 1, 3, 5, 7, 9 )

    if( params.foo && params.bar ) {
        test( ch1 )
    } else {
        test( ch2 )
    }
}

Results:

$ nextflow run script.nf
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [nauseous_pare] - revision: e1c4770ff1
executor >  local (5)
[36/49d8da] process > test (4) [100%] 5 of 5 ✔
9
1
3
5
7

$ nextflow run script.nf --foo --bar
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [goofy_euler] - revision: e1c4770ff1
executor >  local (2)
[56/e635e8] process > test (2) [100%] 2 of 2 ✔
world
hello


问:
perform calculation on column of a dataframe using data from another dataframe
I have two dataframes, one called order_values & the other fx_rates. They look like below.

What I need to do is convert the value_loc value in the order_values dataframe into EUR's using the fx_rates dataframe.

In reality I won't know how many different currency there are & its likely to be more than shown below.

My current solution I believe is far from optimal. I loop through each different currency (i.e. USD, JPY etc) and merge that currency column (EURUSD, EURJPY) to the order_values dataframe & perform the calculation to convert the value_loc into value_eur & then drop the currency column from the order_values dataframe.

```<code>  order_values
  order_num   value_loc  currency   date
  1           2,345      USD        2-12-2021
  2           104        EUR        2-12-2021
  3           20,000     JPY        2-15-2021
  4           550        USD        3-06-2021

  fx_rates
  date       pair    rate
  2-12-2021  EURUSD  1.5
  2-12-2021  EURJPY  5
  2-12-2021  EUREUR  1
  ...
  3-06-2021  EURUSD  1.56
  3-06-2021  EURJPY  5.6
  3-06-2021  EUREUR  1
</code>```

答:
FYI, a one-line version of the solution of @jezrael:</p>
```<code>order_values['value_loc'] = (
    order_values['value_loc'].str.replace(',', '').astype(float)
    * order_values[['date', 'currency']].merge(fx_rates.assign(currency=fx_rates['pair'].str[3:]), how='left')['rate']
)
print(order_values)

# Output
   order_num  value_loc currency       date
0          1     3517.5      USD  2-12-2021
1          2      104.0      EUR  2-12-2021
2          3        NaN      JPY  2-15-2021
3          4      858.0      USD  3-06-2021
</code>```

Body:
I have two dataframes, one called order_values & the other fx_rates. They look like below.

What I need to do is convert the value_loc value in the order_values dataframe into EUR's using the fx_rates dataframe.

In reality I won't know how many different currency there are & its likely to be more than shown below.

My current solution I believe is far from optimal. I loop through each different currency (i.e. USD, JPY etc) and merge that currency column (EURUSD, EURJPY) to the order_values dataframe & perform the calculation to convert the value_loc into value_eur & then drop the currency column from the order_values dataframe.

  order_values
  order_num   value_loc  currency   date
  1           2,345      USD        2-12-2021
  2           104        EUR        2-12-2021
  3           20,000     JPY        2-15-2021
  4           550        USD        3-06-2021

  fx_rates
  date       pair    rate
  2-12-2021  EURUSD  1.5
  2-12-2021  EURJPY  5
  2-12-2021  EUREUR  1
  ...
  3-06-2021  EURUSD  1.56
  3-06-2021  EURJPY  5.6
  3-06-2021  EUREUR  1

Body:
FYI, a one-line version of the solution of @jezrael:

order_values['value_loc'] = (
    order_values['value_loc'].str.replace(',', '').astype(float)
    * order_values[['date', 'currency']].merge(fx_rates.assign(currency=fx_rates['pair'].str[3:]), how='left')['rate']
)
print(order_values)

# Output
   order_num  value_loc currency       date
0          1     3517.5      USD  2-12-2021
1          2      104.0      EUR  2-12-2021
2          3        NaN      JPY  2-15-2021
3          4      858.0      USD  3-06-2021


问:
SMTP email system using RDS database
For context here is my code:

```<code>import pymysql
import os
import smtplib
from email.message import EmailMessage

# RDS config
endpoint = '**************'
username = '*****'
password = '*********'
database_name = '**********'

#connection config

connection = pymysql.connect(host=endpoint,user=username,passwd=password,db=database_name)

def handler(event, context):
    cursor = connection.cursor()
    cursor.execute('SELECT `Presenters`.Email FROM `Main` INNER JOIN `Presenters` ON `Main`.`PresenterID` = `Presenters`.`PresentersID` WHERE `Main`.`Read Day` ="Wednesday"')

    rows = cursor.fetchall()

    for row in rows:
        print("{0}".format(row[0]))

    EMAIL_ADDRESS = "***********"
    EMAIL_PASSWORD = "*********"

    msg = EmailMessage()
    msg['Subject'] = "***********"
    msg['From'] = EMAIL_ADDRESS
    msg['To'] = ["{0}".format(row[0]),]

    msg.set_content('**************')

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        smtp.send_message(msg)
</code>```

The system works fine mostly a mysql query retrieves a series of emails from an RDS DB and feeds them into the recipients variable however it only seems to send emails to one of the emails not both/all of them.

here is the output log from the lambda function if it helps:

```<code>Test Event Name
test

Response
null

Function Logs
START RequestId: cd5e4bd8-28fc-4a0f-af0c-5f8608b46a57 Version: $LATEST
placeholder@email.example
placeholder@email.example
END RequestId: cd5e4bd8-28fc-4a0f-af0c-5f8608b46a57
REPORT RequestId: cd5e4bd8-28fc-4a0f-af0c-5f8608b46a57  Duration: 2036.07 ms    Billed Duration: 2037 ms    Memory Size: 128 MB Max Memory Used: 43 MB  Init Duration: 153.63 ms

Request ID
cd5e4bd8-28fc-4a0f-af0c-5f8608b46a57
</code>```

答:
You need to loop through all the rows to send emails to recipients defined in each row. Currently, you are using a single row's data to send one email. Following should work for you -

```<code>def handler(event, context):
    cursor = connection.cursor()
    cursor.execute('SELECT `Presenters`.Email FROM `Main` INNER JOIN `Presenters` ON `Main`.`PresenterID` = `Presenters`.`PresentersID` WHERE `Main`.`Read Day` ="Wednesday"')

    rows = cursor.fetchall()

    for row in rows:
        print("{0}".format(row[0]))

    EMAIL_ADDRESS = "***********"
    EMAIL_PASSWORD = "*********"

    for row in rows:
        msg = EmailMessage()
        msg['Subject'] = "***********"
        msg['From'] = EMAIL_ADDRESS
        msg['To'] = ["{0}".format(row[0]),]

        msg.set_content('**************')

        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
            smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
            smtp.send_message(msg)

</code>```

Title: SMTP email system using RDS database

Body:
For context here is my code:

import pymysql
import os
import smtplib
from email.message import EmailMessage

# RDS config
endpoint = '**************'
username = '*****'
password = '*********'
database_name = '**********'

#connection config

connection = pymysql.connect(host=endpoint,user=username,passwd=password,db=database_name)

def handler(event, context):
    cursor = connection.cursor()
    cursor.execute('SELECT `Presenters`.Email FROM `Main` INNER JOIN `Presenters` ON `Main`.`PresenterID` = `Presenters`.`PresentersID` WHERE `Main`.`Read Day` ="Wednesday"')

    rows = cursor.fetchall()

    for row in rows:
        print("{0}".format(row[0]))

    EMAIL_ADDRESS = "***********"
    EMAIL_PASSWORD = "*********"

    msg = EmailMessage()
    msg['Subject'] = "***********"
    msg['From'] = EMAIL_ADDRESS
    msg['To'] = ["{0}".format(row[0]),]

    msg.set_content('**************')

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        smtp.send_message(msg)

The system works fine mostly a mysql query retrieves a series of emails from an RDS DB and feeds them into the recipients variable however it only seems to send emails to one of the emails not both/all of them.

here is the output log from the lambda function if it helps:

Test Event Name
test

Response
null

Function Logs
START RequestId: cd5e4bd8-28fc-4a0f-af0c-5f8608b46a57 Version: $LATEST
placeholder@email.example
placeholder@email.example
END RequestId: cd5e4bd8-28fc-4a0f-af0c-5f8608b46a57
REPORT RequestId: cd5e4bd8-28fc-4a0f-af0c-5f8608b46a57  Duration: 2036.07 ms    Billed Duration: 2037 ms    Memory Size: 128 MB Max Memory Used: 43 MB  Init Duration: 153.63 ms

Request ID
cd5e4bd8-28fc-4a0f-af0c-5f8608b46a57

Body:
You need to loop through all the rows to send emails to recipients defined in each row. Currently, you are using a single row's data to send one email. Following should work for you -

def handler(event, context):
    cursor = connection.cursor()
    cursor.execute('SELECT `Presenters`.Email FROM `Main` INNER JOIN `Presenters` ON `Main`.`PresenterID` = `Presenters`.`PresentersID` WHERE `Main`.`Read Day` ="Wednesday"')

    rows = cursor.fetchall()

    for row in rows:
        print("{0}".format(row[0]))

    EMAIL_ADDRESS = "***********"
    EMAIL_PASSWORD = "*********"

    for row in rows:
        msg = EmailMessage()
        msg['Subject'] = "***********"
        msg['From'] = EMAIL_ADDRESS
        msg['To'] = ["{0}".format(row[0]),]

        msg.set_content('**************')

        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
            smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
            smtp.send_message(msg)


问:
Android: How to make UI thread to wait till AsycTask completes
Currently, I'm executing a heavy task inside AsycTask which uploads images. When I do it via AsycTask, the application closes and no error message appear in the logcat.

```<code>    private class SendIncidentTask extends AsyncTask<Double, Void, Void>{

            @Override
            protected Void doInBackground(Double... params) {
                lat1 = params[0];
                log1 = params[1];
                SendingIncident sincident  = new SendingIncident();
                sincident.sendInciWithoutAttachment(lat1, log1);
                sincident.submitWithAttachment(lat1, log1);
                return null;
            }

   }
</code>```

I think issues occur when the UI thread and AsycTask execute in parallel. How can I make the UI thread wait until the AsycTask finishes?

Thanks in advance.

答: Use onPostExecute method to load UI.This is automaically called after doInBackground is completed </p>

Body:
Currently, I'm executing a heavy task inside AsycTask which uploads images. When I do it via AsycTask, the application closes and no error message appear in the logcat.

    private class SendIncidentTask extends AsyncTask<Double, Void, Void>{

            @Override
            protected Void doInBackground(Double... params) {
                lat1 = params[0];
                log1 = params[1];
                SendingIncident sincident  = new SendingIncident();
                sincident.sendInciWithoutAttachment(lat1, log1);
                sincident.submitWithAttachment(lat1, log1);
                return null;
            }

   }

I think issues occur when the UI thread and AsycTask execute in parallel. How can I make the UI thread wait until the AsycTask finishes?

Thanks in advance.


问:
Can I have a hide/show button but the hidden script doesn't show?
This is my code, but I don't know how to debug it. Please help me and my code. I am trying to add a hide/show button for my contents list, but I don't know what is wrong with it. It is greatly appreciated. Ummm... I don't know what to say as I have to add more information. Just comment to ask any queries.</p>
```<code><!DOCTYPE html>
<html>
    <head>
        <title>How to be Asian</title>
        <style type="text/css">
            h1, h2, h3, h4, h5, h6 {
                font-weight: bold;
                border: 0px;
                margin: 2px;
            }
            h2
                {
                text-indent: 20px;
            }
            ul {
                margin-top: 2%;
            }
            body {
                margin: 2px;
                border: 5px;
                padding: 13px;
            }
            #Contents {
                display: table;
                padding: 7px;
                border: 1px solid #a2a9b1;
                background-color: #f8f9fa;
                font-size: 95%;
                text-align: left;
                float: right;
                width: 15%;
            }
            #Quote {
                text-align: center;
                line-height: 2em;
                padding-left: 25%;
                padding-right: 25%;
                padding-top: 20px;
                padding-bottom: 20px;
                display: block;
            }
            .Bonus {
                display: inline;
                font-size: 1.3em;
            }

            body{
                padding: 1%;
                margin: 1%
            }

            p h1{
                display: inline;
                float: left;
            }
        </style>

    </head>
    <body>
        <script>
            function myFunction() {
                var x = document.getElementById("Contents");
                    if (x.style.display === "none") {
                        x.style.display = "block";
                    } else {
                        x.style.display = "none";
                    }
                }
        </script>
        <div id="Contents">
            <h1 id="Contents">Contents</h1><button onclick="myFunction()">[show]</button>

            <ol>
                <li><a href="#Chapter_1">Chapter 1: Early Childhood</a></li>
                <li><a href="#Chapter_2">Chapter 2: Primary School Education</a></li>
                <li><a href="#Chapter_3">Chapter 3: High School Education</a></li>
                <li><a href="#Chapter_4">Chapter 4: College/University Education</a></li>
                <li><a href="#Chapter_5">Chapter 5: Employment</a></li>
                <li><a href="#Chapter_6">Chapter 6: Relationships</a></li>
                <li><a href="#Chapter_7">Chapter 7: Family Gatherings</a></li>
                <ol>
                    <li><a href="#Chapter_7.1">Chapter 7.1: Public Holidays</a></li>
                    <li><a href="#Chapter_7.2">Chapter 7.2: Death and mourning</a></li>
                </ol>
                <li><a href="#Chapter_8">Chapter 8: Retirement</a></li>
                <li><a href="#Chapter_9">Chapter 9: Death</a></li>
            </ol>
        </div>
        <div>
            <h1 id="Chapter_1">Chapter 1: Early Childhood</h1>
            <p>When Asian kids go through pre-schooling years and primary school, children are always put under pressure and always neglected so that they work harder and feel like they are worth something after some time and not actually useless.<br><span id="Quote">"We just never praise our children, always compare them to people who are better, so they grow up never feeling good enough and then have to constantly outdo everybody else to feel like they aren’t worthless." <br> Quoted from Stven He's father</span></p>
        </div>
        <div>
            <h1 id="Chapter_2">Chapter 2: Primary School Education</h1>
            <p>Asian kids are always compared to their peers by their parents. This is because Asian parents want the best of the child. This also means that children are used too much for the simplest of their demands. <br> <br> During this period of learning, PTSD is most used so that children are trained to cope "in the future". "In the future" meaning whenever you go back to your parents house when you are and adult. But this training will deal emotional damage, social anxiety and negliegence. This part of life is when most of the tactics are used so that the child can get used to them. Once they know how to leave the situation, create more problems for the child so that they get more experience. </p>
            <p>This period of their life is when you can take advantage of them. For example, when you are shopping, tell your child that you are going to get something common in the household, like rice. Then, go to the aisle and watch them go to the cashier person and panic as you are assumed to get rice. Once they start getting constipated, go back with a 5kg bag of rice and start telling your child off for constipating in public. </p>
            <div style="text-align: center;">
                <h4 class="Bonus">BONUS! </h4><p class="Bonus">If you can humiliate your child in front of anyone, especially your child's friends, it will intergrate information for life. </p>
            </div>
        </div>
        <div>
            <h1 id="Chapter_3">Chapter 3: High School Education</h1>
            <p>This period of life is when you get to choose his choices. </p>
        </div>
        <div>
            <h1 id="Chapter_4">Chapter 4: College/University Education</h1>
        </div>
        <div>
            <h1 id="Chapter_5">Chapter 5: Employment</h1>
        </div>
        <div>
            <h1 id="Chapter_6">Chapter 6: Relationships</h1>
        </div>
        <div>
            <h1 id="Chapter_7">Chapter 7: Family Gatherings</h1>
            <h2 id="Chapter_7.1">Chapter 7.1: Public Holidays</h2>
            <h2 id="Chapter_7.2">Chapter 7.2: Death and mourning</h2>
        </div>
        <div>
            <h1 id="Chapter_8">Chapter 8: Retirement</h1>
        </div>
        <div>
            <h1 id="Chapter_9">Chapter 9: Death</h1>
        </div>
    </body>
</html>
</code>```

答:
So it seems that you "hide/show" button hides the whole div called "Contents". meaning that the button also disapears. So you have to make it so that only the
 element get hidden.

You can do this by using the same code part but have a ID on the
 element like "ContentTable" and then instead targeting the "Contents" target the element "ContentTable". This way when you press the "hide" button it will still show the div and therefore the button is still there. Allowing you to press the button again to "show" the contents table again.

Like this:

```<code><script>
        function myFunction() {
            var x = document.getElementById("ContentsTable");
                if (x.style.display === "none") {
                    x.style.display = "block";
                } else {
                    x.style.display = "none";
                }
            }
    </script>
    <div id="Contents">
        <h1>Contents</h1><button onclick="myFunction()">[show]</button>

        <ol id="ContentsTable">
            <li><a href="#Chapter_1">Chapter 1: Early Childhood</a></li>
            <li><a href="#Chapter_2">Chapter 2: Primary School Education</a></li>
            <li><a href="#Chapter_3">Chapter 3: High School Education</a></li>
            <li><a href="#Chapter_4">Chapter 4: College/University Education</a></li>
            <li><a href="#Chapter_5">Chapter 5: Employment</a></li>
            <li><a href="#Chapter_6">Chapter 6: Relationships</a></li>
            <li><a href="#Chapter_7">Chapter 7: Family Gatherings</a></li>
            <ol>
                <li><a href="#Chapter_7.1">Chapter 7.1: Public Holidays</a></li>
                <li><a href="#Chapter_7.2">Chapter 7.2: Death and mourning</a></li>
            </ol>
            <li><a href="#Chapter_8">Chapter 8: Retirement</a></li>
            <li><a href="#Chapter_9">Chapter 9: Death</a></li>
        </ol>
    </div>
</code>```

Body:
This is my code, but I don't know how to debug it. Please help me and my code. I am trying to add a hide/show button for my contents list, but I don't know what is wrong with it. It is greatly appreciated. Ummm... I don't know what to say as I have to add more information. Just comment to ask any queries.

<!DOCTYPE html>

        <title>How to be Asian</title>

Contents
<button onclick="myFunction()">[show]</button>

Chapter 1: Early Childhood

Chapter 2: Primary School Education

Chapter 3: High School Education

Chapter 4: College/University Education

Chapter 5: Employment

Chapter 6: Relationships

Chapter 7: Family Gatherings

Chapter 7.1: Public Holidays

Chapter 7.2: Death and mourning

Chapter 8: Retirement

Chapter 9: Death

Chapter 1: Early Childhood

When Asian kids go through pre-schooling years and primary school, children are always put under pressure and always neglected so that they work harder and feel like they are worth something after some time and not actually useless.
"We just never praise our children, always compare them to people who are better, so they grow up never feeling good enough and then have to constantly outdo everybody else to feel like they aren’t worthless."
 Quoted from Stven He's father

Chapter 2: Primary School Education

Asian kids are always compared to their peers by their parents. This is because Asian parents want the best of the child. This also means that children are used too much for the simplest of their demands.

 During this period of learning, PTSD is most used so that children are trained to cope "in the future". "In the future" meaning whenever you go back to your parents house when you are and adult. But this training will deal emotional damage, social anxiety and negliegence. This part of life is when most of the tactics are used so that the child can get used to them. Once they know how to leave the situation, create more problems for the child so that they get more experience.

This period of their life is when you can take advantage of them. For example, when you are shopping, tell your child that you are going to get something common in the household, like rice. Then, go to the aisle and watch them go to the cashier person and panic as you are assumed to get rice. Once they start getting constipated, go back with a 5kg bag of rice and start telling your child off for constipating in public.

BONUS!

If you can humiliate your child in front of anyone, especially your child's friends, it will intergrate information for life.

Chapter 3: High School Education

This period of life is when you get to choose his choices.

Chapter 4: College/University Education

Chapter 5: Employment

Chapter 6: Relationships

Chapter 7: Family Gatherings

Chapter 7.1: Public Holidays

Chapter 7.2: Death and mourning

Chapter 8: Retirement

Chapter 9: Death

Body:
So it seems that you "hide/show" button hides the whole div called "Contents". meaning that the button also disapears. So you have to make it so that only the <ol> element get hidden.

You can do this by using the same code part but have a ID on the <ol> element like "ContentTable" and then instead targeting the "Contents" target the element "ContentTable". This way when you press the "hide" button it will still show the div and therefore the button is still there. Allowing you to press the button again to "show" the contents table again.

Like this:

<script>
        function myFunction() {
            var x = document.getElementById("ContentsTable");
                if (x.style.display === "none") {
                    x.style.display = "block";
                } else {
                    x.style.display = "none";
                }
            }
    </script>
    <div id="Contents">
        <h1>Contents</h1><button onclick="myFunction()">[show]</button>

        <ol id="ContentsTable">
            <li><a href="#Chapter_1">Chapter 1: Early Childhood</a></li>
            <li><a href="#Chapter_2">Chapter 2: Primary School Education</a></li>
            <li><a href="#Chapter_3">Chapter 3: High School Education</a></li>
            <li><a href="#Chapter_4">Chapter 4: College/University Education</a></li>
            <li><a href="#Chapter_5">Chapter 5: Employment</a></li>
            <li><a href="#Chapter_6">Chapter 6: Relationships</a></li>
            <li><a href="#Chapter_7">Chapter 7: Family Gatherings</a></li>
            <ol>
                <li><a href="#Chapter_7.1">Chapter 7.1: Public Holidays</a></li>
                <li><a href="#Chapter_7.2">Chapter 7.2: Death and mourning</a></li>
            </ol>
            <li><a href="#Chapter_8">Chapter 8: Retirement</a></li>
            <li><a href="#Chapter_9">Chapter 9: Death</a></li>
        </ol>
    </div>


问:
Flutter: How can use FieldValue.arrayRemove?
How can I delete an array of array of objects from Firestore? I want to delete it inside a list.generate

Here is my database structure, I want to delete [{street A, number 25}]

```<code>List.generate(
  ...
  IconButton(
    icon: const Icon(CupertinoIcons.trash),
    onPressed: () async {
      try {
        await FirebaseFirestore.instance
            .collection('users')
            .doc(data['uid'])
            .update(
          {
            'adress':
                FieldValue.arrayRemove(
                    ??)
          },
        );
      } catch (e) {
        print(e);
      }
    },
  ),
)),
</code>```

答:
As I see in your screenshot, the adress field is not of type array, it's a Map:

So there is no way you can call FieldValue.arrayRemove. If you want to remove that field, then please use the following lines of code:

```<code>Firestore.instance.collection('users').document(data['uid']).set(
    {'adress': FieldValue.delete()},
    SetOptions(
      merge: true,
    ),
)
</code>```

Edit:

After you have updated the screenshot, now the adress field is indeed of type array:

If you want to delete a specific object from the array using FieldValue.delete(), you should use all the data in the object and not partial data. I have even written an article regarding updating an array of objects in Cloud Firestore:

How to update an array of objects in Firestore?

Edit2:

In code it should look like this:

```<code>Firestore.instance.collection('users').document(data['uid']).update({
    'adress': FieldValue.arrayRemove(elementToDelete),
});
</code>```

Please note that elementToDelete object should contain both fields populated. The number should hold the value of "25" and street should hold the value of "street A". It will not work if you use only one.

However, if you thought that Firestore provides a direct way to delete an array element by index, please note that is not possible. In such a case, you'll have to read the document, remove the element from the array, then write the document back to Firestore.

Body:
How can I delete an array of array of objects from Firestore? I want to delete it inside a list.generate

Here is my database structure, I want to delete [{street A, number 25}]

List.generate(
  ...
  IconButton(
    icon: const Icon(CupertinoIcons.trash),
    onPressed: () async {
      try {
        await FirebaseFirestore.instance
            .collection('users')
            .doc(data['uid'])
            .update(
          {
            'adress':
                FieldValue.arrayRemove(
                    ??)
          },
        );
      } catch (e) {
        print(e);
      }
    },
  ),
)),

Body:
As I see in your screenshot, the adress field is not of type array, it's a Map:

So there is no way you can call FieldValue.arrayRemove. If you want to remove that field, then please use the following lines of code:

Firestore.instance.collection('users').document(data['uid']).set(
    {'adress': FieldValue.delete()},
    SetOptions(
      merge: true,
    ),
)

Edit:

After you have updated the screenshot, now the adress field is indeed of type array:

If you want to delete a specific object from the array using FieldValue.delete(), you should use all the data in the object and not partial data. I have even written an article regarding updating an array of objects in Cloud Firestore:

How to update an array of objects in Firestore?

Edit2:

In code it should look like this:

Firestore.instance.collection('users').document(data['uid']).update({
    'adress': FieldValue.arrayRemove(elementToDelete),
});

Please note that elementToDelete object should contain both fields populated. The number should hold the value of "25" and street should hold the value of "street A". It will not work if you use only one.

However, if you thought that Firestore provides a direct way to delete an array element by index, please note that is not possible. In such a case, you'll have to read the document, remove the element from the array, then write the document back to Firestore.


问:
How to add frozen columns to primeNG when rows are rendering dynamically in Angular
I was looking for help to add the frozen columns feature in my primeng table where the columns and rows are dynamically rendered.

I do have a config( isPK: true) that came from data on which I want to make frozen columns.

I have tried following stackblitz but I cannot found a solution to match the example given in the documentation of PrimeNG

Thanks, @Owen for the answer but now If I try to add an extra column in the HTML itself it is getting doubled like this,

https://stackblitz.com/edit/primeng-tablescroll-demo-jvmrfs

答:
I added a property isFrozenColumn in the column definition like that and it worked perfectly

See Frozen Columns parte in https://www.primefaces.org/primeng/showcase/#/table/scroll

```<code>columns = [
        {
            field: 'name',
            header: 'Name',
            isFrozenColumn: true
        },
        {
            field: 'Phone',
            header: 'phone',
            isFrozenColumn: false
        }]
</code>```

Header

```<code><th alignFrozen="left"
        pFrozenColumn
        [frozen]="true">Actions</th>
<ng-container *ngFor="let col of columns">
    <th class="width-small"
        alignFrozen="left"
        pFrozenColumn
        [frozen]="col?.isFrozenColumn">
        <p-header>{{ col.header }}</p-header>
    </th>
</ng-container>
</code>```

Body

```<code><td alignFrozen="left"
        pFrozenColumn
        [frozen]="true">
    <a type="button"
        (click)="edit(item)">Edit</a>
    </td>
<ng-container *ngFor="let col of columns">
    <td alignFrozen="left"
        pFrozenColumn
        [frozen]="col?.isFrozenColumn">
        {{ item[col.field] }}
    </td>
</ng-container>
</code>```

Body:
I added a property isFrozenColumn in the column definition like that and it worked perfectly

See Frozen Columns parte in https://www.primefaces.org/primeng/showcase/#/table/scroll

columns = [
        {
            field: 'name',
            header: 'Name',
            isFrozenColumn: true
        },
        {
            field: 'Phone',
            header: 'phone',
            isFrozenColumn: false
        }]

Header

<th alignFrozen="left"
        pFrozenColumn
        [frozen]="true">Actions</th>
<ng-container *ngFor="let col of columns">
    <th class="width-small"
        alignFrozen="left"
        pFrozenColumn
        [frozen]="col?.isFrozenColumn">
        <p-header>{{ col.header }}</p-header>
    </th>
</ng-container>

Body

<td alignFrozen="left"
        pFrozenColumn
        [frozen]="true">
    <a type="button"
        (click)="edit(item)">Edit</a>
    </td>
<ng-container *ngFor="let col of columns">
    <td alignFrozen="left"
        pFrozenColumn
        [frozen]="col?.isFrozenColumn">
        {{ item[col.field] }}
    </td>
</ng-container>


问:
can i delete nohup.out, Because it stopped writing?
I executed a python code in the AWS Lightsail linux server in the background
It contains 5M Records insertions and I added logs after every insertion.
I don't see log output after 852.

I Can see my process is still running the background

If I delete the nohup.out file will it recreate the file with new Logs?
How can I see the actual logs of the python code ?

答:
I assume you started your program using nohup like this:

```<code>nohup your_program maybe some arguments &
</code>```

The nohup command will redirect the output to nohup.out before starting your program. Your program does not know that the output is redirected. That's why you cannot make it recreate the output file nohup.out.

If you remove nohup.out you will only remove the directory entry. The file will still exist as an inode on your disk with all the data until your program terminates (or closes stdout and stderr), but you can no longer access the file by its name.

If you don't see any new output, then your program doesn't produce any. Note that the output is probably buffered, so it will appear in the file only when the program has written a certain amount of data.
You have to check what your program is doing. It might be blocked somehow or you might have a bug in your program.

Maybe you can use strace to check what system calls are done by your program.

Body:
I assume you started your program using nohup like this:

nohup your_program maybe some arguments &

The nohup command will redirect the output to nohup.out before starting your program. Your program does not know that the output is redirected. That's why you cannot make it recreate the output file nohup.out.

If you remove nohup.out you will only remove the directory entry. The file will still exist as an inode on your disk with all the data until your program terminates (or closes stdout and stderr), but you can no longer access the file by its name.

If you don't see any new output, then your program doesn't produce any. Note that the output is probably buffered, so it will appear in the file only when the program has written a certain amount of data.
You have to check what your program is doing. It might be blocked somehow or you might have a bug in your program.

Maybe you can use strace to check what system calls are done by your program.


问:
Rearrange seaborn countplot x-axis
I am using seaborn countplot on a pandas data series. The series looks like this:

```<code>df['col'] =

['Week 4',
 'Week 4',
 'Week 3',
 'Week 1',
 'Week 5',
 'Week 3',
 'Week 3',
 'Week 2',
 'Week 4',
 'Week 5',
 'Week 5',
 'Week 4',
 'Week 5',
 'Week 2',
 'Week 5',
 'Week 1',
 ..
 ..
 ..
 ..
]
</code>```

I'd like rearrange the x-axis to start with Week 1, Week 2, Week 3.... and so on.

```<code>sns.countplot(LeaseComp['Weeks on market'])
</code>```

答:
For seaborn:

```<code>sns.countplot( x = 'Weeks on market', data = LeaseComp,
              order = sorted(LeaseComp['Weeks on market'].unique()))
</code>```

Same plot can be achieved by what BEATHUB has posted, but it may produce some warnings.

Title: Rearrange seaborn countplot x-axis

Body:
I am using seaborn countplot on a pandas data series. The series looks like this:

df['col'] =

['Week 4',
 'Week 4',
 'Week 3',
 'Week 1',
 'Week 5',
 'Week 3',
 'Week 3',
 'Week 2',
 'Week 4',
 'Week 5',
 'Week 5',
 'Week 4',
 'Week 5',
 'Week 2',
 'Week 5',
 'Week 1',
 ..
 ..
 ..
 ..
]

I'd like rearrange the x-axis to start with Week 1, Week 2, Week 3.... and so on.

sns.countplot(LeaseComp['Weeks on market'])

Body:
For seaborn:

sns.countplot( x = 'Weeks on market', data = LeaseComp,
              order = sorted(LeaseComp['Weeks on market'].unique()))

Same plot can be achieved by what BEATHUB has posted, but it may produce some warnings.


问:
Match specific string from the first 3 characters and specific string anywhere from the 4th characters
Problem
I want to capture the string if the first 3 char is YZA, YZB, and YZB and another string is NUM12345 located anywhere after the first 3 chars.

Regex I am using that does not match the strings with the format described above:

^YZ[ABC]\sNUM12345
```
<p>Here are the sample lines:</p>
<pre class="lang-none prettyprint-override"><code>YZC/GH/A1/M,KNUM12345
YZB/M,SD-GG,K*NUM12345/A2
YZA/A1/M,SD-GG,KNUM12345/A2
YZB/M,SD-GG,K*NUM12345/A2/AA
YZA/A1/M,SD-GG,KNUM12345/A2/A2A
YZW/GH/A1/M,KNUM12345
YZR/M,SD-GG,K*NUM12345/A2
YZS/A1/M,SD-GG,KNUM12345/A2
YZT/M,SD-GG,K*NUM12345/A2/AA
YZJ/A1/M,SD-GG,KNUM12345/A2/A2A
</code>```

The lines I am trying to match:

YZC/GH/A1/M,KNUM12345
YZB/M,SD-GG,K*NUM12345/A2
YZA/A1/M,SD-GG,KNUM12345/A2
YZB/M,SD-GG,K*NUM12345/A2/AA
YZA/A1/M,SD-GG,KNUM12345/A2/A2A
```

Anyone can help correct the pattern below?

答:
You can use

^YZ[ABC].*NUM12345.*
```
<p>See the regex demo:</p>
<p><img src="https://i.stack.imgur.com/EWgQb.png" alt="enter image description here" /></p>
<p>If you want to remove all lines other than the ones that match the above pattern, you can use</p>
<pre class="lang-none prettyprint-override"><code>^(?!YZ[ABC].*NUM12345).*\R*
</code>```

See the regex demo:

Details:

^YZ[ABC].*NUM12345.* - start of string, YZ, A / B or C, then any zero or more chars (other than line break chars) as many as possible, NUM12345 and then any zero or more chars (other than line break chars) as many as possible.

^(?!YZ[ABC].*NUM12345).*\R* - start of string, then a negative  lookahead that fails the match if the above pattern is matched, and then any zero or more chars (other than line break chars) as many as possible and then any zero or more line break sequences.

Body:
Problem
I want to capture the string if the first 3 char is YZA, YZB, and YZB and another string is NUM12345 located anywhere after the first 3 chars.

Regex I am using that does not match the strings with the format described above:

^YZ[ABC]\sNUM12345

Here are the sample lines:

YZC/GH/A1/M,KNUM12345
YZB/M,SD-GG,K*NUM12345/A2
YZA/A1/M,SD-GG,KNUM12345/A2
YZB/M,SD-GG,K*NUM12345/A2/AA
YZA/A1/M,SD-GG,KNUM12345/A2/A2A
YZW/GH/A1/M,KNUM12345
YZR/M,SD-GG,K*NUM12345/A2
YZS/A1/M,SD-GG,KNUM12345/A2
YZT/M,SD-GG,K*NUM12345/A2/AA
YZJ/A1/M,SD-GG,KNUM12345/A2/A2A

The lines I am trying to match:

YZC/GH/A1/M,KNUM12345
YZB/M,SD-GG,K*NUM12345/A2
YZA/A1/M,SD-GG,KNUM12345/A2
YZB/M,SD-GG,K*NUM12345/A2/AA
YZA/A1/M,SD-GG,KNUM12345/A2/A2A

Anyone can help correct the pattern below?

Body:
You can use

^YZ[ABC].*NUM12345.*

See the regex demo:

If you want to remove all lines other than the ones that match the above pattern, you can use

^(?!YZ[ABC].*NUM12345).*\R*

See the regex demo:

Details:

^YZ[ABC].*NUM12345.* - start of string, YZ, A / B or C, then any zero or more chars (other than line break chars) as many as possible, NUM12345 and then any zero or more chars (other than line break chars) as many as possible.

^(?!YZ[ABC].*NUM12345).*\R* - start of string, then a negative  lookahead that fails the match if the above pattern is matched, and then any zero or more chars (other than line break chars) as many as possible and then any zero or more line break sequences.


问:
Ternary operators in JavaScript without an "else"
I've always had to put null in the else conditions that don't have anything. Is there a way around it?

For example,

```<code>condition ? x = true : null;
</code>```

Basically, is there a way to do the following?

```<code>condition ? x = true;
</code>```

Now it shows up as a syntax error.

FYI, here is some real example code:

```<code>!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;
</code>```

答:
The simple way to do this is:</p>
```<code>if (y == x) z;
</code>```

Body:
I've always had to put null in the else conditions that don't have anything. Is there a way around it?

For example,

condition ? x = true : null;

Basically, is there a way to do the following?

condition ? x = true;

Now it shows up as a syntax error.

FYI, here is some real example code:

!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;

Body:
The simple way to do this is:

if (y == x) z;