问:
No identifier/primary key specified for Entity why using KNP Translatable
I am using Knp/DoctrineBehaviors to translate my database content.
I followed the manual and created 2 entities, 1 for non-translatable content and the other for translatable fields.

```<code>namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;

    /**
     * Class Test
     * @package App\Entity
     * @ORM\Entity()
     */
    class Test implements TranslatableInterface
    {

        use TranslatableTrait;

        /**
         * @var integer
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         * @ORM\Id()
         */
        private $id;

        /**
         * @return int
         */
        public function getId(): int
        {
            return $this->id;
        }

        /**
         * @param int $id
         */
        public function setId(int $id): void
        {
            $this->id = $id;
        }

    }
</code>```

and the Translation entity:

```<code>namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;

/**
 * Class TestTranslation
 * @package App\Entity
 * @ORM\Entity()
 */
class TestTranslation implements TranslationInterface
{

    use TranslationTrait;

    /**
     * @var
     * @ORM\Column(type="string")
     */
    private $name;

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): void
    {
        $this->name = $name;
    }

}
</code>```

I also added the Bundle in my bundles.php file.

But when I run the command php bin/console doctrine:schema:update --force to create the table in give the error: No identifier/primary key specified for Entity "App\Entity\TestTranslation". Every Entity must have an identifier/p     rimary key.

答:
A primary key is missing in your entity "TestTranslation".
In doctrine every entity class must have an identifier/primary key. You can select the field that serves as the identifier with the @Id() annotation or in your case : @ORM\Id().

For example, add this to your entity :

```<code>/**
* @var integer
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Id()
*/
private $id;
</code>```

And then, you can play the command: php bin/console d:s:u --force

Body:
I am using Knp/DoctrineBehaviors to translate my database content.
I followed the manual and created 2 entities, 1 for non-translatable content and the other for translatable fields.

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;

    /**
     * Class Test
     * @package App\Entity
     * @ORM\Entity()
     */
    class Test implements TranslatableInterface
    {

        use TranslatableTrait;

        /**
         * @var integer
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         * @ORM\Id()
         */
        private $id;

        /**
         * @return int
         */
        public function getId(): int
        {
            return $this->id;
        }

        /**
         * @param int $id
         */
        public function setId(int $id): void
        {
            $this->id = $id;
        }

    }

and the Translation entity:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;

/**
 * Class TestTranslation
 * @package App\Entity
 * @ORM\Entity()
 */
class TestTranslation implements TranslationInterface
{

    use TranslationTrait;

    /**
     * @var
     * @ORM\Column(type="string")
     */
    private $name;

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): void
    {
        $this->name = $name;
    }

}

I also added the Bundle in my bundles.php file.

But when I run the command php bin/console doctrine:schema:update --force to create the table in give the error: No identifier/primary key specified for Entity "App\Entity\TestTranslation". Every Entity must have an identifier/p     rimary key.

Body:
A primary key is missing in your entity "TestTranslation".
In doctrine every entity class must have an identifier/primary key. You can select the field that serves as the identifier with the @Id() annotation or in your case : @ORM\Id().

For example, add this to your entity :

/**
* @var integer
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Id()
*/
private $id;

And then, you can play the command: php bin/console d:s:u --force


来源: stackexchange

问:
Problem skipping line whilst iterating using previous line and current line comparison
I have a list of sorted data arranged so that each item in the list is a csv line to be written to file.

The final step of the script checks the contents of each field and if all but the last field match then it will copy the current line's last field onto the previous line's last field.

I would like to as I've found and processed one of these matches skip the current line where the field was copied from thus only leaving one of the lines.

Here's an example set of data

```<code>field1,field2,field3,field4,something
field1,field2,field3,field4,else
</code>```

Desired output

```<code>field1,field2,field3,field4,something else
</code>```

This is what I have so far

```<code>output_csv = ['field1,field2,field3,field4,something',
              'field1,field2,field3,field4,else']

# run through the output
# open and create a csv file to save output
with open('output_table.csv', 'w') as f:

    previous_line = None
    part_duplicate_line = None
    part_duplicate_flag = False

    for line in output_csv:
        part_duplicate_flag = False

        if previous_line is not None:
            previous = previous_line.split(',')
            current = line.split(',')

            if (previous[0] == current[0]
                and previous[1] == current[1]
                and previous[2] == current[2]
                and previous[3] == current[3]):
                print(previous[0], current[0])
                previous[4] = previous[4].replace('\n', '') + ' ' + current[4]
                part_duplicate_line = ','.join(previous)
                part_duplicate_flag = True
                f.write(part_duplicate_line)

            if part_duplicate_flag is False:
                f.write(previous_line)

        previous_line = line
</code>```

ATM script adds the line but doesn't skip the next line, I've tried various renditions of continue statements after part_duplicate_line is written to file but to no avail.

答:
Looks like you want one entry for each combination of the first 4 fields

You can use a dict to aggregate data -

```<code>#First we extract the key and values
output_csv_keys = list(map(lambda x: ','.join(x.split(',')[:-1]), output_csv))
output_csv_values = list(map(lambda x: x.split(',')[-1], output_csv))

#Then we construct a dictionary with these keys and combine the values into a list
from collections import defaultdict
output_csv_dict = defaultdict(list)
for key, value in zip(output_csv_keys, output_csv_values):
  output_csv_dict[key].append(value)

#Then we extract the key/value combinations from this dictionary into a list
for_printing = [','.join([k, ' '.join(v)]) for k, v in output_csv_dict.items()]
print(for_printing)
#Output is ['field1,field2,field3,field4,something else']
#Each entry of this list can be output to the csv file
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of sorted data arranged so that each item in the list is a csv line to be written to file.

The final step of the script checks the contents of each field and if all but the last field match then it will copy the current line's last field onto the previous line's last field.

I would like to as I've found and processed one of these matches skip the current line where the field was copied from thus only leaving one of the lines.

Here's an example set of data

field1,field2,field3,field4,something
field1,field2,field3,field4,else

Desired output

field1,field2,field3,field4,something else

This is what I have so far

output_csv = ['field1,field2,field3,field4,something',
              'field1,field2,field3,field4,else']

# run through the output
# open and create a csv file to save output
with open('output_table.csv', 'w') as f:

    previous_line = None
    part_duplicate_line = None
    part_duplicate_flag = False

    for line in output_csv:
        part_duplicate_flag = False

        if previous_line is not None:
            previous = previous_line.split(',')
            current = line.split(',')

            if (previous[0] == current[0]
                and previous[1] == current[1]
                and previous[2] == current[2]
                and previous[3] == current[3]):
                print(previous[0], current[0])
                previous[4] = previous[4].replace('\n', '') + ' ' + current[4]
                part_duplicate_line = ','.join(previous)
                part_duplicate_flag = True
                f.write(part_duplicate_line)

            if part_duplicate_flag is False:
                f.write(previous_line)

        previous_line = line

ATM script adds the line but doesn't skip the next line, I've tried various renditions of continue statements after part_duplicate_line is written to file but to no avail.

Body:
Looks like you want one entry for each combination of the first 4 fields

You can use a dict to aggregate data -

#First we extract the key and values
output_csv_keys = list(map(lambda x: ','.join(x.split(',')[:-1]), output_csv))
output_csv_values = list(map(lambda x: x.split(',')[-1], output_csv))

#Then we construct a dictionary with these keys and combine the values into a list
from collections import defaultdict
output_csv_dict = defaultdict(list)
for key, value in zip(output_csv_keys, output_csv_values):
  output_csv_dict[key].append(value)

#Then we extract the key/value combinations from this dictionary into a list
for_printing = [','.join([k, ' '.join(v)]) for k, v in output_csv_dict.items()]
print(for_printing)
#Output is ['field1,field2,field3,field4,something else']
#Each entry of this list can be output to the csv file


问:
Firefox prevent local ip address from redirecting to HTTPS
I am trying to configure some hardware using the ip address: 192.168.1.251. For some insane reason Firefox keeps forcing it to https://192.168.1.251.

The fact is (a) the address is never on the internet; (b) in this case it is the only other machine; and (c) I have no control over how the hardware does its job any way. So what genius decided that they know better and I can’t connect using plain old http?

The question is how can I tell Firefox to just shut up and do as it’s told? I have already tried browser.urlbar.autoFill and network.stricttransportsecurity.preloadlist and neither of them works.

答:
This might be because at some point a server at this address responded with an HSTS header.

Click on the icon to the left of the URL in the address bar, then in the dialog click clear cookies and site data.  Then confirm in the dialog that appears.


问:
Different result inside train function and outside it
I am playing with tensorflow 2. I did my own model similar to how it is done here.

Then I created my own fit function. Now I get the weirdest thing ever. Here is the EXACT copy/paste output from my notebook where I did the tests:

```<code>def fit(x_train, y_train, learning_rate=0.01, epochs=10, batch_size=100, normal=True, verbose=True, display_freq=100):
    if normal:
        x_train = normalize(x_train)  # TODO: This normalize could be a bit different for each and be bad.

    num_tr_iter = int(len(y_train) / batch_size)  # Number of training iterations in each epoch
    if verbose:
        print("Starting training...")
    for epoch in range(epochs):
        # Randomly shuffle the training data at the beginning of each epoch
        x_train, y_train = randomize(x_train, y_train)
        for iteration in range(num_tr_iter):
            # Get the batch
            start = iteration * batch_size
            end = (iteration + 1) * batch_size
            x_batch, y_batch = get_next_batch(x_train, y_train, start, end)
            # Run optimization op (backpropagation)
            # import pdb; pdb.set_trace()
            if verbose and (epoch * batch_size + iteration) % display_freq == 0:
                current_loss = _apply_loss(y_train, model(x_train, training=True))
                current_acc = evaluate_accuracy(x_train, y_train)
                print("Epoch: {0}/{1}; batch {2}/{3}; loss: {4:.4f}; accuracy: {5:.2f} %"
                      .format(epoch, epochs, iteration, num_tr_iter, current_loss, current_acc*100))
            train_step(x_batch, y_batch, learning_rate)

    current_loss = _apply_loss(y_train, model(x_train, training=True))
    current_acc = evaluate_accuracy(x_train, y_train)
    print("End: loss: {0:.4f}; accuracy: {1:.2f} %".format(current_loss, current_acc*100))

