问:
How can you design a script that is prepared to take varied possible quantity of arguments as argv?
When you give a function a set of needed arguments or assign argv, the code demands that you give the correct number of args or it goes on to give, "expected number of things to unpack from a tuple is wrong", sorts of errors.

But I use scripts everyday that are very dynamic in how specifically the arguments can be given and in which types orders, etc.

I eventually imagine making scripts with a --help switch that list all the possible argv and options you can add, but for now as I am beginning, lets keep it very, somewhat simple:

I want the following to not raise error and to not EXPECT arguments to be given but to take them when they are there:

#!/usr/bin/env python3

from sys import argv

script, verbose_option, user_input = argv

if "verbose" in verbose_option:
    verbose_option = True
else:
    verbose_option = False

x = value
if verbose_option == True:
    print("var x is set to value...")
else:
    pass

if user_input == True: # if true, the var contains any value, correct?
    print(user_input)
else:
    print("user_input not given but, ... no problem!")
    user_input = input("> ") # or maybe it has a default value that can be changed from argv

if verbose_option == True:
    print("Would I really need this conditional on every line I left a verbose explanation on?")
else:
    pass
```

Somehow it has to know that user_input is not intended as verbose just because verbose isn't there, so... maybe a conditional branch that tests the len() of the tuple of arguments and figures, "well, that must be this and not that based on that number. OR.... is that overly complex and there is a better way?

This is a less important: how messy a verbose option must make the code if there isn't a better way than I imagined in the example code, but that's a bonus question. I want to not error and have default values for things or means of getting the data if not given as argv despite being able to be taken as argv.

答:
You can iterate over the arguments that way:

```<code>def handle_arguments(argv):
    env = {'user_input': []}
    for arg in argv:
        if arg in ['-v', '--verbose']
            env['verbose'] = True
        elif arg in ['-h', '--help']
            display_help()
            sys.exit(0)
        else
            env['user_input'] += [arg]

    if length(env['user_input']) == 0
        env['user_input'] = input('> ')
    else
        env['user_input'].join(' ')

    return env
</code>```

there you've got a function that takes arguments and returns a well formed env variable.

So then you can pass sys.argv to handle_arguments by removing the useless sys.argv[0] (useless in this context)

```<code>import sys

if __name__ == "__main__":
    env = handle_arguments(sys.argv[1:])
    do_stuff(**env)
</code>```

where stuff is either a function with the following prototype:

```<code>def do_stuff(user_input='', verbose=False):
</code>```

or you can make it take any argument:

```<code>def do_stuff(**kwargs):
</code>```

That being said, it's more or less the basic inner working of an argument parsing library. And to make it right, expectable by CLI users, you'd better use one, like Click, argparse or my personal favourite docopt.

Body:
When you give a function a set of needed arguments or assign argv, the code demands that you give the correct number of args or it goes on to give, "expected number of things to unpack from a tuple is wrong", sorts of errors.

But I use scripts everyday that are very dynamic in how specifically the arguments can be given and in which types orders, etc.

I eventually imagine making scripts with a --help switch that list all the possible argv and options you can add, but for now as I am beginning, lets keep it very, somewhat simple:

I want the following to not raise error and to not EXPECT arguments to be given but to take them when they are there:

#!/usr/bin/env python3

from sys import argv

script, verbose_option, user_input = argv

if "verbose" in verbose_option:
    verbose_option = True
else:
    verbose_option = False

x = value
if verbose_option == True:
    print("var x is set to value...")
else:
    pass

if user_input == True: # if true, the var contains any value, correct?
    print(user_input)
else:
    print("user_input not given but, ... no problem!")
    user_input = input("> ") # or maybe it has a default value that can be changed from argv

if verbose_option == True:
    print("Would I really need this conditional on every line I left a verbose explanation on?")
else:
    pass

Somehow it has to know that user_input is not intended as verbose just because verbose isn't there, so... maybe a conditional branch that tests the len() of the tuple of arguments and figures, "well, that must be this and not that based on that number. OR.... is that overly complex and there is a better way?

This is a less important: how messy a verbose option must make the code if there isn't a better way than I imagined in the example code, but that's a bonus question. I want to not error and have default values for things or means of getting the data if not given as argv despite being able to be taken as argv.

Body:
You can iterate over the arguments that way:

def handle_arguments(argv):
    env = {'user_input': []}
    for arg in argv:
        if arg in ['-v', '--verbose']
            env['verbose'] = True
        elif arg in ['-h', '--help']
            display_help()
            sys.exit(0)
        else
            env['user_input'] += [arg]

    if length(env['user_input']) == 0
        env['user_input'] = input('> ')
    else
        env['user_input'].join(' ')

    return env

there you've got a function that takes arguments and returns a well formed env variable.

So then you can pass sys.argv to handle_arguments by removing the useless sys.argv[0] (useless in this context)

import sys

if __name__ == "__main__":
    env = handle_arguments(sys.argv[1:])
    do_stuff(**env)

where stuff is either a function with the following prototype:

def do_stuff(user_input='', verbose=False):

or you can make it take any argument:

def do_stuff(**kwargs):

That being said, it's more or less the basic inner working of an argument parsing library. And to make it right, expectable by CLI users, you'd better use one, like Click, argparse or my personal favourite docopt.


来源: stackexchange

问:
Cant save data in multiple tables using cakePHP 3.7
Been trying to save data into other table when saving Fisica entity to the Database, since I am new to cakephp it seems impossible right now, have seen multiple posts, videos, documentations and none seems to work. Please somebody help me figure out what is wrong with that.

I found a huge mistake in my relations between the entitys, now it works like that:
Fisica belongsto Pessoa

associations at FisicasTable.php

```<code>$this->belongsTo('Pessoa')
        ->setForeignKey('id_pessoa')
        ->setJoinType('INNER')
        ->setClassName('Pessoas');
</code>```

Fisicas Controller

```<code>$fisica = $this->Fisicas->newEntity();
    if ($this->request->is('post')) {
        $fisica = $this->Fisicas->patchEntity($fisica, $this->request->getData(),['associated' => 'Pessoa']);
        if ($this->Fisicas->save($fisica))...
</code>```

Fisica add.ctp

```<code><legend><?= __('Add Fisica') ?></legend>
    <?php
        echo $this->Form->control('nr_cpf');
        echo $this->Form->control('dt_nascimento');
    ?>
    <legend><?= __('Add Pessoa') ?></legend>
    <?php
        echo $this->Form->control('pessoa.vr_nome');
        echo $this->Form->control('pessoa.nr_telefone');
        echo $this->Form->control('pessoa.vr_email');
    ?>
</code>```

I am getting the following error:
error

I expected this code to insert in the two tables when submitting a new register to Fisica add.ctp.

答: I found that i had an issue naming my tables in the database combined with the primary key naming pattern. Simply updating the names of the tables to "Fisicas" and "Pessoas" and changing their Primary and Foreign key's to fisica_id and pessoa_id and generating all the code with bake (cake bake all pessoas, for example) resolved the problem (and generated the associations automatically).</p>

ContentLicense: CC BY-SA 4.0

Body:
Been trying to save data into other table when saving Fisica entity to the Database, since I am new to cakephp it seems impossible right now, have seen multiple posts, videos, documentations and none seems to work. Please somebody help me figure out what is wrong with that.

I found a huge mistake in my relations between the entitys, now it works like that:
Fisica belongsto Pessoa

associations at FisicasTable.php

$this->belongsTo('Pessoa')
        ->setForeignKey('id_pessoa')
        ->setJoinType('INNER')
        ->setClassName('Pessoas');

Fisicas Controller

$fisica = $this->Fisicas->newEntity();
    if ($this->request->is('post')) {
        $fisica = $this->Fisicas->patchEntity($fisica, $this->request->getData(),['associated' => 'Pessoa']);
        if ($this->Fisicas->save($fisica))...

Fisica add.ctp

<legend><?= __('Add Fisica') ?></legend>
    <?php
        echo $this->Form->control('nr_cpf');
        echo $this->Form->control('dt_nascimento');
    ?>
    <legend><?= __('Add Pessoa') ?></legend>
    <?php
        echo $this->Form->control('pessoa.vr_nome');
        echo $this->Form->control('pessoa.nr_telefone');
        echo $this->Form->control('pessoa.vr_email');
    ?>

I am getting the following error:
error

I expected this code to insert in the two tables when submitting a new register to Fisica add.ctp.


问:
Why use Facade pattern for EJB session bean
I want to ask what is the reason to use Facade Pattern when access EJB Session Bean. In my Netbeans 6.9.1, if I do New > Sessions Bean for Entity Classes, and let say that I select User entity, then Netbeans would generate this code

```<code>AbstractFacade.java
public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public T edit(T entity) {
        return getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        ...
    }

    public int count() {
        ...
    }
</code>```

AND

```<code>UserFacade.java

package com.bridgeye.ejb;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class UserFacade extends AbstractFacade<User> {
    @PersistenceContext(unitName = "Bridgeye2-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }
}
</code>```

I want to ask what is the benefit of this. If I have 10 entities, then Netbeans would generated 10 Facade classes plus the AbstractFacade. This seems to be overkill to me. Let say somewhere inside my managed bean, i have to persist a User and School then I have do this

```<code>someManagedBean.java

...
@EJB
private UserFacade userEJB;

@EJB
private SchoolFacade schoolEJB;

...

public void someMethod(User user, School school){
    ...
    userEJB.create(user);
    schoolEJB.create(school);
}
</code>```

Is this the right things to do?

答:
Yes and no. The Facade pattern makes a lot of sense, but having a separate facace per domain object makes no sense.

You will want to group facades per groups of functionality of domain objects. Imagine a billing system. It has bills, items, customer, addresses. So you would there perhaps a Facade for bill handling (adding items, setting customer, printing, marking as paid) and a different facade for creation and update of users, associating with addresses and so on.

ContentLicense: CC BY-SA 3.0

Body:
I want to ask what is the reason to use Facade Pattern when access EJB Session Bean. In my Netbeans 6.9.1, if I do New > Sessions Bean for Entity Classes, and let say that I select User entity, then Netbeans would generate this code

AbstractFacade.java
public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public T edit(T entity) {
        return getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        ...
    }

    public int count() {
        ...
    }

AND

UserFacade.java

package com.bridgeye.ejb;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class UserFacade extends AbstractFacade<User> {
    @PersistenceContext(unitName = "Bridgeye2-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }
}

I want to ask what is the benefit of this. If I have 10 entities, then Netbeans would generated 10 Facade classes plus the AbstractFacade. This seems to be overkill to me. Let say somewhere inside my managed bean, i have to persist a User and School then I have do this

someManagedBean.java

...
@EJB
private UserFacade userEJB;

@EJB
private SchoolFacade schoolEJB;

...

public void someMethod(User user, School school){
    ...
    userEJB.create(user);
    schoolEJB.create(school);
}

Is this the right things to do?


问:
Moving an object with a file descriptor
I have a class, say Foo, defined like this:

class Foo {
public:
  Foo(int i) {
    valid = false;
    char devname[] = "/dev/device0";
    sprintf(devname, "/dev/device%d", i);
    fd = open(devname, O_RDWR);
    if (fd > 0) {
      valid = true;
    }

  ~Foo() {
    if (valid) {
      close(fd);
    }
  }

  bool valid;
private:
  int fd;
};
```

<p>I have another class, say <code>Bar</code>, defined like this:</p>

<pre class="lang-cpp prettyprint-override"><code>class Bar {
public:
  Bar() {
    for (int i = 0; i < 4; i++) {
      Foo foo(i);
      if (foo.valid) {
        vector_of_foos.push_back(foo);
      }
    }
  }

  std::vector<Foo> vector_of_foos;
};
</code>```

The problem with this is that push_back makes a copy of the Foo object, which copies the fd property. Then the destructor for the original Foo object is called, which closes the file that fd points to, rendering fd invalid.

Unfortunately I cannot use emplace_back since I need to instantiate my Foo object before adding it to the vector_of_foos vector so that I can check the valid property.

I have also tried using std::move but this still calls the destructor for the original Foo object once it goes out of scope which closes the file.

What is the recommended way of managing a resource like this? Should I use an array of smart pointers? Should my vector_of_foos be instead a std::vector<Foo *> where I maintain a vector of pointers to Foo which I allocate dynamically?

答:
n.m beat me to the punch, but you need to define a move constructor that 'forgets' about your file descriptor in the moved-from object.  Something like:

```<code>Foo (Foo &&move_from)
{
    valid = move_from.valid;
    fd = move_from.fd;
    move_from.valid = false;
}
</code>```

Also, delete your copy constructor and copy assignment operator and implement a move-assignment operator.  You then have an object that can be moved but not copied, rather like std::unique_ptr.

Title: Moving an object with a file descriptor

Body:
I have a class, say Foo, defined like this:

class Foo {
public:
  Foo(int i) {
    valid = false;
    char devname[] = "/dev/device0";
    sprintf(devname, "/dev/device%d", i);
    fd = open(devname, O_RDWR);
    if (fd > 0) {
      valid = true;
    }

  ~Foo() {
    if (valid) {
      close(fd);
    }
  }

  bool valid;
private:
  int fd;
};

I have another class, say Bar, defined like this:

class Bar {
public:
  Bar() {
    for (int i = 0; i < 4; i++) {
      Foo foo(i);
      if (foo.valid) {
        vector_of_foos.push_back(foo);
      }
    }
  }

  std::vector<Foo> vector_of_foos;
};

The problem with this is that push_back makes a copy of the Foo object, which copies the fd property. Then the destructor for the original Foo object is called, which closes the file that fd points to, rendering fd invalid.

Unfortunately I cannot use emplace_back since I need to instantiate my Foo object before adding it to the vector_of_foos vector so that I can check the valid property.

I have also tried using std::move but this still calls the destructor for the original Foo object once it goes out of scope which closes the file.

What is the recommended way of managing a resource like this? Should I use an array of smart pointers? Should my vector_of_foos be instead a std::vector<Foo *> where I maintain a vector of pointers to Foo which I allocate dynamically?

Body:
n.m beat me to the punch, but you need to define a move constructor that 'forgets' about your file descriptor in the moved-from object.  Something like:

Foo (Foo &&move_from)
{
    valid = move_from.valid;
    fd = move_from.fd;
    move_from.valid = false;
}

Also, delete your copy constructor and copy assignment operator and implement a move-assignment operator.  You then have an object that can be moved but not copied, rather like std::unique_ptr.


问:
terraform import rds issue
I am terraform newbie. I've created RDS manually in AWS.

Now I tried to import RDS into terraform using https://www.terraform.io/docs/providers/aws/r/db_instance.html so that I can use terraform to update RDS. The database name is mydb. I have ran terraform init but got this error, still not sure how to resolve it. Please advise. thx

```<code>terraform import aws_db_instance mydb
Error: invalid resource address "aws_db_instance"

For information on valid syntax, see:
https://www.terraform.io/docs/internals/resource-addressing.html
</code>```

答: you need to create the resource block in your terraform project before you can import the existing resource.</p>

Title: terraform import rds issue

Body:
I am terraform newbie. I've created RDS manually in AWS.

Now I tried to import RDS into terraform using https://www.terraform.io/docs/providers/aws/r/db_instance.html so that I can use terraform to update RDS. The database name is mydb. I have ran terraform init but got this error, still not sure how to resolve it. Please advise. thx

terraform import aws_db_instance mydb
Error: invalid resource address "aws_db_instance"

For information on valid syntax, see:
https://www.terraform.io/docs/internals/resource-addressing.html


问:
Reference previous row in a data.frame
I have a very simple problem. I'm am trying to set the value of column X to 0 if column Y[n,] does not equal column Y[n-1,]. My issue is that I do not know how to reference a previous row value in R, and then use that value to set the value of another column.

As an example:

```<code>Y X
1 5
1 1
2 0
2 2
</code>```

X[3,2] is 0 because Y[3,1] does not equal Y[2,1].

I need to basically find all instance of this in a large data-set and set the corresponding X value to 0.

data$X <- 0 if data$Y[n] =! data$Y[n-1]

Is there a simple solution to this in R? It really feels as though there should be.

Thank you

答:
Similarly to the post from @markus, with dplyr you can do:

```<code>df %>%
 mutate(X = (Y == lag(Y, default = first(Y))) * X)

  Y X
1 1 5
2 1 1
3 2 0
4 2 2
</code>```

Title: Reference previous row in a data.frame

Body:
I have a very simple problem. I'm am trying to set the value of column X to 0 if column Y[n,] does not equal column Y[n-1,]. My issue is that I do not know how to reference a previous row value in R, and then use that value to set the value of another column.

As an example:

Y X
1 5
1 1
2 0
2 2

X[3,2] is 0 because Y[3,1] does not equal Y[2,1].

I need to basically find all instance of this in a large data-set and set the corresponding X value to 0.

data$X <- 0 if data$Y[n] =! data$Y[n-1]

Is there a simple solution to this in R? It really feels as though there should be.

Thank you

Body:
Similarly to the post from @markus, with dplyr you can do:

df %>%
 mutate(X = (Y == lag(Y, default = first(Y))) * X)

  Y X
1 1 5
2 1 1
3 2 0
4 2 2


答:
You probably want to delete copy constructors altogether (or provide some logic to have two valid instances with different descriptors). If you delete them, compiler will make sure you use move semantics always.

Then, you can declare move constructors, that will perform valid moving:

```<code>class Foo {
public:
  Foo(int i) {
    valid = false;
    char devname[] = "/dev/device0";
    sprintf(devname, "/dev/device%d", i);
    fd = open(devname, O_RDWR);
    if (fd > 0) {
      valid = true;
    }

  ~Foo() {
    if (valid) {
      close(fd);
    }
  }

  Foo(const Foo&) = delete;
  Foo& operator=(const Foo&) = delete;
  Foo(Foo&& other) {
    valid = other.valid;
    fd = other.fd;
    other.valid = false;
  };
  Foo& operator=(Foo&& other) {
    valid = other.valid;
    fd = other.fd;
    other.valid = false;
  };

  bool valid;
private:
  int fd;
};
</code>```

A bit of explanation:

You violated the Rule of Three/Five/Zero. In short, it says "whenever your class needs a user defined destructor/copy constructor/move constructor, it will most likely the rest of them". Your class does require a destructor, which you provided, but you didn't provide neither copy or move operators, which is a mistake. You have to provide both copy constructor/copy assignment operator (here deleted) and move constructor/move assignment operator.

As to why: compiler is not smart enough to guess what do you need. Ignoring the fact that your class doesn't support move semantics (user-defined destructor prevents implicit creation of move constructors), implicit move constructor is very, very simple. It just calls std::move on every class member. And std::move for primitive types is also very simple - it just copies that variable, as it's the fastest operation.

It could possibly zero the other variable, but that's not necessary. As per definition, the variable must be left in "unknown, but valid state". No change to that variable fits this definition.

Title: Moving an object with a file descriptor

Body:
You probably want to delete copy constructors altogether (or provide some logic to have two valid instances with different descriptors). If you delete them, compiler will make sure you use move semantics always.

Then, you can declare move constructors, that will perform valid moving:

class Foo {
public:
  Foo(int i) {
    valid = false;
    char devname[] = "/dev/device0";
    sprintf(devname, "/dev/device%d", i);
    fd = open(devname, O_RDWR);
    if (fd > 0) {
      valid = true;
    }

  ~Foo() {
    if (valid) {
      close(fd);
    }
  }

  Foo(const Foo&) = delete;
  Foo& operator=(const Foo&) = delete;
  Foo(Foo&& other) {
    valid = other.valid;
    fd = other.fd;
    other.valid = false;
  };
  Foo& operator=(Foo&& other) {
    valid = other.valid;
    fd = other.fd;
    other.valid = false;
  };

  bool valid;
private:
  int fd;
};

A bit of explanation:

You violated the Rule of Three/Five/Zero. In short, it says "whenever your class needs a user defined destructor/copy constructor/move constructor, it will most likely the rest of them". Your class does require a destructor, which you provided, but you didn't provide neither copy or move operators, which is a mistake. You have to provide both copy constructor/copy assignment operator (here deleted) and move constructor/move assignment operator.

As to why: compiler is not smart enough to guess what do you need. Ignoring the fact that your class doesn't support move semantics (user-defined destructor prevents implicit creation of move constructors), implicit move constructor is very, very simple. It just calls std::move on every class member. And std::move for primitive types is also very simple - it just copies that variable, as it's the fastest operation.

It could possibly zero the other variable, but that's not necessary. As per definition, the variable must be left in "unknown, but valid state". No change to that variable fits this definition.


问:
Docusign API request for processing already processed docusign doc
We have some documents which has DocuSign Envelope ID on top of documents. So is there any API present which help us to extract the values like 'date of sign', 'who signed it' etc. from the documents.

(Note - These documents are processed by others we have only there documents.)

Any help would be appreciated.

答: No. The DocuSign API only allows you to pull data from envelopes you already have access to. In this case, I would recommend reaching out to a party on the envelope to request they provide the Certificate of Completion. </p>


问:
using subprocess.run the program doesn't work, but copying the text from the run([xxx]) does work. any suggestions
I have written a short bit of code to run a program (cutadapt) on multiple files. however it gives the following error for each of the files it tries to run: "cutadapt: error: unrecognized arguments".
Run on MacOS, python 3.7.3,

If I print the statement in the same program, copy that as a single call in the terminal, then it does work. Does anyone see what I am doing wrong?

import glob

import subprocess

fastq_folder = "/path/2019.01_spades_output_pathodetect/FASTQ_trimming"

listoffiles = glob.glob(fastq_folder + "/*.gz")

for fastq in listoffiles:
    input_file = fastq
    output_file = fastq.replace("_001.fastq.gz", "_001CUT20.fastq.gz")
    output_file = fastq.replace("2019.01_spades_output_pathodetect/FASTQ_trimming/", "2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/")
    print("cutadapt", "--cut 20", "-o", output_file, input_file)
    subprocess.run(["cutadapt", "--cut 20", "-o", output_file, input_file])
```

<p><strong>so the output in the terminal is:</strong></p>

```cutadapt --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
Run "cutadapt --help" to see command-line options.
See https://cutadapt.readthedocs.io/ for full documentation.

cutadapt: error: unrecognized arguments: /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
```

<p><strong>Then, when I copy the printed statement, it works:</strong></p>

```cutadapt --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz

This is cutadapt 2.3 with Python 3.7.3
Command line parameters: --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
Processing reads on 1 core in single-end mode ...
[   8<-------] 00:00:06       490,635 reads  @     13.6 µs/read;   4.42 M reads/minute
Finished in 6.71 s (14 us/read; 4.39 M reads/minute).
```

答:
Your code passes --cut 20 to cutadapt as a single argument, which it apparently can't handle.  (From cutadapt's argument parser's point of view, it probably thinks you're trying to specify an option named "cut 20", which doesn't exist.)  You need to split the argument in two:

```<code>subprocess.run(["cutadapt", "--cut", "20", "-o", output_file, input_file])
</code>```

Body:
I have written a short bit of code to run a program (cutadapt) on multiple files. however it gives the following error for each of the files it tries to run: "cutadapt: error: unrecognized arguments".
Run on MacOS, python 3.7.3,

If I print the statement in the same program, copy that as a single call in the terminal, then it does work. Does anyone see what I am doing wrong?

import glob

import subprocess

fastq_folder = "/path/2019.01_spades_output_pathodetect/FASTQ_trimming"

listoffiles = glob.glob(fastq_folder + "/*.gz")

for fastq in listoffiles:
    input_file = fastq
    output_file = fastq.replace("_001.fastq.gz", "_001CUT20.fastq.gz")
    output_file = fastq.replace("2019.01_spades_output_pathodetect/FASTQ_trimming/", "2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/")
    print("cutadapt", "--cut 20", "-o", output_file, input_file)
    subprocess.run(["cutadapt", "--cut 20", "-o", output_file, input_file])

so the output in the terminal is:

cutadapt --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
Run "cutadapt --help" to see command-line options.
See https://cutadapt.readthedocs.io/ for full documentation.

cutadapt: error: unrecognized arguments: /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz

Then, when I copy the printed statement, it works:

cutadapt --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz

This is cutadapt 2.3 with Python 3.7.3
Command line parameters: --cut 20 -o /path/2019.01_spades_output_pathodetect/FASTQ_trimming/CUT20/AWGS09281_S20_L001_R2_001.fastq.gz /path/2019.01_spades_output_pathodetect/FASTQ_trimming/AWGS09281_S20_L001_R2_001.fastq.gz
Processing reads on 1 core in single-end mode ...
[   8<-------] 00:00:06       490,635 reads  @     13.6 µs/read;   4.42 M reads/minute
Finished in 6.71 s (14 us/read; 4.39 M reads/minute).

Body:
Your code passes --cut 20 to cutadapt as a single argument, which it apparently can't handle.  (From cutadapt's argument parser's point of view, it probably thinks you're trying to specify an option named "cut 20", which doesn't exist.)  You need to split the argument in two:

subprocess.run(["cutadapt", "--cut", "20", "-o", output_file, input_file])


问:
Force Perforce to accept workspace view as valid
I have a number of files checked out with changes ready to submit.

I realised that my client spec was hardcoding my alternate root, so I removed the alternate root from all lines in the client spec, and specified it in the alternate root box instead.

I also had some files not checked out that I wasn't ready to add to changelists so I renamed the directory structure underneath and then synced all branches I needed and then renamed the directory to AltBranch and renamed the old one back.

Now however all the checked out files are listed as "not mapped to workspace view" - they are still there however.

I wanted to force perforce to agree with my version, so I tried p4 sync -k, however I get the error

```<code>//.../X.cpp#10 - is opened for edit and can't be deleted
</code>```

I then tried p4 sync -k -f, but I get the error

```<code>//.../X.cpp#10 - refreshing C:\Work\...\X.cpp
//.../X.cpp#10 - is opened for edit and can't be deleted
</code>```

On the whole I really like Perforce, however its insistence in always knowing best is frustrating

答:
I have managed to produce a batch file that contains a sequence of Perforce commands to achieve what I want.

This solution is Windows/DOS specific - although I would imagine other command shells could do the parsing needed for this fix:

```<code> @ echo off
 echo Please Exit Perforce
 pause
 setlocal
 rem Retrieve depot spec format of file
 for /f "delims=# " %%d in ('p4 files %1') do set p4name=%%d
 rem Retrieve current pending changelist
 for /f "tokens=5 delims= " %%d in ('p4 opened %p4name%') do set change=%%d
 p4 revert -k %p4name%
 p4 sync -k %p4name%
 p4 edit -c %change% %1
</code>```

This version is specific to files, although a directory version would be possible substituting files for dirs

Also stupidly the Command Prompt does not set ERRORLEVEL if the command in the ticks fails.

ContentLicense: CC BY-SA 2.5

Body:
I have a number of files checked out with changes ready to submit.

I realised that my client spec was hardcoding my alternate root, so I removed the alternate root from all lines in the client spec, and specified it in the alternate root box instead.

I also had some files not checked out that I wasn't ready to add to changelists so I renamed the directory structure underneath and then synced all branches I needed and then renamed the directory to AltBranch and renamed the old one back.

Now however all the checked out files are listed as "not mapped to workspace view" - they are still there however.

I wanted to force perforce to agree with my version, so I tried p4 sync -k, however I get the error

//.../X.cpp#10 - is opened for edit and can't be deleted

I then tried p4 sync -k -f, but I get the error

//.../X.cpp#10 - refreshing C:\Work\...\X.cpp
//.../X.cpp#10 - is opened for edit and can't be deleted

On the whole I really like Perforce, however its insistence in always knowing best is frustrating

Body:
I have managed to produce a batch file that contains a sequence of Perforce commands to achieve what I want.

This solution is Windows/DOS specific - although I would imagine other command shells could do the parsing needed for this fix:

 @ echo off
 echo Please Exit Perforce
 pause
 setlocal
 rem Retrieve depot spec format of file
 for /f "delims=# " %%d in ('p4 files %1') do set p4name=%%d
 rem Retrieve current pending changelist
 for /f "tokens=5 delims= " %%d in ('p4 opened %p4name%') do set change=%%d
 p4 revert -k %p4name%
 p4 sync -k %p4name%
 p4 edit -c %change% %1

This version is specific to files, although a directory version would be possible substituting files for dirs

Also stupidly the Command Prompt does not set ERRORLEVEL if the command in the ticks fails.


问:
Template specialization and inheritance template class from other template class
I have some questions about next code:

template<typename T>
class Base;

template<typename T, typename P>
class Base<T(P)> {

};

template<typename T>
class Derived;

template<typename T, typename P>
class Derived<T(P)> : public Base<T(P)> {

};
```

Class specialization Derived<T(P)> inherits from class template<typename T> class Base or  from class template<typename T, typename P> class Base<T(P)>?

What the name of when I'm binding template parameters T and P of class specialization Derived<T(P)> with template parameter T of class Base.

答:
Class specialization Derived<T(P)> inherits from class template<typename T> class Base or from class template<typename T, typename P> class Base<T(P)>?

Technically, neither. A class or class template never inherits from a template, only from one specific base class type. That is, Derived<int(float&)> inherits Base<int(float&)>, and so on. That base class gets instantiated from whatever is the most specialized declaration associated with Base for those specific types. The importance of this distinction comes up if there are additional partial specializations or explicit specializations.

If I change your example a bit,

```<code>template<typename T> // #1
class Base;

template<typename T, typename P> // #2
class Base<T(P)> {
public:
    static const int mem1 = 1;
};

template<typename T>
class Derived;

template<typename T, typename P>
class Derived<T(P)> : public Base<T(P)> {
};

class SomethingElse {};

template<typename P> // #3
class Base<SomethingElse(const P&)> {
public:
    static const long long mem2 = 2;
};

using ThingType = Derived<SomethingElse(const std::string&)>;
const auto A = ThingType::mem1; // Error!
const auto B = ThingType::mem2; // OK
</code>```

It's not correct to say that partial specialization Derived<T(P)> inherits partial specialization Base<T(P)>, since the example type Derived<SomethingElse(const std::string&)> uses that Derived partial specialization, but doesn't use that Base partial specialization at all.  Base<T(P)> just means the template called Base, with whatever specialization definition for Base best matches the template argument T(P).  The decision about what the base class Base<T(P)> means is made independently for each specific set of template arguments when each specialization of Derived is instantiated.

What the name of when I'm binding template parameters T and P of class specialization Derived<T(P)> with template parameter T of class Base.

I don't know of any term for this, other than that you are using a dependent compound type.  (Dependent = depends on one or more template parameters; Compound = the type T(P) involves the other types T and P.)  This also makes Base<T(P)> a dependent base class in the definition of Derived<T(P)>, meaning the compiler will not look there for plain identifiers, and you need to use this->name or Base::name to make such names valid.  It's also important that the template parameters are in "deducible contexts" within the specialization's template arguments.

Body:
I have some questions about next code:

template<typename T>
class Base;

template<typename T, typename P>
class Base<T(P)> {

};

template<typename T>
class Derived;

template<typename T, typename P>
class Derived<T(P)> : public Base<T(P)> {

};

Class specialization Derived<T(P)> inherits from class template<typename T> class Base or  from class template<typename T, typename P> class Base<T(P)>?

What the name of when I'm binding template parameters T and P of class specialization Derived<T(P)> with template parameter T of class Base.

Body:
Class specialization Derived<T(P)> inherits from class template<typename T> class Base or from class template<typename T, typename P> class Base<T(P)>?

Technically, neither. A class or class template never inherits from a template, only from one specific base class type. That is, Derived<int(float&)> inherits Base<int(float&)>, and so on. That base class gets instantiated from whatever is the most specialized declaration associated with Base for those specific types. The importance of this distinction comes up if there are additional partial specializations or explicit specializations.

If I change your example a bit,

template<typename T> // #1
class Base;

template<typename T, typename P> // #2
class Base<T(P)> {
public:
    static const int mem1 = 1;
};

template<typename T>
class Derived;

template<typename T, typename P>
class Derived<T(P)> : public Base<T(P)> {
};

class SomethingElse {};

template<typename P> // #3
class Base<SomethingElse(const P&)> {
public:
    static const long long mem2 = 2;
};

using ThingType = Derived<SomethingElse(const std::string&)>;
const auto A = ThingType::mem1; // Error!
const auto B = ThingType::mem2; // OK

It's not correct to say that partial specialization Derived<T(P)> inherits partial specialization Base<T(P)>, since the example type Derived<SomethingElse(const std::string&)> uses that Derived partial specialization, but doesn't use that Base partial specialization at all.  Base<T(P)> just means the template called Base, with whatever specialization definition for Base best matches the template argument T(P).  The decision about what the base class Base<T(P)> means is made independently for each specific set of template arguments when each specialization of Derived is instantiated.

What the name of when I'm binding template parameters T and P of class specialization Derived<T(P)> with template parameter T of class Base.

I don't know of any term for this, other than that you are using a dependent compound type.  (Dependent = depends on one or more template parameters; Compound = the type T(P) involves the other types T and P.)  This also makes Base<T(P)> a dependent base class in the definition of Derived<T(P)>, meaning the compiler will not look there for plain identifiers, and you need to use this->name or Base::name to make such names valid.  It's also important that the template parameters are in "deducible contexts" within the specialization's template arguments.


问:
Use cases of the Workflow Engine
I'd like to know about specific problems you - the SO reader - have solved using Workflow Engines and what libraries/frameworks you used if you didn't roll your own.  I'd also like to know when a Workflow Engine wasn't the best choice and if/how you chose something simpler, like a TaskList/WorkList/Task-Management type application using state machines.

Questions:

What problems have you used workflow engines to solve?

What libraries/frameworks did you use?

When did a simpler State Machine/Task Management like system suffice?

Bonus: How did/do you make the distinction between Task Management and Workflow Engine?

I'm looking for first-hand experiences.

Some of the resources I've checked out:

Ruote and State Machine != Workflow Engine

StonePath and Docs

Creating and Managing Worklist Task Plans with Oracle

Design and Implementation of a Workflow Engine - Thesis

What to use Windows Workflow Foundation For

JBoss jBPM Docs

答:
I am one of the authors of Imixs-Workflow. Imixs-Workflow is an open source workflow engine based on BPMN 2.0 and fully integrated into the Java EE technology stack.

I develop workflow engines by myself since more than 10 years. I will try to answer your question in short:

> What problems have you used workflow engines to solve?

My personal goal when I started to think about workflow engines was to avoid hard codding the business logic within my application. Many things in a business application can be reused so it makes sense to keep them configurable. For example:

sending out a notification

view open tasks

assigned a task to a person

describing the current task

From this function list you can see I am talking about human-centric workflows. In short: A human-centric workflow engine answers the questions: Who is responsible for a task and who needs to be informed next? And these are the typical questions in business requirements.

>What libraries/frameworks did you use?

5 years ago we started reimplementing Imixs-Workflow engine focusing on BPMN 2.0. BPMN is the common standard for process modeling. And the surprising thing for me was that we were suddenly able to describe even highly complex business processes that could be visualized and executed. I recommend everyone to use BPMN for modeling business processes.

> When did a simpler State Machine/Task Management like system suffice?

A simple state machine is sufficient if you just want to track the status of a business object. This is the case when you begin to introduce the 'status' attribute into your object model. But in case you need business processes with responsibilities, logging and flow control, then a state machine is no longer sufficient.

> Bonus: How did/do you make the distinction between Task Management and Workflow Engine?

This is exactly the point where many workflow engines mentioned here differ. For a human-centric workflow you typically need a task management to distribute tasks between human actors. For a process automation, this point is not so relevant. It is sufficient if the engine performs certain tasks. Task management and workflow engines can not be compared because task management is always a function of a workflow engine.

Title: Use cases of the Workflow Engine


问:
IF statement using cell formatted value
In Google Sheets, how can you use the IF statement using the output of a cell's formatted value?

I've created a Google Sheet with a date value in B1. The cell is formatted using the date format. B1 is then copied across to the right so that it increments the days of the month.

In B2, based on the B1 date, I want to display the day value (ie Thu, Fri, Sat etc.). Similarly to the first step, I set the date format under Format > Number > More formats > More date and time formats, then from the select box, choose the day and I want to display the "Tue" date format.

Then in B8, I want to display an amount of 30 every Thursday, otherwise, show 0.

This is where it doesn't work. Does it seem like the rendered cell's value can't be used in an IF statement? My desired output is that every the value in row 2 is a 'Thu' display 30.

As a side note, I jumped on Google support and asked this same question. Even though they are technical support, I thought I'd give them a try anyway, after all, I am paying for GSuite.

This is the formula they came back to me with: =if(B2=B1, "30", "0").

Of course, this formula will work in B8, because B2 is equal to B1 in the actual cell value, it doesn't take into account the formatted cell value. This formula will fail the output we need as it will always display 30 instead of only then row 2 is 'Thu'.

So essentially, is there a function in Google Sheets for a rendered cell value?  Or another solution around this?

Note: I do NOT want to use any scripting to get this to work.

答:
Please try and copy across to suit:

```<code>=30*(WEEKDAY(B1)=5)
</code>```

No IF, but shorter.

Title: IF statement using cell formatted value

Body:
Please try and copy across to suit:

=30*(WEEKDAY(B1)=5)

No IF, but shorter.


问:
Enable CORS in Azure Maps Account with Angular 7
I am using now Azure Maps Account with Angular 7 and try to create an Autocomplete input.

I am calling the URL:

```<code>this.http.get('https://atlas.microsoft.com/search/address/json?subscription-key=<key>&api-version=1.0&query=Newyork').subscribe(...)
</code>```

When I run this link in postman, it works perfectly and responses with the data that I want. But when I call in in Angular using HttpClient, I am getting a CORS problem.

I cannot find a place where to change the cors in the service.
Does anybody know how to fix it?

Besides, if someone copied this URL and used it in somewhere else, he will use the service but on my cost. How can I secure it with specific Urls?

答: Azure Maps has now added CORS policy which is less restrictive. All response headers should now contain the necessary  'Access-Control-Allow-Origin': '*'. Also followed up on this thread here.

Body:
I am using now Azure Maps Account with Angular 7 and try to create an Autocomplete input.

I am calling the URL:

this.http.get('https://atlas.microsoft.com/search/address/json?subscription-key=<key>&api-version=1.0&query=Newyork').subscribe(...)

When I run this link in postman, it works perfectly and responses with the data that I want. But when I call in in Angular using HttpClient, I am getting a CORS problem.

I cannot find a place where to change the cors in the service.
Does anybody know how to fix it?

Besides, if someone copied this URL and used it in somewhere else, he will use the service but on my cost. How can I secure it with specific Urls?


问:
Using wildcards with "convert". Or "convert"ing a group of files
I regularly scan in my Homework for class. My scanner exports raw jpg files to usb, and from there I can use gimp to edit and save the files as a pdf. One time saver I've found is to export my multi-page homeworks as a .mng file and then use the convert function to turn it into a pdf. I do it this way because Gimp automatically merges all layers when exporting to a pdf.

```<code>convert HW.mng HW.pdf
</code>```

this works well for individual files, but at the end of every week I can have dozens of files to convert.

I have tried using wildcards in the filenames for convert:

```<code>convert *.mng *.pdf
</code>```

This always runs successfully and never throws an error, but never produces any pdfs.

Both

```<code>convert HW*.mng HW*.pdf
</code>```

and

```<code>convert "HW*.mng" "HW*.pdf"
</code>```

yeild the error

```<code>convert: unable to open image `HW*.pdf': Invalid argument @ error/blob.c/OpenBlob/2712.
</code>```

which I think means the error lies in exporting with a wildcard.

Is there any way to convert all of a specific file type to another using convert? Or should I try using a different program?

答:
You can see this StackExchange post. The accepted answer basically does what you want.

for file in *.mng; do convert -input "$file" -output "${file/%mng/pdf}"; done

Body:
I regularly scan in my Homework for class. My scanner exports raw jpg files to usb, and from there I can use gimp to edit and save the files as a pdf. One time saver I've found is to export my multi-page homeworks as a .mng file and then use the convert function to turn it into a pdf. I do it this way because Gimp automatically merges all layers when exporting to a pdf.

convert HW.mng HW.pdf

this works well for individual files, but at the end of every week I can have dozens of files to convert.

I have tried using wildcards in the filenames for convert:

convert *.mng *.pdf

This always runs successfully and never throws an error, but never produces any pdfs.

Both

convert HW*.mng HW*.pdf

and

convert "HW*.mng" "HW*.pdf"

yeild the error

convert: unable to open image `HW*.pdf': Invalid argument @ error/blob.c/OpenBlob/2712.

which I think means the error lies in exporting with a wildcard.

Is there any way to convert all of a specific file type to another using convert? Or should I try using a different program?


Title: Keep date and time format consistent

Body:
I have some dates and times that for some reason switch between formats at the turn of a new month. I would like to convert them to be consistently Day, Month, Year (19 rather than 2019) and 24 hr clock with seconds. I have managed to switch half using strptime but does not work for entire dataset.

Here is an example:

datetime <- c("02/28/19 11:39:00 PM", "02/28/19 11:40:00 PM", "02/28/19 11:41:00 PM",
"02/28/19 11:42:00 PM", "02/28/19 11:43:00 PM", "02/28/19 11:44:00 PM",
"02/28/19 11:45:00 PM", "02/28/19 11:46:00 PM", "02/28/19 11:47:00 PM",
"02/28/19 11:48:00 PM", "02/28/19 11:49:00 PM", "02/28/19 11:50:00 PM",
"02/28/19 11:51:00 PM", "02/28/19 11:52:00 PM", "02/28/19 11:53:00 PM",
"02/28/19 11:54:00 PM", "02/28/19 11:55:00 PM", "02/28/19 11:56:00 PM",
"02/28/19 11:57:00 PM", "02/28/19 11:58:00 PM", "02/28/19 11:59:00 PM",
"03/01/2019 00:00", "03/01/2019 00:01", "03/01/2019 00:02", "03/01/2019 00:03",
"03/01/2019 00:04", "03/01/2019 00:05", "03/01/2019 00:06", "03/01/2019 00:07",
"03/01/2019 00:08", "03/01/2019 00:09", "03/01/2019 00:10", "03/01/2019 00:11",
"03/01/2019 00:12", "03/01/2019 00:13", "03/01/2019 00:14", "03/01/2019 00:15",
"03/01/2019 00:16", "03/01/2019 00:17", "03/01/2019 00:18", "03/01/2019 00:19",
"03/01/2019 00:20", "03/01/2019 00:21", "03/01/2019 00:22", "03/01/2019 00:23",
"03/01/2019 00:24", "03/01/2019 00:25", "03/01/2019 00:26", "03/01/2019 00:27",
"03/01/2019 00:28", "03/01/2019 00:29")

Body:
One possible approach is

lubridate::mdy_hms(datetime, truncated = 1L)

which returns

 [1] "2019-02-28 23:39:00 UTC" "2019-02-28 23:40:00 UTC" "2019-02-28 23:41:00 UTC" "2019-02-28 23:42:00 UTC"
 [5] "2019-02-28 23:43:00 UTC" "2019-02-28 23:44:00 UTC" "2019-02-28 23:45:00 UTC" "2019-02-28 23:46:00 UTC"
 [9] "2019-02-28 23:47:00 UTC" "2019-02-28 23:48:00 UTC" "2019-02-28 23:49:00 UTC" "2019-02-28 23:50:00 UTC"
[13] "2019-02-28 23:51:00 UTC" "2019-02-28 23:52:00 UTC" "2019-02-28 23:53:00 UTC" "2019-02-28 23:54:00 UTC"
[17] "2019-02-28 23:55:00 UTC" "2019-02-28 23:56:00 UTC" "2019-02-28 23:57:00 UTC" "2019-02-28 23:58:00 UTC"
[21] "2019-02-28 23:59:00 UTC" "2019-03-01 00:00:00 UTC" "2019-03-01 00:01:00 UTC" "2019-03-01 00:02:00 UTC"
[25] "2019-03-01 00:03:00 UTC" "2019-03-01 00:04:00 UTC" "2019-03-01 00:05:00 UTC" "2019-03-01 00:06:00 UTC"
[29] "2019-03-01 00:07:00 UTC" "2019-03-01 00:08:00 UTC" "2019-03-01 00:09:00 UTC" "2019-03-01 00:10:00 UTC"
[33] "2019-03-01 00:11:00 UTC" "2019-03-01 00:12:00 UTC" "2019-03-01 00:13:00 UTC" "2019-03-01 00:14:00 UTC"
[37] "2019-03-01 00:15:00 UTC" "2019-03-01 00:16:00 UTC" "2019-03-01 00:17:00 UTC" "2019-03-01 00:18:00 UTC"
[41] "2019-03-01 00:19:00 UTC" "2019-03-01 00:20:00 UTC" "2019-03-01 00:21:00 UTC" "2019-03-01 00:22:00 UTC"
[45] "2019-03-01 00:23:00 UTC" "2019-03-01 00:24:00 UTC" "2019-03-01 00:25:00 UTC" "2019-03-01 00:26:00 UTC"
[49] "2019-03-01 00:27:00 UTC" "2019-03-01 00:28:00 UTC" "2019-03-01 00:29:00 UTC"

for the given sample dataset.


问:
How to correctly create push buttons on winApi as well as Handle its messages
So my program works, all apart from one thing, I would like for my button, 'pushBtn' , aka BTN_PUSH_TALK , to send a BN_PUSHED or BN_UNPUSHED message so I can handle it accordingly.

Following steps online, as well as trial and improvement, right now the only response I ever get is once I am done holding / clicking the button.

```<code>       pushBtn = CreateWindowEx(0, L"BUTTON", L"TALK", WS_CHILD |
       WS_VISIBLE |
       BS_DEFPUSHBUTTON , 0 , 290 , 50, 50,
   hWnd,(HMENU)BTN_PUSH_TALK, GetModuleHandle(NULL), NULL);
</code>```

Handler (or at least what matters) :

```<code> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM
lParam)
{
    bool asd;
    switch (message)
    {
    case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);

        // Parse the menu selections:
        switch (wmId)
        {
        case BTN_PUSH_TALK:
            switch (HIWORD(wParam))
            {
            case BN_UNPUSHED:
                if (connected && inputChoiceStr == "Push To Talk") {
                    tplug->setDuck(false);
                }
                break;
            case BN_PUSHED:
                if (connected && inputChoiceStr == "Push To Talk") {
                    tplug->setDuck(true);
                }
                break;
            }
            break;
</code>```

I expected once i clicked and held down the button , that the BN_PUSHED case would be entered, however it is not.
On letting go, I expect the BN_UNPUSHED case to be entered, but this was not the case either.
case BTN_PUSH_TALK is reached, meaning the button is identifiable, however the switch case within this block of code is never reached.

答:
If I'm reading the question right, your goal is to get notifications when a standard push button is initially pushed by the user, whereas standard notification behavior of buttons only posts WM_COMMANDs on "clicks" where a click is the whole mouse down plus mouse up sequence.

Historically in order to get the BN_PUSHED and BN_UNPUSHED notifications in your WM_COMMAND handler you had to use the BS_NOTIFY window style when creating the button. However, if you read the documentation for BN_PUSHED or BN_UNPUSHED you will see

This notification code is provided only for compatibility with 16-bit versions of Windows earlier than version 3.0. Applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

These were very old notifications that from what I can tell are not just deprecated but no longer even supported. You can do, however, as the documentation suggests: use an owner drawn button i.e. a button created with the BS_OWNERDRAW style.

This turns out to be more difficult than just creating the button with BS_NOTIFY turned on, because the button will no longer perform default painting by itself. Given this added chore, I'd recommend not doing it this way unless you want to custom paint your buttons anyway -- unless you happen to want some nonstandard visual look-and-feel for these buttons as well as nonstandard notification behavior. Otherwise, I would probably just do Win32 subclassing as someone else suggested to trap WM_LBUTTONDOWN etc. and then call the standard button WNDPROC after doing some action on the events i cared about.

Anyway the minimal owner drawn button that reports button down and button up events is like the following. (I post the button events as custom messages but you could do whatever you wish there)

```<code>#include <windows.h>

#define BTN_ID 101

#define WM_PUSHBUTTONDOWN   WM_APP + 1
#define WM_PUSHBUTTONUP     WM_APP + 2

HINSTANCE g_instance = 0;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    g_instance = hInstance;

    MSG msg = { 0 };
    WNDCLASS wc = { 0 };
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND);
    wc.lpszClassName = L"owner_draw_btn";

    if (!RegisterClass(&wc))
        return -1;

    if (!CreateWindow(wc.lpszClassName, L"foobar",  WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 640, 480, 0, 0, hInstance, NULL))
        return -1;

    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT HandleDrawItem(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    auto* dis = reinterpret_cast<DRAWITEMSTRUCT*>(lParam);
    if (dis->CtlType != ODT_BUTTON)
        return 0;

    auto style = (dis->itemState & ODS_SELECTED) ?
        DFCS_BUTTONPUSH | DFCS_PUSHED :
        DFCS_BUTTONPUSH;

    auto rect = &dis->rcItem;
    DrawFrameControl(dis->hDC, rect, DFC_BUTTON, style);

    TCHAR text[512];
    auto n = GetWindowText(dis->hwndItem, text, 512);
    DrawText(dis->hDC, text, n, rect, DT_SINGLELINE | DT_VCENTER | DT_CENTER);

    if (dis->itemAction == ODA_SELECT) {
        PostMessage(
            hWnd,
            (dis->itemState & ODS_SELECTED) ? WM_PUSHBUTTONDOWN : WM_PUSHBUTTONUP,
            dis->CtlID,
            0
        );
    }
    return 0;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_CREATE:
            CreateWindow(
                L"button", L"foobar",
                BS_OWNERDRAW | WS_CHILD | WS_VISIBLE,
                10, 10, 150, 35, hWnd,
                (HMENU) BTN_ID,
                g_instance,
                0
            );
            return 0;

        case WM_DRAWITEM:
            return HandleDrawItem(hWnd, wParam, lParam);

        case WM_PUSHBUTTONDOWN:
            OutputDebugString(L"Button down event\n");
            break;

        case WM_PUSHBUTTONUP:
            OutputDebugString(L"Button up event\n");
            break;

        case WM_CLOSE:
            PostQuitMessage(0);
            return 0;
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
}
</code>```

Body:
So my program works, all apart from one thing, I would like for my button, 'pushBtn' , aka BTN_PUSH_TALK , to send a BN_PUSHED or BN_UNPUSHED message so I can handle it accordingly.

Following steps online, as well as trial and improvement, right now the only response I ever get is once I am done holding / clicking the button.

       pushBtn = CreateWindowEx(0, L"BUTTON", L"TALK", WS_CHILD |
       WS_VISIBLE |
       BS_DEFPUSHBUTTON , 0 , 290 , 50, 50,
   hWnd,(HMENU)BTN_PUSH_TALK, GetModuleHandle(NULL), NULL);

Handler (or at least what matters) :

 LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM
lParam)
{
    bool asd;
    switch (message)
    {
    case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);

        // Parse the menu selections:
        switch (wmId)
        {
        case BTN_PUSH_TALK:
            switch (HIWORD(wParam))
            {
            case BN_UNPUSHED:
                if (connected && inputChoiceStr == "Push To Talk") {
                    tplug->setDuck(false);
                }
                break;
            case BN_PUSHED:
                if (connected && inputChoiceStr == "Push To Talk") {
                    tplug->setDuck(true);
                }
                break;
            }
            break;

I expected once i clicked and held down the button , that the BN_PUSHED case would be entered, however it is not.
On letting go, I expect the BN_UNPUSHED case to be entered, but this was not the case either.
case BTN_PUSH_TALK is reached, meaning the button is identifiable, however the switch case within this block of code is never reached.

Body:
If I'm reading the question right, your goal is to get notifications when a standard push button is initially pushed by the user, whereas standard notification behavior of buttons only posts WM_COMMANDs on "clicks" where a click is the whole mouse down plus mouse up sequence.

Historically in order to get the BN_PUSHED and BN_UNPUSHED notifications in your WM_COMMAND handler you had to use the BS_NOTIFY window style when creating the button. However, if you read the documentation for BN_PUSHED or BN_UNPUSHED you will see

This notification code is provided only for compatibility with 16-bit versions of Windows earlier than version 3.0. Applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

These were very old notifications that from what I can tell are not just deprecated but no longer even supported. You can do, however, as the documentation suggests: use an owner drawn button i.e. a button created with the BS_OWNERDRAW style.

This turns out to be more difficult than just creating the button with BS_NOTIFY turned on, because the button will no longer perform default painting by itself. Given this added chore, I'd recommend not doing it this way unless you want to custom paint your buttons anyway -- unless you happen to want some nonstandard visual look-and-feel for these buttons as well as nonstandard notification behavior. Otherwise, I would probably just do Win32 subclassing as someone else suggested to trap WM_LBUTTONDOWN etc. and then call the standard button WNDPROC after doing some action on the events i cared about.

Anyway the minimal owner drawn button that reports button down and button up events is like the following. (I post the button events as custom messages but you could do whatever you wish there)

#include <windows.h>

#define BTN_ID 101

#define WM_PUSHBUTTONDOWN   WM_APP + 1
#define WM_PUSHBUTTONUP     WM_APP + 2

HINSTANCE g_instance = 0;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    g_instance = hInstance;

    MSG msg = { 0 };
    WNDCLASS wc = { 0 };
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND);
    wc.lpszClassName = L"owner_draw_btn";

    if (!RegisterClass(&wc))
        return -1;

    if (!CreateWindow(wc.lpszClassName, L"foobar",  WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 640, 480, 0, 0, hInstance, NULL))
        return -1;

    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT HandleDrawItem(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    auto* dis = reinterpret_cast<DRAWITEMSTRUCT*>(lParam);
    if (dis->CtlType != ODT_BUTTON)
        return 0;

    auto style = (dis->itemState & ODS_SELECTED) ?
        DFCS_BUTTONPUSH | DFCS_PUSHED :
        DFCS_BUTTONPUSH;

    auto rect = &dis->rcItem;
    DrawFrameControl(dis->hDC, rect, DFC_BUTTON, style);

    TCHAR text[512];
    auto n = GetWindowText(dis->hwndItem, text, 512);
    DrawText(dis->hDC, text, n, rect, DT_SINGLELINE | DT_VCENTER | DT_CENTER);

    if (dis->itemAction == ODA_SELECT) {
        PostMessage(
            hWnd,
            (dis->itemState & ODS_SELECTED) ? WM_PUSHBUTTONDOWN : WM_PUSHBUTTONUP,
            dis->CtlID,
            0
        );
    }
    return 0;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_CREATE:
            CreateWindow(
                L"button", L"foobar",
                BS_OWNERDRAW | WS_CHILD | WS_VISIBLE,
                10, 10, 150, 35, hWnd,
                (HMENU) BTN_ID,
                g_instance,
                0
            );
            return 0;

        case WM_DRAWITEM:
            return HandleDrawItem(hWnd, wParam, lParam);

        case WM_PUSHBUTTONDOWN:
            OutputDebugString(L"Button down event\n");
            break;

        case WM_PUSHBUTTONUP:
            OutputDebugString(L"Button up event\n");
            break;

        case WM_CLOSE:
            PostQuitMessage(0);
            return 0;
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
}


问:
tool / API for extracting football matches result to automatically insert into database
I have HANA database on SAP Neo Cloud Platform for storing results of Football events (matches of Euro, World Cup, Championship League, Premier Leagues).

Each Cup type has its own table (one for Euro, one for World Cup ... ), in which I store results of all seasons (example, Euro 2020, 2016, 2012 ...).

As there are much data coming almost every day I need an automatic way for inserting new rows with results, which will be done on Live or every day at the same time.

Is there a tool, which will extract data and generate inserts for database and which I can deploy to SAP Cloud Platform for automatic processing or Open WebService/Database, with which I can work comfortably to automatically do it myself?
Thank you for answer.

答:
you can use an api that give you all the matches real time

check out this one

https://rapidapi.com/hmoccupe/api/sports-scores


问:
PrestaShop - How to add a variable to an e-mail template
I recently purchased a review module for PrestaShop 1.7.5.

I'd like to add the customer's phone number to the email is sent by the module. But the tech support told me customizations are not covered by modules support, has to do by myself.

So, I try to do it myself.

I found the template variable code in LGMailer.php:

```<code>    $template_vars = array(
        '{firstname}' => $order['firstname'],
        '{lastname}'  => $order['lastname'],
        '{storename}' => Configuration::get('PS_SHOP_NAME'),
        '{email}'     => $order['email'],
        '{id_order}'  => $order['id_order'],
        '{link}'      => $link,
        '{product_details}' => $products
    );

    return $template_vars;
</code>```

as I want to add customer phone so modified it like this:

```<code>     $template_vars = array(
        '{firstname}' => $order['firstname'],
        '{lastname}'  => $order['lastname'],
        '{storename}' => Configuration::get('PS_SHOP_NAME'),
        '{email}'     => $order['email'],
        '{phone_mobile}'     => $order['phone_mobile'],        (Added this line)
        '{id_order}'  => $order['id_order'],
        '{link}'      => $link,
        '{product_details}' => $products
    );

    return $template_vars;
}
</code>```

But It doesn't seem to work.

Can anyone tell me what I am doing wrong? attached is the php file.

答:
The getTemplateVars() method from your module is called in the cron.php file and is using the getOrders() from the LGMailer class to retrieve orders for which e-mails will be sent.

If you look closely at this method, you will see that it does not select the mobile phone column, you would need to add it.

Edit the getOrders() method in LGMailer.php:

First, add the missing column

```<code>$query->select('a.`phone_mobile`');
</code>```

Then, add a JOIN statement base on the delivery address

```<code>$query->leftJoin('address', 'a', 'o.`id_address_delivery` = a.`id_address`');
</code>```

Finally

Don't forget to add {phone_mobile} inside opinion-request.html
(which you forgot to attach to your question).

I hope this helps!

Body:
I recently purchased a review module for PrestaShop 1.7.5.

I'd like to add the customer's phone number to the email is sent by the module. But the tech support told me customizations are not covered by modules support, has to do by myself.

So, I try to do it myself.

I found the template variable code in LGMailer.php:

    $template_vars = array(
        '{firstname}' => $order['firstname'],
        '{lastname}'  => $order['lastname'],
        '{storename}' => Configuration::get('PS_SHOP_NAME'),
        '{email}'     => $order['email'],
        '{id_order}'  => $order['id_order'],
        '{link}'      => $link,
        '{product_details}' => $products
    );

    return $template_vars;

as I want to add customer phone so modified it like this:

     $template_vars = array(
        '{firstname}' => $order['firstname'],
        '{lastname}'  => $order['lastname'],
        '{storename}' => Configuration::get('PS_SHOP_NAME'),
        '{email}'     => $order['email'],
        '{phone_mobile}'     => $order['phone_mobile'],        (Added this line)
        '{id_order}'  => $order['id_order'],
        '{link}'      => $link,
        '{product_details}' => $products
    );

    return $template_vars;
}

But It doesn't seem to work.

Can anyone tell me what I am doing wrong? attached is the php file.

Body:
The getTemplateVars() method from your module is called in the cron.php file and is using the getOrders() from the LGMailer class to retrieve orders for which e-mails will be sent.

If you look closely at this method, you will see that it does not select the mobile phone column, you would need to add it.

Edit the getOrders() method in LGMailer.php:

First, add the missing column

$query->select('a.`phone_mobile`');

Then, add a JOIN statement base on the delivery address

$query->leftJoin('address', 'a', 'o.`id_address_delivery` = a.`id_address`');

Finally

Don't forget to add {phone_mobile} inside opinion-request.html
(which you forgot to attach to your question).

I hope this helps!


问:
Export Azure SSL certificate as pfx file
I purchased a wild card certificate from azure. It sits right now in the Key Vault. I need to upload it to our other server which hosts one of our other applications for the same domain. There is no option to export the certificate as a .pfx file anywhere in azure portal.

Please help.

答:
I've found @dmitry-kazakov's answer to be helpful, but had to perform some minor updates to get it to work for me.

First I had to execute this command and assign it to $azureUserPrincipalName:

```<code>PS Azure:\> Get-Azureaduser

ObjectId                             DisplayName UserPrincipalName                                             UserType
--------                             ----------- -----------------                                             --------
89500455-0019-4059-8ef8-f1w32993z520 A User rmoore_roundlabinc.com#EXT#@rmooreroundlabinc.onmicrosoft.com Member
</code>```

Then here is the updated script:

```<code>$appServiceCertificateName = "ascdemo" #This is the "Subject Name" in Azure, not "Name"
$resourceGroupName = "ascdemorg"
$azureLoginEmailId = "user@microsoft.com"
$subscriptionId = "fb2c25dc-6bab-45c4-8cc9-cece7c42a95a"
$azureUserPrincipalName = "user@microsoft.com#EXT#@user@microsoft.com.onmicrosoft.com"

Login-AzureRmAccount
Set-AzureRmContext -SubscriptionId $subscriptionId

$ascResource= Get-AzureRmResource -ResourceName $appServiceCertificateName -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.CertificateRegistration/certificateOrders" -ApiVersion "2019-05-01"
$keyVaultId = ""
$keyVaultSecretName = ""

$certificateProperties=Get-Member -InputObject $ascResource.Properties.certificates[0] -MemberType NoteProperty
$certificateName = $certificateProperties[0].Name
$keyVaultId = $ascResource.Properties.certificates[0].$certificateName.KeyVaultId
$keyVaultSecretName = $ascResource.Properties.certificates[0].$certificateName.KeyVaultSecretName

$keyVaultIdParts = $keyVaultId.Split("/")
$keyVaultName = $keyVaultIdParts[$keyVaultIdParts.Length - 1]
$keyVaultResourceGroupName = $keyVaultIdParts[$keyVaultIdParts.Length - 5]
Set-AzureRmKeyVaultAccessPolicy -ResourceGroupName $keyVaultResourceGroupName -VaultName $keyVaultName -UserPrincipalName $azureUserPrincipalName -PermissionsToSecrets get
$secret = Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $keyVaultSecretName
$pfxCertObject=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @([Convert]::FromBase64String($secret.SecretValueText),"", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfxPassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 50 | % {[char]$_})
$currentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[io.file]::WriteAllBytes(".\appservicecertificate.pfx", $pfxCertObject.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $pfxPassword))
Write-Host "Created an App Service Certificate copy at: $currentDirectory\appservicecertificate.pfx"
Write-Warning "For security reasons, do not store the PFX password. Use it directly from the console as required."
Write-Host "PFX password: $pfxPassword"

Powershell –ExecutionPolicy Bypass
.\copyasc.ps1
</code>```

Body:
I've found @dmitry-kazakov's answer to be helpful, but had to perform some minor updates to get it to work for me.

First I had to execute this command and assign it to $azureUserPrincipalName:

PS Azure:\> Get-Azureaduser

ObjectId                             DisplayName UserPrincipalName                                             UserType
--------                             ----------- -----------------                                             --------
89500455-0019-4059-8ef8-f1w32993z520 A User rmoore_roundlabinc.com#EXT#@rmooreroundlabinc.onmicrosoft.com Member

Then here is the updated script:

$appServiceCertificateName = "ascdemo" #This is the "Subject Name" in Azure, not "Name"
$resourceGroupName = "ascdemorg"
$azureLoginEmailId = "user@microsoft.com"
$subscriptionId = "fb2c25dc-6bab-45c4-8cc9-cece7c42a95a"
$azureUserPrincipalName = "user@microsoft.com#EXT#@user@microsoft.com.onmicrosoft.com"

Login-AzureRmAccount
Set-AzureRmContext -SubscriptionId $subscriptionId

$ascResource= Get-AzureRmResource -ResourceName $appServiceCertificateName -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.CertificateRegistration/certificateOrders" -ApiVersion "2019-05-01"
$keyVaultId = ""
$keyVaultSecretName = ""

$certificateProperties=Get-Member -InputObject $ascResource.Properties.certificates[0] -MemberType NoteProperty
$certificateName = $certificateProperties[0].Name
$keyVaultId = $ascResource.Properties.certificates[0].$certificateName.KeyVaultId
$keyVaultSecretName = $ascResource.Properties.certificates[0].$certificateName.KeyVaultSecretName

$keyVaultIdParts = $keyVaultId.Split("/")
$keyVaultName = $keyVaultIdParts[$keyVaultIdParts.Length - 1]
$keyVaultResourceGroupName = $keyVaultIdParts[$keyVaultIdParts.Length - 5]
Set-AzureRmKeyVaultAccessPolicy -ResourceGroupName $keyVaultResourceGroupName -VaultName $keyVaultName -UserPrincipalName $azureUserPrincipalName -PermissionsToSecrets get
$secret = Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $keyVaultSecretName
$pfxCertObject=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @([Convert]::FromBase64String($secret.SecretValueText),"", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfxPassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 50 | % {[char]$_})
$currentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
[io.file]::WriteAllBytes(".\appservicecertificate.pfx", $pfxCertObject.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $pfxPassword))
Write-Host "Created an App Service Certificate copy at: $currentDirectory\appservicecertificate.pfx"
Write-Warning "For security reasons, do not store the PFX password. Use it directly from the console as required."
Write-Host "PFX password: $pfxPassword"

Powershell –ExecutionPolicy Bypass
.\copyasc.ps1


问:
Java "?." operator for checking null - What is it? (Not Ternary!)
I was reading an InfoWorld article (link to Wayback machine since the excerpt was since removed), and came across this little tidbit:

Take the latest version of Java, which
tries to make null-pointer checking
easier by offering shorthand syntax
for the endless pointer testing. Just
adding a question mark to each method
invocation automatically includes a
test for null pointers, replacing a
rat's nest of if-then statements, such
as:
```
public String getPostcode(Person person) {
String ans= null;
if (person != null) {
Name nm= person.getName();
if (nm!= null) {
ans= nm.getPostcode();
}
}
return ans
} ```

With this:
```
public String getFirstName(Person person) {
return person?.getName()?.getGivenName();
} ```

I've scoured the internet (okay, I spent at least 15 minutes googling variations on "java question mark") and got nothing. So, my question: is there any official documentation on this? I found that C# has a similar operator (the "??" operator), but I'd like to get the documentation for the language I'm working in. Or, is this just a use of the ternary operator that I've never seen before.

Thanks!

答:
Since Android does not support Lambda Functions unless your installed OS is >= 24, we need to use reflection.</p>

```<code>// Example using doIt function with sample classes
public void Test() {
    testEntry(new Entry(null));
    testEntry(new Entry(new Person(new Name("Bob"))));
}

static void testEntry(Entry entry) {
    doIt(doIt(doIt(entry,  "getPerson"), "getName"), "getName");
}

// Helper to safely execute function
public static <T,R> R doIt(T obj, String methodName) {
    try {
       if (obj != null)
           return (R)obj.getClass().getDeclaredMethod(methodName).invoke(obj);
    } catch (Exception ignore) {
    }
    return null;
}
</code>```

```<code>// Sample test classes
    static class Entry {
        Person person;
        Entry(Person person) { this.person = person; }
        Person getPerson() { return person; }
    }

    static class Person {
        Name name;
        Person(Name name) { this.name = name; }
        Name getName() { return name; }
    }

    static class Name {
        String name;
        Name(String name) { this.name = name; }
        String getName() {
            System.out.print(" Name:" + name + " ");
            return name;
        }
    }
}
</code>```

Body:
I was reading an InfoWorld article (link to Wayback machine since the excerpt was since removed), and came across this little tidbit:

Take the latest version of Java, which
tries to make null-pointer checking
easier by offering shorthand syntax
for the endless pointer testing. Just
adding a question mark to each method
invocation automatically includes a
test for null pointers, replacing a
rat's nest of if-then statements, such
as:

public String getPostcode(Person person) {
String ans= null;
if (person != null) {
Name nm= person.getName();
if (nm!= null) {
ans= nm.getPostcode();
}
}
return ans
}

With this:

public String getFirstName(Person person) {
return person?.getName()?.getGivenName();
}

I've scoured the internet (okay, I spent at least 15 minutes googling variations on "java question mark") and got nothing. So, my question: is there any official documentation on this? I found that C# has a similar operator (the "??" operator), but I'd like to get the documentation for the language I'm working in. Or, is this just a use of the ternary operator that I've never seen before.

Thanks!

Body:
Since Android does not support Lambda Functions unless your installed OS is >= 24, we need to use reflection.

// Example using doIt function with sample classes
public void Test() {
    testEntry(new Entry(null));
    testEntry(new Entry(new Person(new Name("Bob"))));
}

static void testEntry(Entry entry) {
    doIt(doIt(doIt(entry,  "getPerson"), "getName"), "getName");
}

// Helper to safely execute function
public static <T,R> R doIt(T obj, String methodName) {
    try {
       if (obj != null)
           return (R)obj.getClass().getDeclaredMethod(methodName).invoke(obj);
    } catch (Exception ignore) {
    }
    return null;
}

// Sample test classes
    static class Entry {
        Person person;
        Entry(Person person) { this.person = person; }
        Person getPerson() { return person; }
    }

    static class Person {
        Name name;
        Person(Name name) { this.name = name; }
        Name getName() { return name; }
    }

    static class Name {
        String name;
        Name(String name) { this.name = name; }
        String getName() {
            System.out.print(" Name:" + name + " ");
            return name;
        }
    }
}


问:
How do I exclude a column in a "ThenInclude" object in Entity Framework select query
I am doing a complex Entity Framework select query and I want to exclude one specific column in an object that is "ThenIncluded".

I tried to find a solution in StackOverflow, but no-one really fits my complex query.

Here is the query:

```<code>// topLevelId is given when we get here
await this.Context.TopLevel
                .Include(c1 => c1.Child1)
                .Include(c2 => c2.Child2)
                .Include(c3 => c3.Child3)
                .Include(c4 => c4.Child4).ThenInclude(gc1 => gc1.GrandChild1)
                .Include(c4 => c4.Child4).ThenInclude(gc2 => gc2.GrandChild2)
                .Include(c4 => c4.Child4).ThenInclude(gc3 => gc3.GrandChild3)
                .FirstAsync(tl => tl.TopLevelId == topLevelId);