import logging
logging.getLogger('tensorflow').disabled = True
fit(x_train, y_train)

current_loss = _apply_loss(y_train, model(x_train, training=True))
current_acc = evaluate_accuracy(x_train, y_train)
print("End: loss: {0:.4f}; accuracy: {1:.2f} %".format(current_loss, current_acc*100))
</code>```

This segment outputs:

```<code>Starting training...
Epoch: 0/10; batch 0/80; loss: 0.9533; accuracy: 59.67 %
Epoch: 1/10; batch 0/80; loss: 0.9386; accuracy: 60.15 %
Epoch: 2/10; batch 0/80; loss: 0.9259; accuracy: 60.50 %
Epoch: 3/10; batch 0/80; loss: 0.9148; accuracy: 61.05 %
Epoch: 4/10; batch 0/80; loss: 0.9051; accuracy: 61.15 %
Epoch: 5/10; batch 0/80; loss: 0.8968; accuracy: 61.35 %
Epoch: 6/10; batch 0/80; loss: 0.8896; accuracy: 61.27 %
Epoch: 7/10; batch 0/80; loss: 0.8833; accuracy: 61.51 %
Epoch: 8/10; batch 0/80; loss: 0.8780; accuracy: 61.52 %
Epoch: 9/10; batch 0/80; loss: 0.8733; accuracy: 61.54 %
End: loss: 0.8733; accuracy: 61.54 %
End: loss: 0.4671; accuracy: 77.08 %
</code>```

Now my question is, how is it that I get a different value on the last 2 lines!? I am doing the same thing right? I am totally puzzled here. I don't even know how to google this.

答: So the problem was just stupid. It was due to the normalize thing I did at the start of the train example! Removed it and started working Ok.</p>

Body:
I am playing with tensorflow 2. I did my own model similar to how it is done here.

Then I created my own fit function. Now I get the weirdest thing ever. Here is the EXACT copy/paste output from my notebook where I did the tests:

def fit(x_train, y_train, learning_rate=0.01, epochs=10, batch_size=100, normal=True, verbose=True, display_freq=100):
    if normal:
        x_train = normalize(x_train)  # TODO: This normalize could be a bit different for each and be bad.

    num_tr_iter = int(len(y_train) / batch_size)  # Number of training iterations in each epoch
    if verbose:
        print("Starting training...")
    for epoch in range(epochs):
        # Randomly shuffle the training data at the beginning of each epoch
        x_train, y_train = randomize(x_train, y_train)
        for iteration in range(num_tr_iter):
            # Get the batch
            start = iteration * batch_size
            end = (iteration + 1) * batch_size
            x_batch, y_batch = get_next_batch(x_train, y_train, start, end)
            # Run optimization op (backpropagation)
            # import pdb; pdb.set_trace()
            if verbose and (epoch * batch_size + iteration) % display_freq == 0:
                current_loss = _apply_loss(y_train, model(x_train, training=True))
                current_acc = evaluate_accuracy(x_train, y_train)
                print("Epoch: {0}/{1}; batch {2}/{3}; loss: {4:.4f}; accuracy: {5:.2f} %"
                      .format(epoch, epochs, iteration, num_tr_iter, current_loss, current_acc*100))
            train_step(x_batch, y_batch, learning_rate)

    current_loss = _apply_loss(y_train, model(x_train, training=True))
    current_acc = evaluate_accuracy(x_train, y_train)
    print("End: loss: {0:.4f}; accuracy: {1:.2f} %".format(current_loss, current_acc*100))

import logging
logging.getLogger('tensorflow').disabled = True
fit(x_train, y_train)

current_loss = _apply_loss(y_train, model(x_train, training=True))
current_acc = evaluate_accuracy(x_train, y_train)
print("End: loss: {0:.4f}; accuracy: {1:.2f} %".format(current_loss, current_acc*100))

This segment outputs:

Starting training...
Epoch: 0/10; batch 0/80; loss: 0.9533; accuracy: 59.67 %
Epoch: 1/10; batch 0/80; loss: 0.9386; accuracy: 60.15 %
Epoch: 2/10; batch 0/80; loss: 0.9259; accuracy: 60.50 %
Epoch: 3/10; batch 0/80; loss: 0.9148; accuracy: 61.05 %
Epoch: 4/10; batch 0/80; loss: 0.9051; accuracy: 61.15 %
Epoch: 5/10; batch 0/80; loss: 0.8968; accuracy: 61.35 %
Epoch: 6/10; batch 0/80; loss: 0.8896; accuracy: 61.27 %
Epoch: 7/10; batch 0/80; loss: 0.8833; accuracy: 61.51 %
Epoch: 8/10; batch 0/80; loss: 0.8780; accuracy: 61.52 %
Epoch: 9/10; batch 0/80; loss: 0.8733; accuracy: 61.54 %
End: loss: 0.8733; accuracy: 61.54 %
End: loss: 0.4671; accuracy: 77.08 %

Now my question is, how is it that I get a different value on the last 2 lines!? I am doing the same thing right? I am totally puzzled here. I don't even know how to google this.


问:
retrofit spring boot not responding
I have a server in spring boot, which is running on port 8080.

Now I'm trying to call rest api in my android application using retrofit2.

Here is what I have implemented:

```<code>        final TextView textView=findViewById(R.id.t1);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://localhost:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);

        Call<TC> call = jsonPlaceHolderApi.getPosts();

        call.enqueue(new Callback<TC>() {
            @Override
            public void onResponse(Call<TC> call, Response<TC> response) {
                textView.setText(response.toString());

                if (!response.isSuccessful()) {
                    return;
                }

                TC posts = response.body();
                textView.setText(posts.toString());
            }

            @Override
            public void onFailure(Call<TC> call, Throwable t) {

            }
        });

</code>```

I can surly say that, it's not working as my api is not even being called. As the hello world screen remains as it is.

And in my server I have logger, which doesn't log anything, so it doesn't get called.

Here is my CORS:

```<code>@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("*")
                        .allowedOrigins("*");
            }
        };
    }
</code>```

答:
The problem is with the word localhost.

As for debugging purpose I'm connecting the android device with my PC so my android device can't connect to localhost as it is just an alias of my IP address.

To resolve this, I opened up CMD and wrote ipconfig, by this command I can see all details related to IP.

And here it shows my IPv4 address as $.$.$.$. I just replaced the localhost with that $.$.$.$.
Now everything is working fine.

Title: retrofit spring boot not responding

Body:
I have a server in spring boot, which is running on port 8080.

Now I'm trying to call rest api in my android application using retrofit2.

Here is what I have implemented:

        final TextView textView=findViewById(R.id.t1);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://localhost:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);

        Call<TC> call = jsonPlaceHolderApi.getPosts();

        call.enqueue(new Callback<TC>() {
            @Override
            public void onResponse(Call<TC> call, Response<TC> response) {
                textView.setText(response.toString());

                if (!response.isSuccessful()) {
                    return;
                }

                TC posts = response.body();
                textView.setText(posts.toString());
            }

            @Override
            public void onFailure(Call<TC> call, Throwable t) {

            }
        });

I can surly say that, it's not working as my api is not even being called. As the hello world screen remains as it is.

And in my server I have logger, which doesn't log anything, so it doesn't get called.

Here is my CORS:

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("*")
                        .allowedOrigins("*");
            }
        };
    }


问:
Increment column based on second column
Consider a dataframe like this:

```<code>dat <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, NA, NA, 12, 10, NA, NA, NA, 9, 10, 10, 11, NA, 11, 11, NA),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    NA 2008
3   John    NA 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    NA 2019
7    Sam    NA 2019
8    Sam    NA 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    NA 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    NA 2020
</code>```

I'd like to fill in the missing NAs in grade based on year.  So Sam for example is in 10th grade in 2018, and in 2019 he'll be in 11th grade:

```<code>dat_desired <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, 10, 11, 12, 10, 11, 11, 12, 9, 10, 10, 11, 10, 11, 11, 12),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    10 2008
3   John    11 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    11 2019
7    Sam    11 2019
8    Sam    12 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    10 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    12 2020
</code>```

How can I do this?  I've tried:

```<code>dat %>%
  group_by(name) %>%
  fill(grade, .direction = "updown")
</code>```

which doesn't work because it doesn't take year into account.  Adding a group_by(year) doesn't help either, because then no NAs are replaced.

答:
A rough solution can be implemented with a for loop:</p>

```<code>X <- as.character(unique(dat$name))