</code>```

The "ThenIncluded" object I need to exclude a column from is GrandChild1, which is of this type:

```<code>public partial class Document
{
    public Document()
    {
        this.MyType = new HashSet<MyType>();
    }

    public Guid DocumentId { get; set; }
    public string DocumentName { get; set; }
    public string FileName { get; set; }
    public string MimeType { get; set; }
    public byte[] Data { get; set; }

    public ICollection<MyType> MyType { get; set; }
}
</code>```

And the column I want to exclude is Data (a byte array).

NB: I need that column in other queries and updates, so I cannot ignore the column from my EF model.

答:
Depending on what your consumer needs, you use .Select() to tell EF what data you want to pull. This can be relational like your data model, or you can flatten the data from the hierarchy down into a simpler structure.

For instance, given:

```<code>await this.Context.TopLevel
                .Include(c1 => c1.Child1).ThenInclude(gc1 => gc1.GrandChild1)
                .FirstAsync(tl => tl.TopLevelId == topLevelId);
</code>```

Assuming GrandChild1 is the Document with the byte array.

```<code>public class TopLevelViewModel
{
   public int TopLevelId { get; set; }
   public int Child1Id { get; set; }
   public string DocumentName { get; set; }
   public string FileName { get; set; }
}

await this.Context.TopLevel
    .Select(x => new TopLevelViewModel
    {
        TopLevelId = x.TopLevelId,
        Child1Id = x.Child1.Child1Id,
        DocumentName = x.Child1.Grandchild1.DocumentName,
        FileName = x.Child1.GrandChild1.FileName
    }).SingleAsync(x => x.TopLevelId = topLevelId);