for ( i in 1:length(X)){
a <- min(dat[dat$name==X[i],]$grade, na.rm = T)
b <- min(dat[dat$name==X[i],]$year, na.rm = T)
dat[dat$name==X[i] & is.na(dat$grade),]$grade <- dat[dat$name==X[i] & is.na(dat$grade),]$year-b+a
}
</code>```

Title: Increment column based on second column

Body:
Consider a dataframe like this:

dat <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, NA, NA, 12, 10, NA, NA, NA, 9, 10, 10, 11, NA, 11, 11, NA),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    NA 2008
3   John    NA 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    NA 2019
7    Sam    NA 2019
8    Sam    NA 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    NA 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    NA 2020

I'd like to fill in the missing NAs in grade based on year.  So Sam for example is in 10th grade in 2018, and in 2019 he'll be in 11th grade:

dat_desired <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, 10, 11, 12, 10, 11, 11, 12, 9, 10, 10, 11, 10, 11, 11, 12),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    10 2008
3   John    11 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    11 2019
7    Sam    11 2019
8    Sam    12 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    10 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    12 2020

How can I do this?  I've tried:

dat %>%
  group_by(name) %>%
  fill(grade, .direction = "updown")

which doesn't work because it doesn't take year into account.  Adding a group_by(year) doesn't help either, because then no NAs are replaced.

Body:
A rough solution can be implemented with a for loop:

X <- as.character(unique(dat$name))

for ( i in 1:length(X)){
a <- min(dat[dat$name==X[i],]$grade, na.rm = T)
b <- min(dat[dat$name==X[i],]$year, na.rm = T)
dat[dat$name==X[i] & is.na(dat$grade),]$grade <- dat[dat$name==X[i] & is.na(dat$grade),]$year-b+a
}


问:
Faking HTTP request responses for testing in Android
I'm writing an Android app which sometimes needs to request data through HTTP from a REST API. I'm using the Apache DefaultHttpClient for performing requests. Is there a way to write tests for this app and "replace" DefaultHttpClient's response when running the tests so that test results are always consistent?

As an example of the things I'd like to test, one of the web services I'm accessing takes a string and performs a text search, returning a paged list of objects. I need to test the cases where the list is empty, the list fits in the first page, or the list is larger than a page and the app needs to make several requests to get the complete list.

I'm not the developer of this web API nor can modify its responses, so I can't change what it returns. For the above example, if I want to test the case where the list returned is empty, I could just search for a string which I'm sure won't return any results, but the other two cases are harder because what the service can return is always changing.

I think ideally I would have a way to get a modified DefaultHttpClient when running tests, that returns a hardcoded result for requests to a given URL instead of actually doing the network request. This way I would always get consistent results independently of the real web service's response.

I'm currently using Robotium for testing but I'm open to using other tools too.

答: Another option is to use Dependency Injection so that you can change the HttpClient when running the tests. Check out Guice if you are interested.</p>

ContentLicense: CC BY-SA 3.0


问:
FormData object from React doesnt convert on backend C# to model
I have application made with React Native, and the backend API is in .NET C#.
I am trying to send some data from frontend to backend

reactjs

```<code>let formData = new FormData();
formData.append('token', token)
formData.append('document', document)
formData.append('file', file);
</code>```

Where token is a string, file is some file, but document is an object with params like Id and Name . So on backend I receive the data like this

C#

```<code>[HttpPost]
[AllowAnonymous]
public ActionResult SendDocument(string token, DocumentMobile document, HttpPostedFileBase file)
{
    //do thins
}
</code>```

The problem is that object document is not converted to DocumentMobile model, like it used to do without using FormData, and all props inside are null.

How to do this?

答:
You need to bind each properties of your class, that's how the model binder is working, it is looking for the name of the properties of your class. So depends on the structure of your document class, one of the following should works in your case:

```<code>formData.append('Id', document.Id)
formData.append('Name', document.Name)
</code>```

Or this:

```<code>formData.append('document', {Id: document.Id, Name: document.Name})
</code>```

Or:

```<code>formdata.append("document[id]", document.Id)
formdata.append("document[name]", document.Name)
</code>```

And for file you might want to use something like this:

```<code>formData.append('file', {uri: file, name: 'image.jpg', type: 'image/jpeg'})
</code>```

Body:
I have application made with React Native, and the backend API is in .NET C#.
I am trying to send some data from frontend to backend

reactjs

let formData = new FormData();
formData.append('token', token)
formData.append('document', document)
formData.append('file', file);

Where token is a string, file is some file, but document is an object with params like Id and Name . So on backend I receive the data like this

C#

[HttpPost]
[AllowAnonymous]
public ActionResult SendDocument(string token, DocumentMobile document, HttpPostedFileBase file)
{
    //do thins
}

The problem is that object document is not converted to DocumentMobile model, like it used to do without using FormData, and all props inside are null.

How to do this?

Body:
You need to bind each properties of your class, that's how the model binder is working, it is looking for the name of the properties of your class. So depends on the structure of your document class, one of the following should works in your case:

formData.append('Id', document.Id)
formData.append('Name', document.Name)

Or this:

formData.append('document', {Id: document.Id, Name: document.Name})

Or:

formdata.append("document[id]", document.Id)
formdata.append("document[name]", document.Name)

And for file you might want to use something like this:

formData.append('file', {uri: file, name: 'image.jpg', type: 'image/jpeg'})


问:
Can envsubst not do in-place substitution?
I have a config file which contains some ENV_VARIABLE styled variables.

```<code>This is my file.
It might contain $EXAMPLES of text.
</code>```

Now I want that variable replaced with a value which is saved in my actual environment variables. So I'm trying this:

```<code>export EXAMPLES=lots
envsubst < file.txt > file.txt
</code>```

But it doesn't work when the input file and output file are identical. The result is an empty file of size 0.

There must be a good reason for this, some bash basics that I'm not aware of?
How do I achieve what I want to do, ideally without first outputting to a different file and then replacing the original file with it?

I know that I can do it easily enough with sed, but when I discovered the envsubst command I thought that it should be perfect for my use case, so I'd like to use that.

答:
```<code>envsubst < file.txt | tee file.txt
</code>```

Caution: @SoftwareFactor rightly pointed out in the comments that this answer suffers from a race condition and can cause the resulting file to be empty at random.

Body:
I have a config file which contains some ENV_VARIABLE styled variables.

This is my file.
It might contain $EXAMPLES of text.

Now I want that variable replaced with a value which is saved in my actual environment variables. So I'm trying this:

export EXAMPLES=lots
envsubst < file.txt > file.txt

But it doesn't work when the input file and output file are identical. The result is an empty file of size 0.

There must be a good reason for this, some bash basics that I'm not aware of?
How do I achieve what I want to do, ideally without first outputting to a different file and then replacing the original file with it?

I know that I can do it easily enough with sed, but when I discovered the envsubst command I thought that it should be perfect for my use case, so I'd like to use that.

Body:
envsubst < file.txt | tee file.txt

Caution: @SoftwareFactor rightly pointed out in the comments that this answer suffers from a race condition and can cause the resulting file to be empty at random.


问:
Intelij extract method keeps trying to replace duplicate method signatures - please stop
Intellij has a really neat feature, that lets me seamlessly extract a block of code into its own method. I can then give this method a nice, descriptive name and move on with life.

However, intellij also tries to find other blocks of code that are similar, and then tries to perusade me that I should also refactor them too, to use this new method its made. And then, when I hit the oddly-named "cancel" button (which implies the whole operation is cancelled, but it's not, it just stops asking about any remaining blocks), it leaves me looking at whatever the block of code it last asked me about.

I really don't like this feature. Here's why: If I'm say comparing two ints - the naming of the code block will depend on the context of those two ints, but intellij will find any comparison between two ints anywhere in that file, and then insist that this is also a candidate for extraction.

Most times it is not, and to make it worse, when I ask intellij to stop it, in a fit of pique, leaves me wherever the last comparison was, so now I have to navigate back to where I was working.

How do I tell intellij just to extract exactly what I selected, and do nothing else?

答:
Please follow/vote/comment the issue created for this usability problem at YouTrack:
https://youtrack.jetbrains.com/issue/IDEA-233201</p>


问:
Reducing Function Complexity
I'm writing a simple calculator in React. I'm trying to update the state of a component based on which button is clicked (as you would expect). The component's state is as follows:

```<code>this.state = {
  total: null,
  next: null,
  operation: null,
}

</code>```

Presently, I have one long if/else statement that checks a bunch of scenarios to determine what the appropriate values should be. I'm wondering how I could rewrite this to reduce the complexity of the function:

```<code>handleClick(buttonName) {
    let { total, next } = this.state;
    const { operation } = this.state;
    let obj;
    const nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    const syms = ['+', '-', 'X', '/', '%'];
    const equal = '=';
    const reset = 'AC';
    const decimalPoint = '.';

    if (total === null && nums.indexOf(buttonName) >= 0) {
      this.setState({
        total: buttonName,
      });
    } else if (total !== null
      && buttonName === decimalPoint
      && (total.indexOf(decimalPoint) === -1)) {
      this.setState({
        total: total += buttonName,
      });
    } else if (total !== null
      && next !== null
      && buttonName === decimalPoint
      && (next.indexOf(decimalPoint) === -1)) {
      this.setState({
        next: next += buttonName,
      });
    } else if (total !== null
      && operation === null
      && syms.indexOf(buttonName) >= 0) {
      this.setState({
        operation: buttonName,
      });
    } else if (total !== null
      && operation === null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        total: total += buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next === null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        next: buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next !== null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        next: next += buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next !== null
      && ((buttonName === equal) || (buttonName === reset))) {
      obj = method.calculate(this.state, operation);
      this.setState({
        total: obj.total,
        next: obj.next,
        operation: buttonName,
      });
    }
  }
</code>```

PS. the "method.calculate" function is stated in another module.

答:
You can reify the click handler conditions, and then have a utility function select and invoke the relevant handler.

I don't know if this will work in your case because I am not sure if the reference to state is constant and whether setState is target-dependent, but this serves as an example.

Edit: I have investigated how React works, and the precise code below will likely not work, but the general approach is sound.

const createHandler =
    ({ state, setState }) =>
        (buttonName) => handlers.some(({condition, action}) =>
            condition({ buttonName, state: this.state}) &&
            action({buttonName, state, setState}) &&
            true)

const handlers = [
    {
        condition: ({ state: { total }}) => {
            const nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
            return (total === null && nums.indexOf(buttonName) >= 0)
        },
        action: ({ buttonName, setState }) => setState({ total: buttonName })
    },
    // ...
];

class MyComponent {
    constructor() {
        this.handle = createHandler({ state: this.state, setState: this.setState })
    }

    handleClick(buttonName) {
        this.handle(buttonName)
    }
}
```

Title: Reducing Function Complexity

Body:
I'm writing a simple calculator in React. I'm trying to update the state of a component based on which button is clicked (as you would expect). The component's state is as follows:

this.state = {
  total: null,
  next: null,
  operation: null,
}

Presently, I have one long if/else statement that checks a bunch of scenarios to determine what the appropriate values should be. I'm wondering how I could rewrite this to reduce the complexity of the function:

handleClick(buttonName) {
    let { total, next } = this.state;
    const { operation } = this.state;
    let obj;
    const nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    const syms = ['+', '-', 'X', '/', '%'];
    const equal = '=';
    const reset = 'AC';
    const decimalPoint = '.';

    if (total === null && nums.indexOf(buttonName) >= 0) {
      this.setState({
        total: buttonName,
      });
    } else if (total !== null
      && buttonName === decimalPoint
      && (total.indexOf(decimalPoint) === -1)) {
      this.setState({
        total: total += buttonName,
      });
    } else if (total !== null
      && next !== null
      && buttonName === decimalPoint
      && (next.indexOf(decimalPoint) === -1)) {
      this.setState({
        next: next += buttonName,
      });
    } else if (total !== null
      && operation === null
      && syms.indexOf(buttonName) >= 0) {
      this.setState({
        operation: buttonName,
      });
    } else if (total !== null
      && operation === null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        total: total += buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next === null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        next: buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next !== null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        next: next += buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next !== null
      && ((buttonName === equal) || (buttonName === reset))) {
      obj = method.calculate(this.state, operation);
      this.setState({
        total: obj.total,
        next: obj.next,
        operation: buttonName,
      });
    }
  }

PS. the "method.calculate" function is stated in another module.


问:
Keyword 'Selenium2Library.Click Element' expected 1 to 3 arguments, got 0
I'm trying to select the first item from the list below using robotframework:

```<code><select id="organization_saml_enabled" name="organization[saml_enabled]">
   <option value="true">SAML SSO enabled</option>
   <option value="false" selected="selected">SAML SSO disabled</option>
</select>
</code>```

With this snippet:

```<code>Click Element  //select[@id="organization_saml_enabled"]/option[@value="true"]
</code>```

I get the error Keyword 'Selenium2Library.Click Element' expected 1 to 3 arguments, got 0.

I dont get it because from the way i understand the documentation the Click Element needs the locator and optional offsets.
Can anyone help me check what I'm missing here.

答: dont use Selenium2Library, use SeleniumLibrary latest version. </p>

Body:
I'm trying to select the first item from the list below using robotframework:

<select id="organization_saml_enabled" name="organization[saml_enabled]">
   <option value="true">SAML SSO enabled</option>
   <option value="false" selected="selected">SAML SSO disabled</option>
</select>

With this snippet:

Click Element  //select[@id="organization_saml_enabled"]/option[@value="true"]

I get the error Keyword 'Selenium2Library.Click Element' expected 1 to 3 arguments, got 0.

I dont get it because from the way i understand the documentation the Click Element needs the locator and optional offsets.
Can anyone help me check what I'm missing here.


问:
DEVICE_STATE(SIP/mypeer) in Asterisk returning only UNAVAILABLE and NOT_INUSE, not returning other status why?
DEVICE_STATE(SIP/mypeer) is returning only UNAVAILABLE and NOT_INUSE but not the other available options such as UNKNOWN, INUSE, BUSY, INVALID, RINGING, RINGINUSE, ONHOLD.

```<code>exten=>1,NoOp(SIP/mypeer has state ${DEVICE_STATE(SIP/mypeer)})
same=>2,ExecIf($[${DEVICE_STATE(SIP/mypeer)}=NOT_INUSE]?Goto(5):Goto(2))
</code>```

Here I am expecting the device_state should return busy, ringing, inuse or onhold at mypeer while getting a second call but I am getting only UNAVAILABLE and NOT_INUSE as output.

I already set callcounter=yes and call-limit=1000. What should I do now?

答:
as stated by the official page here:
asterisk chan_sip state and presence

The callcounter option in sip.conf must be enabled for SIP devices (e.g. SIP/Alice) to provide advanced device state. Without it you may see some state, such as unavailable or idle, but not much more.

Body:
DEVICE_STATE(SIP/mypeer) is returning only UNAVAILABLE and NOT_INUSE but not the other available options such as UNKNOWN, INUSE, BUSY, INVALID, RINGING, RINGINUSE, ONHOLD.

exten=>1,NoOp(SIP/mypeer has state ${DEVICE_STATE(SIP/mypeer)})
same=>2,ExecIf($[${DEVICE_STATE(SIP/mypeer)}=NOT_INUSE]?Goto(5):Goto(2))

Here I am expecting the device_state should return busy, ringing, inuse or onhold at mypeer while getting a second call but I am getting only UNAVAILABLE and NOT_INUSE as output.

I already set callcounter=yes and call-limit=1000. What should I do now?


问:
How to upload contacts as Iterable from Flutter to Firestore
I'm creating an app which will upload all contacts to Firestore database with map type. But below code do not upload contacts to Firestore. Please help.

I have been trying to fetch contacts from my phone to Firestore using Flutter app. I used contact_services library to fetch contacts. Even after trying some similar examples, I could not my contacts to Firestore using map type. Where do I make changes so that I can upload all my contacts as map value to Firestore

```<code>final Iterable<Contact> contacts = await ContactsService.getContacts(withThumbnails: false);
Firestore.instance
            .collection('contacts')
            .document(firebaseUser.uid)
            .setData({
          'contact':{ contacts.map((Contact contact){ 'name': contacts.displayName,contacts.phone})}
        });
</code>```

I expected to display all my contacts in firestore with map type, but actual output is none were uploaded.

答:
I am sure you have fixed this since this is an old post. But there are a few things incorrect with how you are using the map method id Dart.

You named your element variable "contact" and not "contacts" so that is the variable you should be referencing "contact" to get your information. So it would be contact.displayName.

You are not returning anything. Because there is no "=>" there is no implicit return and because there is no "return" there is no explicit return.

Also, what you are returning from the map method is an Iterable to the contact field.

I am not sure what you are trying to accomplish here. Are you trying to insert a nested object? If so, your phone is also missing a key

Body:
I'm creating an app which will upload all contacts to Firestore database with map type. But below code do not upload contacts to Firestore. Please help.

I have been trying to fetch contacts from my phone to Firestore using Flutter app. I used contact_services library to fetch contacts. Even after trying some similar examples, I could not my contacts to Firestore using map type. Where do I make changes so that I can upload all my contacts as map value to Firestore

final Iterable<Contact> contacts = await ContactsService.getContacts(withThumbnails: false);
Firestore.instance
            .collection('contacts')
            .document(firebaseUser.uid)
            .setData({
          'contact':{ contacts.map((Contact contact){ 'name': contacts.displayName,contacts.phone})}
        });

I expected to display all my contacts in firestore with map type, but actual output is none were uploaded.


问:
GoogleTrans API Error - Expecting value: line 1 column 1 (char 0)
I am having this error when translating thousands of text data in an iteration:

```<code>Expecting value: line 1 column 1 (char 0)
</code>```

My code for translating big amounts of text:

```<code>translatedList = []
for index, row in df.iterrows():
    newrow = copy.deepcopy(row)
    try:
        # translate the 'text' column
        translated = translator.translate(row['text'], dest='en')
        newrow['translated'] = translated.text
    except Exception as e:
        print(str(e))
        continue
    translatedList.append(newrow)
</code>```

I receive this error after translating about 2-3k rows.

答:
I will give a modified answer of Austin Marino, here a solution that just worked for me in a 2000 word list (would work in bigger list too).

first you need to install NordVPN and add it to the system path check this link :

https://support.nordvpn.com/Connectivity/Windows/1350897482/Connect-to-NordVPN-app-on-Windows-using-the-Command-Prompt.htm

The goal is so you can connect/disconnect and chose servers with CMD (you can do the same thing in linux) so you can cantrole theses NordVPN CMD commands through Python code.

Here is the function (please import the libraries) :

```<code>   import random

listofservers = ["South Africa", "Egypt" , "Australia", "New Zealand",  "South Korea", "Singapore", "Taiwan", "Vietnam", "Hong Kong", "Indonesia", "Thailand", "Japan", "Malaysia", "United Kingdom", "Netherlands", "Germany", "France", "Belgium", "Switzerland", "Sweden","Spain","Denmark", "Italy", "Norway", "Austria", "Romania", "Czech Republic", "Luxembourg", "Poland", "Finland", "Hungary", "Latvia", "Russia", "Iceland", "Bulgaria", "Croatia", "Moldova", "Portugal", "Albania", "Ireland", "Slovakia","Ukraine", "Cyprus", "Estonia", "Georgia", "Greece", "Serbia", "Slovenia", "Azerbaijan", "Bosnia and Herzegovina", "Macedonia","India", 'Turkey', 'Israel', 'United Arab Emirates', 'United States', 'Canada','Mexico'
,"Brazil", "Costa Rica", "Argentina", "Chile"]

def SelectServer(l):
    return random.choice(l)

def translate_text(text, dest_language="en"):
    # Used to translate using the googletrans library
    translator = googletrans.Translator()
    try:

        translation = translator.translate(text=text, dest=dest_language)

    except json.decoder.JSONDecodeError:
        # api call restriction

        print("exception !! déconection du VPN ")
        process = subprocess.Popen(["nordvpn", "-d"], shell = True ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.wait()

        time.sleep(5)

        srv = SelectServer(listofservers)

        print("sélection du serveur  : "+ srv + " et connexion")

        process = subprocess.Popen(["nordvpn", "-c", "-g", srv ], shell = True ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.wait()
        time.sleep(60)

        return translate_text(text=text, dest_language=dest_language)

    return translation.text

    #translate to EN and remove EN stopwords
    ListCapTranslated = []
    for row  in ListCaptionsCleanFiltred:
        # REINITIALIZE THE API
        newrow = translate_text(row, dest_language="en")
        ListCapTranslated.append(newrow)

ListCapTranslated
</code>```

Before running the code, please add NordVPN to System path and test connecting/disconnecting on servers through CMD so you make sure everything works.

Cheers.

Body:
I am having this error when translating thousands of text data in an iteration:

Expecting value: line 1 column 1 (char 0)

My code for translating big amounts of text:

translatedList = []
for index, row in df.iterrows():
    newrow = copy.deepcopy(row)
    try:
        # translate the 'text' column
        translated = translator.translate(row['text'], dest='en')
        newrow['translated'] = translated.text
    except Exception as e:
        print(str(e))
        continue
    translatedList.append(newrow)

I receive this error after translating about 2-3k rows.

Body:
I will give a modified answer of Austin Marino, here a solution that just worked for me in a 2000 word list (would work in bigger list too).

first you need to install NordVPN and add it to the system path check this link :

https://support.nordvpn.com/Connectivity/Windows/1350897482/Connect-to-NordVPN-app-on-Windows-using-the-Command-Prompt.htm

The goal is so you can connect/disconnect and chose servers with CMD (you can do the same thing in linux) so you can cantrole theses NordVPN CMD commands through Python code.

Here is the function (please import the libraries) :

   import random

listofservers = ["South Africa", "Egypt" , "Australia", "New Zealand",  "South Korea", "Singapore", "Taiwan", "Vietnam", "Hong Kong", "Indonesia", "Thailand", "Japan", "Malaysia", "United Kingdom", "Netherlands", "Germany", "France", "Belgium", "Switzerland", "Sweden","Spain","Denmark", "Italy", "Norway", "Austria", "Romania", "Czech Republic", "Luxembourg", "Poland", "Finland", "Hungary", "Latvia", "Russia", "Iceland", "Bulgaria", "Croatia", "Moldova", "Portugal", "Albania", "Ireland", "Slovakia","Ukraine", "Cyprus", "Estonia", "Georgia", "Greece", "Serbia", "Slovenia", "Azerbaijan", "Bosnia and Herzegovina", "Macedonia","India", 'Turkey', 'Israel', 'United Arab Emirates', 'United States', 'Canada','Mexico'
,"Brazil", "Costa Rica", "Argentina", "Chile"]

def SelectServer(l):
    return random.choice(l)