</code>```

If the children represent a 1-to-many collection then you can define a ChildViewModel with their relevant document details:

```<code>public class TopLevelViewModel
{
   public int TopLevelId { get; set; }
   public ICollection<Child1ViewModel> Children { get; set; } = new List<Child1ViewModel>();
}
public class Child1ViewModel
{
   public int Child1Id { get; set; }
   public string DocumentName { get; set; }
   public string FileName { get; set; }
}

await this.Context.TopLevel
    .Select(x => new TopLevelViewModel
    {
        TopLevelId = x.TopLevelId,
        Children = x.Child1s.Select( c => new Child1ViewModel
        {
            Child1Id = c.Child1Id,
            DocumentName = c.Grandchild1.DocumentName,
            FileName = c.GrandChild1.FileName
        }).ToList()
    }).SingleAsync(x => x.TopLevelId = topLevelId);
</code>```

You can structure the relationships and data to pull back as you like. The advantages are that you only pull back the data fields you need which can reduce the payload size to improve performance, leverage indexes on the database, and keep from revealing too much about your data structure to the consumer.

Body:
I am doing a complex Entity Framework select query and I want to exclude one specific column in an object that is "ThenIncluded".

I tried to find a solution in StackOverflow, but no-one really fits my complex query.

Here is the query:

// topLevelId is given when we get here
await this.Context.TopLevel
                .Include(c1 => c1.Child1)
                .Include(c2 => c2.Child2)
                .Include(c3 => c3.Child3)
                .Include(c4 => c4.Child4).ThenInclude(gc1 => gc1.GrandChild1)
                .Include(c4 => c4.Child4).ThenInclude(gc2 => gc2.GrandChild2)
                .Include(c4 => c4.Child4).ThenInclude(gc3 => gc3.GrandChild3)
                .FirstAsync(tl => tl.TopLevelId == topLevelId);

The "ThenIncluded" object I need to exclude a column from is GrandChild1, which is of this type:

public partial class Document
{
    public Document()
    {
        this.MyType = new HashSet<MyType>();
    }

    public Guid DocumentId { get; set; }
    public string DocumentName { get; set; }
    public string FileName { get; set; }
    public string MimeType { get; set; }
    public byte[] Data { get; set; }

    public ICollection<MyType> MyType { get; set; }
}

And the column I want to exclude is Data (a byte array).

NB: I need that column in other queries and updates, so I cannot ignore the column from my EF model.

Body:
Depending on what your consumer needs, you use .Select() to tell EF what data you want to pull. This can be relational like your data model, or you can flatten the data from the hierarchy down into a simpler structure.

For instance, given:

await this.Context.TopLevel
                .Include(c1 => c1.Child1).ThenInclude(gc1 => gc1.GrandChild1)
                .FirstAsync(tl => tl.TopLevelId == topLevelId);

Assuming GrandChild1 is the Document with the byte array.

public class TopLevelViewModel
{
   public int TopLevelId { get; set; }
   public int Child1Id { get; set; }
   public string DocumentName { get; set; }
   public string FileName { get; set; }
}

await this.Context.TopLevel
    .Select(x => new TopLevelViewModel
    {
        TopLevelId = x.TopLevelId,
        Child1Id = x.Child1.Child1Id,
        DocumentName = x.Child1.Grandchild1.DocumentName,
        FileName = x.Child1.GrandChild1.FileName
    }).SingleAsync(x => x.TopLevelId = topLevelId);

If the children represent a 1-to-many collection then you can define a ChildViewModel with their relevant document details:

public class TopLevelViewModel
{
   public int TopLevelId { get; set; }
   public ICollection<Child1ViewModel> Children { get; set; } = new List<Child1ViewModel>();
}
public class Child1ViewModel
{
   public int Child1Id { get; set; }
   public string DocumentName { get; set; }
   public string FileName { get; set; }
}

await this.Context.TopLevel
    .Select(x => new TopLevelViewModel
    {
        TopLevelId = x.TopLevelId,
        Children = x.Child1s.Select( c => new Child1ViewModel
        {
            Child1Id = c.Child1Id,
            DocumentName = c.Grandchild1.DocumentName,
            FileName = c.GrandChild1.FileName
        }).ToList()
    }).SingleAsync(x => x.TopLevelId = topLevelId);

You can structure the relationships and data to pull back as you like. The advantages are that you only pull back the data fields you need which can reduce the payload size to improve performance, leverage indexes on the database, and keep from revealing too much about your data structure to the consumer.


问:
DocuSign API - Email sent to a signer - How do you enable links for HTML content in the email body?
I am trying to set the email body for a signer in my DocuSign envelope using the REST API. I am setting it using the emailNotification property for the EnvelopeRecipient (https://developers.docusign.com/esign-rest-api/reference/Envelopes/EnvelopeRecipients).

My concern is that the email body is HTML that has some links, but those links are not clickable in the email. Is there any way to allow for links to be clickable/navigatable?

答:
There's a back-end setting for Allow HTML input in the API.

You won't be able to configure this setting yourself - you can either reach out to your Account Manager, or have an administrator on the account open a case with DocuSign Support to request that setting be enabled.

If you open a support case, be sure to include your Sandbox account ID if you would like to have it enabled in the Demo environment as well.


问:
Problem with hierarchical facets on Shopify with Algolia's named_tags
I'm having issues with Algolia's instantsearch hierachicalmenu implementation on shopify. Every item on the list seems ok, but I couldn't get it working. Here is what I've done so far:

.
.
.

I have

 in snippets/algolia_instant_search.hogan.liquid

I have following codes in assets/algolia_instant_search.js.liquid

```<code>  instant.search.addWidget(
      instantsearch.widgets.hierarchicalMenu({
         container: '.hierarchical-categories-menu',
         attributes: ['named_tags.lvl0', 'named_tags.lvl1', 'named_tags.lvl2', 'named_tags.lvl3'],
         autoHideContainer: false,
         showParentLevel: true,
      })
   );