def translate_text(text, dest_language="en"):
    # Used to translate using the googletrans library
    translator = googletrans.Translator()
    try:

        translation = translator.translate(text=text, dest=dest_language)

    except json.decoder.JSONDecodeError:
        # api call restriction

        print("exception !! déconection du VPN ")
        process = subprocess.Popen(["nordvpn", "-d"], shell = True ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.wait()

        time.sleep(5)

        srv = SelectServer(listofservers)

        print("sélection du serveur  : "+ srv + " et connexion")

        process = subprocess.Popen(["nordvpn", "-c", "-g", srv ], shell = True ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.wait()
        time.sleep(60)

        return translate_text(text=text, dest_language=dest_language)

    return translation.text

    #translate to EN and remove EN stopwords
    ListCapTranslated = []
    for row  in ListCaptionsCleanFiltred:
        # REINITIALIZE THE API
        newrow = translate_text(row, dest_language="en")
        ListCapTranslated.append(newrow)

ListCapTranslated

Before running the code, please add NordVPN to System path and test connecting/disconnecting on servers through CMD so you make sure everything works.

Cheers.


问:
Interrupt heavy processing
I'm facing an issue with rxjs.

Basically, I have a method that makes an http request (using Angular's HttpClientModule), do some time-consuming parsing, sorting, etc... then store the result in a BehaviorSubject.

My problem is that the request does not take very long to complete, but the parsing does (simple methods).

I can have some other calls to same method which need to interrupt (discard) the previous processing.

All this needs to be able to be cleared via a boolean.

Some representations of the process:

Interrupt

```<code>A   >-request--processing----|
A'  >--------------request--processing----|
A'' >-----------------------request--processing----|
</code>```

A is interrupted by A' and never completes

A' is interrupted by A'' and never completes

A'' completes

Clear

```<code>A      >-request--processing----|
A'     >--------------request--processing----|
switch >----------------------stop----|
</code>```

A is interrupted by A' and never completes

A' is interrupted by switch and never completes

switch blocks any new request as long as it is false

So far, I'm unable to find a way to interrupt the processing when some new request is needed or a decent way to block new requests.

I was thinking maybe making my parsing method return an observable and mergeMapping it...

Any idea is welcome.

答:
You can set you observable to a Subscription variable.

Usage example:

```<code>import { Subscription } from 'rxjs/internal/Subscription';

/...

public subscription: Subscription;

onInit() {
    this.getData();
}

getData() {
    this.subscription = this.myService.getA().subscribe(...)
}

cancelService() {
   this.subscription.unsubscribe(); // This will cancel the request
}
</code>```

Title: Interrupt heavy processing

Body:
I'm facing an issue with rxjs.

Basically, I have a method that makes an http request (using Angular's HttpClientModule), do some time-consuming parsing, sorting, etc... then store the result in a BehaviorSubject.

My problem is that the request does not take very long to complete, but the parsing does (simple methods).

I can have some other calls to same method which need to interrupt (discard) the previous processing.

All this needs to be able to be cleared via a boolean.

Some representations of the process:

Interrupt

A   >-request--processing----|
A'  >--------------request--processing----|
A'' >-----------------------request--processing----|

A is interrupted by A' and never completes

A' is interrupted by A'' and never completes

A'' completes

Clear

A      >-request--processing----|
A'     >--------------request--processing----|
switch >----------------------stop----|

A is interrupted by A' and never completes

A' is interrupted by switch and never completes

switch blocks any new request as long as it is false

So far, I'm unable to find a way to interrupt the processing when some new request is needed or a decent way to block new requests.

I was thinking maybe making my parsing method return an observable and mergeMapping it...

Any idea is welcome.

Body:
You can set you observable to a Subscription variable.

Usage example:

import { Subscription } from 'rxjs/internal/Subscription';

/...

public subscription: Subscription;

onInit() {
    this.getData();
}

getData() {
    this.subscription = this.myService.getA().subscribe(...)
}

cancelService() {
   this.subscription.unsubscribe(); // This will cancel the request
}


问:
How to get parts of a string via regular expressions in Kotlin or Java?
Suppose you have a string http://server.com/s123456 and want to get 123456 from it. Or http://server.com/s123456&a=100 and get 123456, 100. Many different situations where you want to have parts of a string.

In order to match strings I use regular expressions.

```<code>@Test
fun test() {
    val text = "http://server.com/s123456" // Source string.
    val reg = "^http://server.com/s\\d+\$".toRegex()
    assertEquals(true, reg.matches(text))

    // Try to split the string with findAll().
    val a: Sequence<MatchResult> = reg.findAll(text, 0)
    val names = a.map { it.groupValues[0] }.joinToString()
    println(names) // http://server.com/s123456
}
</code>```

But it doesn't split the source string into chars and digits, just prints: http://server.com/s123456. Is there a way to write a mask, so that we can retrieve numbers (or any other parts) from the string?

答:
Thanks to @Eraklon and @moys I wrote a similar answer.</p>

```<code>@Test
fun test1() {
    val text = "http://server.com/s123456"
    val reg = "^http://server.com/s(\\d+)\$".toRegex()
    val a = reg.findAll(text, 0)
    val names = a.map { it.groupValues[1] }.joinToString()
    println(names)
    // 123456
    assertEquals(true, reg.matches(text))
}

@Test
fun test2() {
    val a = "http://server.com/s123456"
    val b = "http://server.com/s123456&a=100"
    val c = "http://server.com/s122&&&"
    val d = "http://server.com/s1234!56&a=100terere"
    val e = "http://server.com/s"
    val f = "http://server.com"
    val reg = "(\\d+)".toRegex()

    val list = listOf(a, b, c, d, e, f)
    list.map { item ->
        val groups: Sequence<MatchResult> = reg.findAll(item, 0)
        val names = groups.map { it.groupValues[1] }.joinToString()
        println(names)
    }
    // Output:
    // 123456
    // 123456, 100
    // 122
    // 1234, 56, 100
    //
    //

    val groups: Sequence<MatchResult> = reg.findAll(e, 0)
    val names = groups.map { it.groupValues[1] }.firstOrNull()
    println(names)
    // null
}
</code>```

Body:
Suppose you have a string http://server.com/s123456 and want to get 123456 from it. Or http://server.com/s123456&a=100 and get 123456, 100. Many different situations where you want to have parts of a string.

In order to match strings I use regular expressions.

@Test
fun test() {
    val text = "http://server.com/s123456" // Source string.
    val reg = "^http://server.com/s\\d+\$".toRegex()
    assertEquals(true, reg.matches(text))

    // Try to split the string with findAll().
    val a: Sequence<MatchResult> = reg.findAll(text, 0)
    val names = a.map { it.groupValues[0] }.joinToString()
    println(names) // http://server.com/s123456
}

But it doesn't split the source string into chars and digits, just prints: http://server.com/s123456. Is there a way to write a mask, so that we can retrieve numbers (or any other parts) from the string?

Body:
Thanks to @Eraklon and @moys I wrote a similar answer.

@Test
fun test1() {
    val text = "http://server.com/s123456"
    val reg = "^http://server.com/s(\\d+)\$".toRegex()
    val a = reg.findAll(text, 0)
    val names = a.map { it.groupValues[1] }.joinToString()
    println(names)
    // 123456
    assertEquals(true, reg.matches(text))
}

@Test
fun test2() {
    val a = "http://server.com/s123456"
    val b = "http://server.com/s123456&a=100"
    val c = "http://server.com/s122&&&"
    val d = "http://server.com/s1234!56&a=100terere"
    val e = "http://server.com/s"
    val f = "http://server.com"
    val reg = "(\\d+)".toRegex()

    val list = listOf(a, b, c, d, e, f)
    list.map { item ->
        val groups: Sequence<MatchResult> = reg.findAll(item, 0)
        val names = groups.map { it.groupValues[1] }.joinToString()
        println(names)
    }
    // Output:
    // 123456
    // 123456, 100
    // 122
    // 1234, 56, 100
    //
    //

    val groups: Sequence<MatchResult> = reg.findAll(e, 0)
    val names = groups.map { it.groupValues[1] }.firstOrNull()
    println(names)
    // null
}


问:
Undefined reference when using "Hello world" of Irrlicht library
I'm trying to compile the very first code given by Irrlicht library website.

As said in the title, I get an undefined reference. I'm using 8.2 netbeans IDE.

This is what I've done so far :
Installed Irrlicht library from the Linux repository (I'm using Ubuntu 18.04).
Using these command lines : sudo apt-get install libirrlicht1.8 libirrlicht1.8-dbg libirrlicht-dev libirrlicht-doc

In the "project properties", I've added the include directory, as well as the include headers (e.g all the files contained in /usr/include/irrlicht. Also, in the "Additional Options" (the linker part, I guess ?) , I've seen online that I should add -lIrrlicht command line, and it still got me the undefined reference.

I've tried also the following command line : -L /usr/include/irrlicht -lIrrlicht, still got me the undefined reference.

I know that the compiler finds the library, as it does not make a compilation error saying that it doesn't know "irrlicht.h", so the problem is coming from the linker. What command line does the linker expects ?

Note : I'm not able to make any update. Talking about irrlicht, it seems that I have 363 packages outdated. Could the problem be from there ?

Edit : Here is the minimum code, as requested. There is no point showing it, as the error comes from the linker command line :

```<code>#include <cstdlib>
#include <iostream>
#include <irrlicht.h>

using namespace std;
using namespace irr;
using namespace core;

int main(int argc, char** argv) {

    IrrlichtDevice *device=createDevice(video::EDT_SOFTWARE,dimension2d<u32>(640,480),16,false,false,false,0);
return 0;
}
</code>```

答:
I had a similar problem with another library. I fixed it by changing the path in the linker?

according to https://de.wikibooks.org/wiki/Irrlicht_-_from_Noob_to_Pro:_C%2B%2B_f%C3%BCr_Irrlicht_einrichten

you have to link lIrrlicht like:

```<code>LIBS += -L/.../Irrlicht/irrlicht-1.7.1/lib/Linux
LIBS += -lIrrlicht
</code>```

instead of -L /usr/include/irrlicht -lIrrlicht (for unix).

Did you try that?

Body:
I'm trying to compile the very first code given by Irrlicht library website.

As said in the title, I get an undefined reference. I'm using 8.2 netbeans IDE.

This is what I've done so far :
Installed Irrlicht library from the Linux repository (I'm using Ubuntu 18.04).
Using these command lines : sudo apt-get install libirrlicht1.8 libirrlicht1.8-dbg libirrlicht-dev libirrlicht-doc

In the "project properties", I've added the include directory, as well as the include headers (e.g all the files contained in /usr/include/irrlicht. Also, in the "Additional Options" (the linker part, I guess ?) , I've seen online that I should add -lIrrlicht command line, and it still got me the undefined reference.

I've tried also the following command line : -L /usr/include/irrlicht -lIrrlicht, still got me the undefined reference.

I know that the compiler finds the library, as it does not make a compilation error saying that it doesn't know "irrlicht.h", so the problem is coming from the linker. What command line does the linker expects ?

Note : I'm not able to make any update. Talking about irrlicht, it seems that I have 363 packages outdated. Could the problem be from there ?

Edit : Here is the minimum code, as requested. There is no point showing it, as the error comes from the linker command line :

#include <cstdlib>
#include <iostream>
#include <irrlicht.h>

using namespace std;
using namespace irr;
using namespace core;

int main(int argc, char** argv) {

    IrrlichtDevice *device=createDevice(video::EDT_SOFTWARE,dimension2d<u32>(640,480),16,false,false,false,0);
return 0;
}

Body:
I had a similar problem with another library. I fixed it by changing the path in the linker?

according to https://de.wikibooks.org/wiki/Irrlicht_-_from_Noob_to_Pro:_C%2B%2B_f%C3%BCr_Irrlicht_einrichten

you have to link lIrrlicht like:

LIBS += -L/.../Irrlicht/irrlicht-1.7.1/lib/Linux
LIBS += -lIrrlicht

instead of -L /usr/include/irrlicht -lIrrlicht (for unix).

Did you try that?


问:
How can I group and sum multiple columns in CSV file?
I'm still new to python and pandas and currently trying to get sum of multiple columns in a CSV file.

I have a CSV file with columns that I want to sum unitCount, orderCount, invoiceCount:

```<code>     date       id   name   unitCount   orderCount   invoiceCount
 2020-02-12     1   Guitar     200          100           200
 2020-02-12     2   Drums      300          200           100
 2020-02-12     3   Piano      400          700           300
 2020-02-11     1   Guitar     100          500           300
 2020-02-11     2   Drums      200          400           400
 2020-02-11     3   Piano      300          300           100
</code>```

My desired output would be a CSV file with sum of those last 3 columns (grouped by ID) and linked to the latest date only:

```<code>     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
 2020-02-12     1   Guitar        300              600                   500
 2020-02-12     2   Drums         500              600                   500
 2020-02-12     3   Piano         700              1000                  400
</code>```

Would someone be able to help?

so far I was trying the below, but it doesn't work for me. Would be possible to add groupby to the first line of the below code? Or I started completely wrong? Thanks!

```<code>df = pd.read_csv(r'path/to/myfile.csv', sep=';').sum()
df.to_csv(r'path/to/myfile_sum.csv')
</code>```

答:
You simply need to call sum() on the groupby object, then rename the column names accordingly and finally write the resulting dataframe to a csv file.

The following should do the trick:

```<code>df = pd.read_csv(r'path/to/myfile.csv', sep=';')

df.groupby(['id', 'name'])['unitCount', 'orderCount', 'invoiceCount'] \
  .sum() \
  .rename(columns={'unitCount':'total_unitCount', 'orderCount' : 'total_orderCount', 'invoiceCount': 'total_invoiceCount'}) \
  .to_csv('path/to/myoutputfile_sum.csv', sep=';')
</code>```

Body:
I'm still new to python and pandas and currently trying to get sum of multiple columns in a CSV file.

I have a CSV file with columns that I want to sum unitCount, orderCount, invoiceCount:

     date       id   name   unitCount   orderCount   invoiceCount
 2020-02-12     1   Guitar     200          100           200
 2020-02-12     2   Drums      300          200           100
 2020-02-12     3   Piano      400          700           300
 2020-02-11     1   Guitar     100          500           300
 2020-02-11     2   Drums      200          400           400
 2020-02-11     3   Piano      300          300           100

My desired output would be a CSV file with sum of those last 3 columns (grouped by ID) and linked to the latest date only:

     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
 2020-02-12     1   Guitar        300              600                   500
 2020-02-12     2   Drums         500              600                   500
 2020-02-12     3   Piano         700              1000                  400

Would someone be able to help?

so far I was trying the below, but it doesn't work for me. Would be possible to add groupby to the first line of the below code? Or I started completely wrong? Thanks!

df = pd.read_csv(r'path/to/myfile.csv', sep=';').sum()
df.to_csv(r'path/to/myfile_sum.csv')

Body:
You simply need to call sum() on the groupby object, then rename the column names accordingly and finally write the resulting dataframe to a csv file.

The following should do the trick:

df = pd.read_csv(r'path/to/myfile.csv', sep=';')

df.groupby(['id', 'name'])['unitCount', 'orderCount', 'invoiceCount'] \
  .sum() \
  .rename(columns={'unitCount':'total_unitCount', 'orderCount' : 'total_orderCount', 'invoiceCount': 'total_invoiceCount'}) \
  .to_csv('path/to/myoutputfile_sum.csv', sep=';')


问:
Get response variables from array
I am trying to output all the users I have created in my Marqeta API Sandbox environment. I'm making a GET request to /users through my custom marqetaAPI function that handles each request type.

Call to custom API function:

```<code>$responseData = MarqetaAPI('GET', 'https://sandbox-
api.marqeta.com/v3/users/');
</code>```

Custom function API Call with cURL:

```<code>function marqetaAPI($method, $url, $data, $headers = false) {

//credentials
$uname='xxxxx-xxxxx-xxxx-xxxx';
$pword='xxxxx-xxxxx-xxxx-xxxx';

$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
if (!$headers) {
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
// 'APIKEY: $uname:$pword',
'Content-Type: application/json',
));
}else {
curl_setopt($curl, CURLOPT_HTTPHEADER, array (
// 'APIKEY: $uname:$pword',
'Content-Type: application/json',
));
}

curl_setopt($curl, CURLOPT_USERPWD, "$uname:$pword");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}
</code>```

Decoding response array with json_decode:

```<code>$responseArray = json_decode($data, true);
</code>```

Here is the json decoded array:

```<code>Array
(
    [count] => 5
    [start_index] => 0
    [end_index] => 4
    [is_more] => 1
    [data] => Array
        (
            [0] => Array
                (
                    [token] => f7b17921-8f77-4896-82ae-1dc3114ff3e7
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-05T15:20:49Z
                    [last_modified_time] => 2020-02-05T15:20:49Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

            [1] => Array
                (
                    [token] => 638ab57b-bffa-48a7-938f-eae5f3620bd5
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-05T15:19:55Z
                    [last_modified_time] => 2020-02-05T15:19:55Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

            [2] => Array
                (
                    [token] => 3242d309-1a53-493e-9bfd-dd6351cbb851
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-04T16:24:13Z
                    [last_modified_time] => 2020-02-04T16:24:13Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

            [3] => Array
                (
                    [token] => 67a045d1-87b7-40fd-8a0f-9c6b88a7f10b
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-04T16:23:51Z
                    [last_modified_time] => 2020-02-04T16:23:51Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

            [4] => Array
                (
                    [token] => cb12cd70-a119-42a9-ba22-90b88a85f216
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-04T16:17:25Z
                    [last_modified_time] => 2020-02-04T16:17:25Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

        )

)
</code>```

I'm calling the response array nested 'data' key here. The result is 5 arrays (one for each user)

```<code>foreach($responseArray['data'] as $key=>$value) {
 echo $key . " " . $value . "<br>";
};

//Result
    0 Array
    1 Array
    2 Array
    3 Array
    4 Array
</code>```

Say I wanted the first users keys and values I would do:

```<code>foreach($response['data'][0] as $key=>$value) {
    echo $key . " " . $value . "<br>";
};

//Result
token f7b17921-8f77-4896-82ae-1dc3114ff3e7
active 1
uses_parent_account
corporate_card_holder
created_time 2020-02-05T15:20:49Z
last_modified_time 2020-02-05T15:20:49Z
metadata Array
account_holder_group_token DEFAULT_AHG
status ACTIVE
</code>```

Now lets say i want to echo each users keys and values I would do something like:

```<code>//loop over each $response['data'] array
foreach($response['data'] as $userArrays) {

  //loop over each users keys and values
  foreach($userArrays as $key=>$value) {

    echo $key . " " . $value . "<br>";
  };
};
</code>```

with expected output:

```<code>First User:
token f7b17921-8f77-4896-82ae-1dc3114ff3e7
active 1
uses_parent_account
corporate_card_holder
created_time 2020-02-05T15:20:49Z
last_modified_time 2020-02-05T15:20:49Z
metadata Array
account_holder_group_token DEFAULT_AHG
status ACTIVE

Second User:
token 67a045d1-87b7-40fd-8a0f-9c6b88a7f10b
active 1
uses_parent_account
corporate_card_holder
created_time 2020-02-05T15:20:49Z
last_modified_time 2020-02-05T15:20:49Z
metadata Array
account_holder_group_token DEFAULT_AHG
status ACTIVE

etc.
</code>```

答:
If you only want to echo all arrays in variable depth, then this function is a solution:

```<code>function echo_recursive( &$array )  {
  foreach( $array as $key => &$value )  {
    if( is_array( $value ) )  {
      echo_recursive( $value );
    } else {
      echo "$key: $value<br>";
      // or do whatever you want with these
    }
  }
}

// USAGE:
// print_recursive($responseArray);
</code>```

Based on your comment above - echo only one key:

```<code>foreach( $responseArray['data'] as $data )  {
  echo "token: " . $data['token'] . "<br>";
  // echo "active: " . $data['active'] . "<br>";
  // echo "created_time: " . $data['created_time'] . "<br>";
  // and so on...
}
</code>```

Or if you want to echo all the data:

```<code>foreach( $responseArray['data'] as $data )  {
  foreach( $data as $key => $value )  {
    echo "$key: $value<br>";
  }
}
</code>```

Title: Get response variables from array

Body:
I am trying to output all the users I have created in my Marqeta API Sandbox environment. I'm making a GET request to /users through my custom marqetaAPI function that handles each request type.

Call to custom API function:

$responseData = MarqetaAPI('GET', 'https://sandbox-
api.marqeta.com/v3/users/');

Custom function API Call with cURL:

function marqetaAPI($method, $url, $data, $headers = false) {

//credentials
$uname='xxxxx-xxxxx-xxxx-xxxx';
$pword='xxxxx-xxxxx-xxxx-xxxx';

$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
if (!$headers) {
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
// 'APIKEY: $uname:$pword',
'Content-Type: application/json',
));
}else {
curl_setopt($curl, CURLOPT_HTTPHEADER, array (
// 'APIKEY: $uname:$pword',
'Content-Type: application/json',
));
}

curl_setopt($curl, CURLOPT_USERPWD, "$uname:$pword");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}

Decoding response array with json_decode:

$responseArray = json_decode($data, true);

Here is the json decoded array:

Array
(
    [count] => 5
    [start_index] => 0
    [end_index] => 4
    [is_more] => 1
    [data] => Array
        (
            [0] => Array
                (
                    [token] => f7b17921-8f77-4896-82ae-1dc3114ff3e7
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-05T15:20:49Z
                    [last_modified_time] => 2020-02-05T15:20:49Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

            [1] => Array
                (
                    [token] => 638ab57b-bffa-48a7-938f-eae5f3620bd5
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-05T15:19:55Z
                    [last_modified_time] => 2020-02-05T15:19:55Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

            [2] => Array
                (
                    [token] => 3242d309-1a53-493e-9bfd-dd6351cbb851
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-04T16:24:13Z
                    [last_modified_time] => 2020-02-04T16:24:13Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

            [3] => Array
                (
                    [token] => 67a045d1-87b7-40fd-8a0f-9c6b88a7f10b
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-04T16:23:51Z
                    [last_modified_time] => 2020-02-04T16:23:51Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

            [4] => Array
                (
                    [token] => cb12cd70-a119-42a9-ba22-90b88a85f216
                    [active] => 1
                    [uses_parent_account] =>
                    [corporate_card_holder] =>
                    [created_time] => 2020-02-04T16:17:25Z
                    [last_modified_time] => 2020-02-04T16:17:25Z
                    [metadata] => Array
                        (
                        )

                    [account_holder_group_token] => DEFAULT_AHG
                    [status] => ACTIVE
                )

        )

)

I'm calling the response array nested 'data' key here. The result is 5 arrays (one for each user)

foreach($responseArray['data'] as $key=>$value) {
 echo $key . " " . $value . "
";
};

//Result
    0 Array
    1 Array
    2 Array
    3 Array
    4 Array

Say I wanted the first users keys and values I would do:

foreach($response['data'][0] as $key=>$value) {
    echo $key . " " . $value . "
";
};

//Result
token f7b17921-8f77-4896-82ae-1dc3114ff3e7
active 1
uses_parent_account
corporate_card_holder
created_time 2020-02-05T15:20:49Z
last_modified_time 2020-02-05T15:20:49Z
metadata Array
account_holder_group_token DEFAULT_AHG
status ACTIVE

Now lets say i want to echo each users keys and values I would do something like:

//loop over each $response['data'] array
foreach($response['data'] as $userArrays) {

  //loop over each users keys and values
  foreach($userArrays as $key=>$value) {

    echo $key . " " . $value . "
";
  };
};

with expected output:

First User:
token f7b17921-8f77-4896-82ae-1dc3114ff3e7
active 1
uses_parent_account
corporate_card_holder
created_time 2020-02-05T15:20:49Z
last_modified_time 2020-02-05T15:20:49Z
metadata Array
account_holder_group_token DEFAULT_AHG
status ACTIVE

Second User:
token 67a045d1-87b7-40fd-8a0f-9c6b88a7f10b
active 1
uses_parent_account
corporate_card_holder
created_time 2020-02-05T15:20:49Z
last_modified_time 2020-02-05T15:20:49Z
metadata Array
account_holder_group_token DEFAULT_AHG
status ACTIVE

etc.

Body:
If you only want to echo all arrays in variable depth, then this function is a solution:

function echo_recursive( &$array )  {
  foreach( $array as $key => &$value )  {
    if( is_array( $value ) )  {
      echo_recursive( $value );
    } else {
      echo "$key: $value<br>";
      // or do whatever you want with these
    }
  }
}

// USAGE:
// print_recursive($responseArray);

Based on your comment above - echo only one key:

foreach( $responseArray['data'] as $data )  {
  echo "token: " . $data['token'] . "<br>";
  // echo "active: " . $data['active'] . "<br>";
  // echo "created_time: " . $data['created_time'] . "<br>";
  // and so on...
}

Or if you want to echo all the data:

foreach( $responseArray['data'] as $data )  {
  foreach( $data as $key => $value )  {
    echo "$key: $value<br>";
  }
}


问:
How do you make a dynamic range function in excel with a dynamic start and end cell?
I have n export from a database of financial statement information. It only includes non zero rows. I am trying to use INDEX(MATCH) to copy the information and calculate key figures, KPI's etc. So far no problem.

The problem is the balance sheet contains multiple lines with the same text e.g. 'other receivables', so the basic INDEX(MATCH) will always take the first value. I can't solve it by counting the number of occurences either as if for example 'long term receivables' lacks 'other receivables' then that row is missing.

The solution I tried was using INDEX(MATCH) functions inside the INDEX(Match) 'array' section (first argument). It works fine if only the end point of the array is dynamic, but seizes to work when the starting value is dynamic as well. The idea is to isolate the 'other receivables' in e.g. short term receivables by searching an array starting from 'Short term receivables' and ending in 'Total short term receivables'.

To sum it up, the question is simple: How does one code an array with a dynamic start and end value?

答:
See

https://exceljet.net/formula/get-address-of-lookup-result

You can get address of starting cell matching criteria (Short term receivables) and ending cell matching criteria (Total short term receivables) and you can thus create dynamic range.

Once get the starting cell dynamically you can select dynamic range using indirect (As the result of the following will be a string) and offset.

Referring ti the same link above
Following is the formula in H11
=CELL("address",INDEX(C:C,MATCH("Short Term Receivables",C:C,0),1))&":"&CELL("address",INDEX(C:C,MATCH("Total Short Term Receivables",C:C,0),1))


问:
X++ select statement on related tabled
I need help to get data from prodtable that are related to salesline.
My task is to get all Prodid that are related to current salesid. Related field prodtable.inventrefid == salesline.salesid. But the values are a bit differend to join so I get no data. Inventrefid have eg. ZPR0000011 and sales id is ZS00000011.</p>

```<code>salesline tablebuffer = this.cursor();
while select ProdId, CollectRefProdId from prodtable where prodtable.inventrefid == 'ZPR00000165'
</code>```

答:
The main problem I immediately see is:

prodtable.inventrefid == 'ZPR00000165'

inventRefId would be your SalesId, which is ZS00000011 not your ProdId.

An example of a more correct query is below. You can refine it by joining the two selects together so you get all related ProdTable records to all SalesLine records for a given SalesId and you can also specify fields in the queries so that you are not returning the entire buffer.

SalesLine           salesLine;
ProdTable           prodTable;

/*
This just chooses the first sales line with that salesid. You would need to join these together
if you wanted to do all sales lines in one query.
*/
select firstOnly salesLine
    where salesLine.SalesStatus                 == SalesStatus::Backorder       &&
          salesLine.SalesId                     == 'ZS00000011';

while select prodTable
    where prodTable.InventRefTransId            == salesLine.InventTransId      &&
          prodTable.InventRefId                 == salesLine.SalesId            &&
          prodTable.InventRefType               == InventRefType::Sales
{
    info(strFmt("Found related ProdTable record %1 - %2 (%3)", prodTable.ProdId, prodTable.CollectRefProdId, prodTable.RecId));
}
```

Title: X++ select statement on related tabled

Body:
I need help to get data from prodtable that are related to salesline.
My task is to get all Prodid that are related to current salesid. Related field prodtable.inventrefid == salesline.salesid. But the values are a bit differend to join so I get no data. Inventrefid have eg. ZPR0000011 and sales id is ZS00000011.

salesline tablebuffer = this.cursor();
while select ProdId, CollectRefProdId from prodtable where prodtable.inventrefid == 'ZPR00000165'


问:
Check for condition in GROUP BY?
Take this example data:

```<code>ID    Status    Date
1     Pending   2/10/2020
2     Pending   2/10/2020
3     Pending   2/10/2020
2     Pending   2/10/2020
2     Pending   2/10/2020
1     Complete  2/15/2020
</code>```

I need an SQL statement that will group all the data but bring back the current status. So for ID 1 the group by needs a condition that only returns the Completed row and also returned the pending rows for ID 2 and 3.

I am not 100% how to write in the condition for this.

Maybe something like:

```<code>SELECT ID, Status, Date
FROM table
GROUP BY ID, Status, Date
ORDER BY ID
</code>```

The problem with this is the resulting data would look like:

```<code>ID    Status    Date
1     Pending   2/10/2020
1     Complete  2/15/2020
2     Pending   2/10/2020
3     Pending   2/10/2020
</code>```

But I need:

```<code>ID    Status    Date
1     Complete  2/15/2020
2     Pending   2/10/2020
3     Pending   2/10/2020
</code>```

What can I do to check for the Completed status so I can only return Completed in the group by?

答:
To use Date as 'last row indicator', you can:

```<code>DECLARE @Src TABLE (
    ID int,
    Status varchar(20),
    Date Date
)

INSERT @Src VALUES
(1, 'Pending' ,'2/10/2020'),
(1, 'Complete' ,'2/15/2020'),
(2, 'Pending' ,'2/10/2020'),
(3, 'Pending' ,'2/10/2020');

SELECT TOP 1 WITH TIES *
FROM @Src
ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC)
</code>```

Result:

```<code>ID          Status               Date
----------- -------------------- ----------
1           Complete             2020-02-15
2           Pending              2020-02-10
3           Pending              2020-02-10
</code>```

Title: Check for condition in GROUP BY?

Body:
Take this example data:

ID    Status    Date
1     Pending   2/10/2020
2     Pending   2/10/2020
3     Pending   2/10/2020
2     Pending   2/10/2020
2     Pending   2/10/2020
1     Complete  2/15/2020

I need an SQL statement that will group all the data but bring back the current status. So for ID 1 the group by needs a condition that only returns the Completed row and also returned the pending rows for ID 2 and 3.

I am not 100% how to write in the condition for this.

Maybe something like:

SELECT ID, Status, Date
FROM table
GROUP BY ID, Status, Date
ORDER BY ID

The problem with this is the resulting data would look like:

ID    Status    Date
1     Pending   2/10/2020
1     Complete  2/15/2020
2     Pending   2/10/2020
3     Pending   2/10/2020

But I need:

ID    Status    Date
1     Complete  2/15/2020
2     Pending   2/10/2020
3     Pending   2/10/2020

What can I do to check for the Completed status so I can only return Completed in the group by?

Body:
To use Date as 'last row indicator', you can:

DECLARE @Src TABLE (
    ID int,
    Status varchar(20),
    Date Date
)

INSERT @Src VALUES
(1, 'Pending' ,'2/10/2020'),
(1, 'Complete' ,'2/15/2020'),
(2, 'Pending' ,'2/10/2020'),
(3, 'Pending' ,'2/10/2020');

SELECT TOP 1 WITH TIES *
FROM @Src
ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC)

Result:

ID          Status               Date
----------- -------------------- ----------
1           Complete             2020-02-15
2           Pending              2020-02-10
3           Pending              2020-02-10


问:
Firebase Notifications not being delivered if sent other than firebase console
I am facing a really strange issue, the notifications sent from the Firebase Console are being delivered properly so it means the project is configured and certificates are correct, but when I send notification from the app it doesn't work. I am using the following method to send notifications.

```<code>func sendPushNotification(to token: String, title: String, body: String, Type: String) {

        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] =
            [
                "message" :[
                    "to" : token,
                    "notification" : ["title" : title, "body" : body],
                    "data" : ["notification_type": Type]
                ],
                "to" : token
            ]

        print(paramString)
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAApQ9EAjg:XXXX", forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict))")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()

    }
</code>```

I have also tried sending through curl with the following method

```<code><?php
/**
 * Created by PhpStorm.
 * User: ussaidiqbal
 * Date: 2020-02-17
 * Time: 19:45
 */

$url = "https://fcm.googleapis.com/fcm/send";
$token = "eMIK6wGOTUUutqp62vEIr-:XXXXXX";
$serverKey = 'AIzaSyCJFUydXXXXXXXXXX';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,

    "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
</code>```

I also have tried to send through PostMan using the following payload

```<code>{
    "notification":{
        "title": "XXXXX",
        "body": "XXXXX"
    },
  "to": "XXXXXXX"
}
</code>```

This is the response of the request

```<code>{
    "multicast_id": 36126XXXXXXXX,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1581960379105057~~~~~~~~~~"
        }
    ]
}
</code>```

None of the above method seems to be working, What am I doing wrong?
I have tried both the Legacy server key and Server key but no luck. Has anyone ever faced such an issue?

答:
```<code>struct NotificationStruct: Codable {
    var notification: NotificationBodyStruct?
    var to: String?
    var time_to_live = 60000
}

struct NotificationBodyStruct: Codable {
    var title: String?
    var text: String?
    var sound: String?
}

func sendNotificationtoken: String, name: String, completion: @escaping(Bool) -> Void) {
    do {
        let noti = NotificationStruct(notification: NotificationBodyStruct(title: name, text: text, sound: "default"), to: "\(token)", time_to_live: 6000)
        let body = try JSONEncoder().encode(noti)

        makeConnection(body: body) { (success) in
            DispatchQueue.main.async {
                completion(true)
            }
        }
    } catch {
        print("sendNotification \(error.localizedDescription)")
        DispatchQueue.main.async {
            completion(false)
        }
    }
}

private func makeConnection(body: Data, completion: @escaping(Bool) -> Void) {
    guard let url = URL(string: "http://gcm-http.googleapis.com/gcm/send") else {
            completion(false)
            return
    }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = ["Content-Type": "application/json", "Authorization": "key=A**YOUR_KEY**A"]
    request.httpBody = body

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
        guard error == nil else {
            print("Error NotificationHelper ", error?.localizedDescription ?? "")
            completion(false)
            return
        }

        guard let httpResponse = response as? HTTPURLResponse else {
            print("httpResponse error NotificationHelper ")
            completion(false)
            return
        }

        guard httpResponse.statusCode  < 500 else {
            print("Error NotificationHelper < 500 \(httpResponse)", response ?? "" )
            completion(false)
            return
        }

        guard (httpResponse.statusCode >= 200 && httpResponse.statusCode <= 299) else {
            print("error NotificationHelper  >= 200 && httpResponse.statusCode <= 299 \(httpResponse)", response ?? "" )
            completion(false)
            return
        }

        guard let _ = data  else {
            print("Problem with Data NotificationHelper ")
            completion(false)
            return
        }

        completion(true)
    })
    dataTask.resume()
}
</code>```

Body:
I am facing a really strange issue, the notifications sent from the Firebase Console are being delivered properly so it means the project is configured and certificates are correct, but when I send notification from the app it doesn't work. I am using the following method to send notifications.

func sendPushNotification(to token: String, title: String, body: String, Type: String) {

        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] =
            [
                "message" :[
                    "to" : token,
                    "notification" : ["title" : title, "body" : body],
                    "data" : ["notification_type": Type]
                ],
                "to" : token
            ]

        print(paramString)
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAApQ9EAjg:XXXX", forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict))")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()

    }

I have also tried sending through curl with the following method

<?php
/**
 * Created by PhpStorm.
 * User: ussaidiqbal
 * Date: 2020-02-17
 * Time: 19:45
 */

$url = "https://fcm.googleapis.com/fcm/send";
$token = "eMIK6wGOTUUutqp62vEIr-:XXXXXX";
$serverKey = 'AIzaSyCJFUydXXXXXXXXXX';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,

    "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);

I also have tried to send through PostMan using the following payload

{
    "notification":{
        "title": "XXXXX",
        "body": "XXXXX"
    },
  "to": "XXXXXXX"
}

This is the response of the request

{
    "multicast_id": 36126XXXXXXXX,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1581960379105057~~~~~~~~~~"
        }
    ]
}

None of the above method seems to be working, What am I doing wrong?
I have tried both the Legacy server key and Server key but no luck. Has anyone ever faced such an issue?