</code>```

I have lvl0, lvl1, lvl2, lvl3 facets as "active" and "hidden" on shopify-app's "Search Options" page.

Algolia's XHR response includes results[0].facets.named_tags.lvl0 .. lvl3 nodes with values and counts correctly.

Algolia's XHR response includes results[0].hits[n].named_tags.lvl0 .. lvl3 nodes.

Sample level data is as follows:
lvl0: "Žene"
lvl1: "Žene > Odeća"
lvl2: "Žene > Odeća > Gornji Delovi"
lvl3: "Žene > Odeća > Gornji Delovi > Košulje"

.
.
.

When I inspect the elements on the result page, I only see an empty div as the last child of .hierarchical-categories-menu:

Can anyone tell what the problem might be?

Thanks.

答: It turns out that you should make the "lvl" facets "inactive" on shopify-app's config page for some reason.

Body:
I'm having issues with Algolia's instantsearch hierachicalmenu implementation on shopify. Every item on the list seems ok, but I couldn't get it working. Here is what I've done so far:

.
.
.

I have

 in snippets/algolia_instant_search.hogan.liquid

I have following codes in assets/algolia_instant_search.js.liquid

  instant.search.addWidget(
      instantsearch.widgets.hierarchicalMenu({
         container: '.hierarchical-categories-menu',
         attributes: ['named_tags.lvl0', 'named_tags.lvl1', 'named_tags.lvl2', 'named_tags.lvl3'],
         autoHideContainer: false,
         showParentLevel: true,
      })
   );

I have lvl0, lvl1, lvl2, lvl3 facets as "active" and "hidden" on shopify-app's "Search Options" page.

Algolia's XHR response includes results[0].facets.named_tags.lvl0 .. lvl3 nodes with values and counts correctly.

Algolia's XHR response includes results[0].hits[n].named_tags.lvl0 .. lvl3 nodes.

Sample level data is as follows:
lvl0: "Žene"
lvl1: "Žene > Odeća"
lvl2: "Žene > Odeća > Gornji Delovi"
lvl3: "Žene > Odeća > Gornji Delovi > Košulje"

.
.
.

When I inspect the elements on the result page, I only see an empty div as the last child of .hierarchical-categories-menu:

Can anyone tell what the problem might be?

Thanks.


问:
How do I resolve "non-configurable property "ChoiceGroupOption" in a React.js app, I am using Parcel and imported comp from "office-ui-fabric-react"
I have a React app, I am using Parcel as my bundler. I want to use "office-ui-fabric-react" components. Everything works fine up until I import a Component from "office-ui-fabric-react" (Office Fabric Ui).

This is the error message I get from console -

TypeError: can't redefine non-configurable property "ChoiceGroupOption".

I have ensured that all dependencies are installed ("office-UI-fabric-react" does not require any stated dependency).

I then set up a new React project, this time using Create-React-App command to generate the boilerplate. This version doesn't have any issues, even after importing components from "office-ui-fabric-react", it works ok

```<code>import { PrimaryButton } from "office-ui-fabric-react
</code>```

//just add this line to a Reactjs project using parcel

TypeError: can't redefine non-configurable property "ChoiceGroupOption"

答:
Based on @VitalieBraga 's recommendation, the solution to this issue is to reference the specific module for every office-UI react component to be imported.
For example

```<code>import { PrimaryButton } from "office-ui-fabric-react/lib/button";
import { ChoiceGroup,IChoiceGroupOption} from "office-ui-fabric-react/lib/ChoiceGroup";
</code>```

this actually addresses the issue I had, but in regards, the issue of importing multiple components on a single line this is not possible with Parcel.

```<code>import { css, classNamesFunction, DefaultButton, IStyle, Label, PrimaryButton } from 'office-ui-fabric-react';
</code>```

The other alternative is to use Webpack as against Parcel

Body:
I have a React app, I am using Parcel as my bundler. I want to use "office-ui-fabric-react" components. Everything works fine up until I import a Component from "office-ui-fabric-react" (Office Fabric Ui).

This is the error message I get from console -

TypeError: can't redefine non-configurable property "ChoiceGroupOption".

I have ensured that all dependencies are installed ("office-UI-fabric-react" does not require any stated dependency).

I then set up a new React project, this time using Create-React-App command to generate the boilerplate. This version doesn't have any issues, even after importing components from "office-ui-fabric-react", it works ok

import { PrimaryButton } from "office-ui-fabric-react

//just add this line to a Reactjs project using parcel

TypeError: can't redefine non-configurable property "ChoiceGroupOption"

Body:
Based on @VitalieBraga 's recommendation, the solution to this issue is to reference the specific module for every office-UI react component to be imported.
For example

import { PrimaryButton } from "office-ui-fabric-react/lib/button";
import { ChoiceGroup,IChoiceGroupOption} from "office-ui-fabric-react/lib/ChoiceGroup";

this actually addresses the issue I had, but in regards, the issue of importing multiple components on a single line this is not possible with Parcel.

import { css, classNamesFunction, DefaultButton, IStyle, Label, PrimaryButton } from 'office-ui-fabric-react';

The other alternative is to use Webpack as against Parcel


问:
2 different Firestore interfaces
I've got 2 different firestore interfaces: both using the same firestore project.

I'm finding this abit confusing - which one am I meant to operate in?

How come the 2nd doesn't have access to other settings such as Rules?

答: Work in the first one. The second one is a simplified screen I think, because it is also for other services</p>

Title: 2 different Firestore interfaces