问:
R: Trying to recreate mean-median difference gerrymander tests
I'm trying to recreate the mean-median difference test described here: Archive of NYT article. I've downloaded House data from MIT's Election Lab, and pared it down to the 2012 Pennsylvania race. Using dplyr, I whittled it down to the relevant columns, and it now looks something like this:

```<code>Rows: 42
Columns: 5
$ district       <dbl> 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 1~
$ party          <chr> "REPUBLICAN", "DEMOCRAT", "INDEPENDENT", "REPUBLICAN", "DEMOCRAT", "DEMOCRAT", ~
$ candidatevotes <dbl> 41708, 235394, 4829, 33381, 318176, 123933, 165826, 12755, 6210, 181603, 11524,~
$ totalvotes     <dbl> 277102, 277102, 356386, 356386, 356386, 302514, 302514, 302514, 303980, 303980,~
$ pct_votes      <dbl> 15.051497, 84.948503, 1.354991, 9.366530, 89.278479, 40.967691, 54.815975, 4.21~
</code>```

Each row represents a district candidate. The final column was created using mutate, and represents the percentage of the vote in that district that went to the candidate. Now, I can find the median and mean democratic vote with

```<code>PA2012_house_dem <- PA2012_house %>% filter(party == "DEMOCRAT")
obs_median <- median(PA2012_house_dem$pct_votes)
obs_mean <- mean(PA2012_house_dem$pct_votes)
obs_median - obs_mean
</code>```

What's giving me fits is calculating the "zone of chance". What I'd like to do is some kind of Monte Carlo simulation of taking each voter and randomly assigning them to a district, so that the number of voters in each district is unchanged, the number of total votes for each party is unchanged, but the proportion of Republican and Democratic (and other parties) in each district is random, as in a permutation test. The mean Democratic vote should be unchanged, but I can't figure out a good way to carry out this randomization so that I can calculate the median district's Democratic vote percentage.

Thanks in advance for your help!

Edit for clarification: I'd like to do the randomization, say, 10,000 times, and for each of those trials, calculate the median-mean difference. The result should then, ideally, be a vector or data frame with 10,000 rows, that I can then turn into a histogram or something.

EDIT 2 -- PARTIAL SOLUTION:

I have some code that runs, but it's not giving me a reasonable answer. Using dplyr, I've filtered out all but the DEMOCRAT votes, so that each row just gives me the Democrat vote share for a single district.

```<code>Rows: 18
Columns: 5
$ district       <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18
$ party          <chr> "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCR~
$ candidatevotes <dbl> 235394, 318176, 123933, 104643, 104725, 143803, 143509, 152859, 105128, 94227, 118231, 163589, 209901, ~
$ totalvotes     <dbl> 277102, 356386, 302514, 303980, 282465, 335528, 353451, 352238, 274305, 273790, 285198, 338941, 303819,~
$ pct_votes      <dbl> 84.94850, 89.27848, 40.96769, 34.42430, 37.07539, 42.85872, 40.60223, 43.39651, 38.32522, 34.41579, 41.~
</code>```

This is saved as PA2012_reduced_dem.

Now, here is my code:

```<code>require(mosaic) # for the tally() function
data <- PA2012_reduced_dem
B <- 100
samples_diff <- vector("numeric", B)
samples_mean <- vector("numeric", B)
samples_median <- vector("numeric", B)

for(samp in 1:B) {
data_w_sample <- mutate(data, sample_vote = tally(sample(district, sum(candidatevotes),replace=T, prob = totalvotes)))
  data_w_sample <- mutate(data_w_sample, sample_vote_pct = (sample_vote / totalvotes *100))
  mean_sample <- weighted.mean(data_w_sample$sample_vote_pct, w = data_w_sample$totalvotes)
  median_sample <- median(data_w_sample$sample_vote_pct)
  diff_mean_median <- mean_sample - median_sample
  samples_diff[samp] <- diff_mean_median
  samples_mean[samp] <- mean_sample
  samples_median[samp] <- median_sample
}

samples <- data.frame(samples_mean,samples_median,samples_diff)
</code>```

The idea is that I'm randomly placing each Democrat voter in a district, weighted by the total number of votes per district. Since I have the total vote as a variable, I can compute the share of vote in each district that goes to the Democrat (I'm ignoring independent and other party votes).

Obviously, this is slow, because each trial is sampling for every single Democrat vote (roughly 2.8 million), so I'm only running 100 trials right now.

However, my Monte Carlo simulations are finding a very small "zone of chance" around the mean, the median is only about 0.05 percent above or below the mean. Again, I'm only running 100 trials, but I was expecting a wider zone of chance.

答:
I figured it out! Randomly placing voters in each district is not correct, and honestly it was pretty silly of me to do so. Instead, I had to use dplyr to create a data frame with the number of Democrat and Republican votes in each of the 435 House districts, one district per row. Then, I followed the advice on page 12 of this paper. I created samples of 18 districts sampled from this 435-row data frame, rejecting them if the mean vote share was more than 1 percent away from that of PA. The results have a much nicer 95% confidence interval, that matches the results of the original article.

```<code>data <- house_2012_reduced
# created with dplyr, contains total and percentage of votes
# for Democrats and Republicans.
B <- 100000
del_districts <- 18 # 18 districts in PA
samples_diff <- vector("numeric", B)
samples_mean <- vector("numeric", B)
samples_median <- vector("numeric", B)

for(samp in 1:B) {
  sample_delegation <- sample_n(data, del_districts)
  sample_delegation_pct_dem_mean <- weighted.mean(sample_delegation$pct_dem_votes, w = sample_delegation$total_votes)
  sample_delegation_pct_dem_median <- median(sample_delegation$pct_dem_votes)
  if(near(mean_dem_pct_PA, sample_delegation_pct_dem_mean, 1)){
    samples_mean[samp] <- sample_delegation_pct_dem_mean
    samples_median[samp] <- sample_delegation_pct_dem_median
    samples_diff[samp] <- (sample_delegation_pct_dem_mean - sample_delegation_pct_dem_median)
  }
}

samples <- data.frame(samples_mean,samples_median,samples_diff)
samples <- filter_all(samples, any_vars(. != 0))
quantile(samples$samples_median, c(0.025,0.975))
</code>```

Body:
I'm trying to recreate the mean-median difference test described here: Archive of NYT article. I've downloaded House data from MIT's Election Lab, and pared it down to the 2012 Pennsylvania race. Using dplyr, I whittled it down to the relevant columns, and it now looks something like this:

Rows: 42
Columns: 5
$ district       <dbl> 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 1~
$ party          <chr> "REPUBLICAN", "DEMOCRAT", "INDEPENDENT", "REPUBLICAN", "DEMOCRAT", "DEMOCRAT", ~
$ candidatevotes <dbl> 41708, 235394, 4829, 33381, 318176, 123933, 165826, 12755, 6210, 181603, 11524,~
$ totalvotes     <dbl> 277102, 277102, 356386, 356386, 356386, 302514, 302514, 302514, 303980, 303980,~
$ pct_votes      <dbl> 15.051497, 84.948503, 1.354991, 9.366530, 89.278479, 40.967691, 54.815975, 4.21~

Each row represents a district candidate. The final column was created using mutate, and represents the percentage of the vote in that district that went to the candidate. Now, I can find the median and mean democratic vote with

PA2012_house_dem <- PA2012_house %>% filter(party == "DEMOCRAT")
obs_median <- median(PA2012_house_dem$pct_votes)
obs_mean <- mean(PA2012_house_dem$pct_votes)
obs_median - obs_mean

What's giving me fits is calculating the "zone of chance". What I'd like to do is some kind of Monte Carlo simulation of taking each voter and randomly assigning them to a district, so that the number of voters in each district is unchanged, the number of total votes for each party is unchanged, but the proportion of Republican and Democratic (and other parties) in each district is random, as in a permutation test. The mean Democratic vote should be unchanged, but I can't figure out a good way to carry out this randomization so that I can calculate the median district's Democratic vote percentage.

Thanks in advance for your help!

Edit for clarification: I'd like to do the randomization, say, 10,000 times, and for each of those trials, calculate the median-mean difference. The result should then, ideally, be a vector or data frame with 10,000 rows, that I can then turn into a histogram or something.

EDIT 2 -- PARTIAL SOLUTION:

I have some code that runs, but it's not giving me a reasonable answer. Using dplyr, I've filtered out all but the DEMOCRAT votes, so that each row just gives me the Democrat vote share for a single district.

Rows: 18
Columns: 5
$ district       <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18
$ party          <chr> "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCRAT", "DEMOCR~
$ candidatevotes <dbl> 235394, 318176, 123933, 104643, 104725, 143803, 143509, 152859, 105128, 94227, 118231, 163589, 209901, ~
$ totalvotes     <dbl> 277102, 356386, 302514, 303980, 282465, 335528, 353451, 352238, 274305, 273790, 285198, 338941, 303819,~
$ pct_votes      <dbl> 84.94850, 89.27848, 40.96769, 34.42430, 37.07539, 42.85872, 40.60223, 43.39651, 38.32522, 34.41579, 41.~

This is saved as PA2012_reduced_dem.

Now, here is my code:

require(mosaic) # for the tally() function
data <- PA2012_reduced_dem
B <- 100
samples_diff <- vector("numeric", B)
samples_mean <- vector("numeric", B)
samples_median <- vector("numeric", B)

for(samp in 1:B) {
data_w_sample <- mutate(data, sample_vote = tally(sample(district, sum(candidatevotes),replace=T, prob = totalvotes)))
  data_w_sample <- mutate(data_w_sample, sample_vote_pct = (sample_vote / totalvotes *100))
  mean_sample <- weighted.mean(data_w_sample$sample_vote_pct, w = data_w_sample$totalvotes)
  median_sample <- median(data_w_sample$sample_vote_pct)
  diff_mean_median <- mean_sample - median_sample
  samples_diff[samp] <- diff_mean_median
  samples_mean[samp] <- mean_sample
  samples_median[samp] <- median_sample
}

samples <- data.frame(samples_mean,samples_median,samples_diff)

The idea is that I'm randomly placing each Democrat voter in a district, weighted by the total number of votes per district. Since I have the total vote as a variable, I can compute the share of vote in each district that goes to the Democrat (I'm ignoring independent and other party votes).

Obviously, this is slow, because each trial is sampling for every single Democrat vote (roughly 2.8 million), so I'm only running 100 trials right now.

However, my Monte Carlo simulations are finding a very small "zone of chance" around the mean, the median is only about 0.05 percent above or below the mean. Again, I'm only running 100 trials, but I was expecting a wider zone of chance.

Body:
I figured it out! Randomly placing voters in each district is not correct, and honestly it was pretty silly of me to do so. Instead, I had to use dplyr to create a data frame with the number of Democrat and Republican votes in each of the 435 House districts, one district per row. Then, I followed the advice on page 12 of this paper. I created samples of 18 districts sampled from this 435-row data frame, rejecting them if the mean vote share was more than 1 percent away from that of PA. The results have a much nicer 95% confidence interval, that matches the results of the original article.

data <- house_2012_reduced
# created with dplyr, contains total and percentage of votes
# for Democrats and Republicans.
B <- 100000
del_districts <- 18 # 18 districts in PA
samples_diff <- vector("numeric", B)
samples_mean <- vector("numeric", B)
samples_median <- vector("numeric", B)

for(samp in 1:B) {
  sample_delegation <- sample_n(data, del_districts)
  sample_delegation_pct_dem_mean <- weighted.mean(sample_delegation$pct_dem_votes, w = sample_delegation$total_votes)
  sample_delegation_pct_dem_median <- median(sample_delegation$pct_dem_votes)
  if(near(mean_dem_pct_PA, sample_delegation_pct_dem_mean, 1)){
    samples_mean[samp] <- sample_delegation_pct_dem_mean
    samples_median[samp] <- sample_delegation_pct_dem_median
    samples_diff[samp] <- (sample_delegation_pct_dem_mean - sample_delegation_pct_dem_median)
  }
}

samples <- data.frame(samples_mean,samples_median,samples_diff)
samples <- filter_all(samples, any_vars(. != 0))
quantile(samples$samples_median, c(0.025,0.975))


来源: stackexchange

问:
Run "traditional" unit test in Nightwatch
I have a couple of utility functions, like validateEmail(email) that I would like to test directly, that is, without going through the UI.  Is that possible through Nightwatch?  I have all my UI testing in Nightwatch, and would like to stick with a single toolset for all my testing.
And yes, I "get it" that most testing can (and perhaps should) be at the "public" level.  But for completeness I also like to directly test some internal utility functions with every conceivable input.
Thanks! </p>

答:
Nightwatch now explicitly supports running this sort of test - note the @unittest annotation in the example below.
But, for some reason, this feature seem to be available on their site anymore.

An example:

```<code>const assert = require('assert');
const testScript = require('../../Scripts/unitTestScript');

const dataProvider = [
  {input: 'value_1', expected: 'value_1Test'},
  {input: 'value_2', expected: 'value_2Test'},
  {input: 'value_3', expected: 'value_3Test'},
];

module.exports = {
  '@tags': ['unit_test'],
  '@unitTest' : true,
  'example unit test' : function (done) {
    dataProvider.forEach(function (values) {
      assert.strictEqual(testScript.testMethod(values.input), values.expected);
    });
    setTimeout(function() {
      done();
    }, 10);
  }
};
</code>```

(from https://www.drupal.org/docs/automated-testing/javascript-testing-using-nightwatch#s-writing-unit-tests-in-nightwatch)

ContentLicense: CC BY-SA 3.0

Body:
Nightwatch now explicitly supports running this sort of test - note the @unittest annotation in the example below.
But, for some reason, this feature seem to be available on their site anymore.

An example:

const assert = require('assert');
const testScript = require('../../Scripts/unitTestScript');

const dataProvider = [
  {input: 'value_1', expected: 'value_1Test'},
  {input: 'value_2', expected: 'value_2Test'},
  {input: 'value_3', expected: 'value_3Test'},
];

module.exports = {
  '@tags': ['unit_test'],
  '@unitTest' : true,
  'example unit test' : function (done) {
    dataProvider.forEach(function (values) {
      assert.strictEqual(testScript.testMethod(values.input), values.expected);
    });
    setTimeout(function() {
      done();
    }, 10);
  }
};

(from https://www.drupal.org/docs/automated-testing/javascript-testing-using-nightwatch#s-writing-unit-tests-in-nightwatch)

ContentLicense: CC BY-SA 4.0


问:
Django server not refreshing pages after reloading
When I start the Django server it gives me proper output at first but the next time I make changes to code it does not reflect the changes even after reloading. I am usin react at the frontend.</p>

答: I had same problem Couple days ago. Then I found out Putty. Its a program thats connects to server (screean share). Download Putty and login to your account. From Conslore run command. It Should Work (Sorry for Eanglish :/)</p>


问:
Runtime Code Coverage Tools
I know that there are a number of tools for analysing .NET code and calculating the coverage, plus identifying classes/methods/properties etc that are never going to be hit.

However, I am trying to clean-up a legacy application that I am certain contains an amount of unused code - however a lot of code is accessed via some arbitrary and complex reflection tecniques that will disguise the intent to the compiler - thererfore any coverage tool that only analyses the compiled code is unlikely to generate any reliable reports on code useage within this application.

Are there any tools that work rather like profilers, whereby they listen to a running application and log what classes/methods/properties are actually hit and generate the coverage based on this data.

I hope Ive made everything clear - thanks in anticipation

答:
Can't think of a tool other than a profiler, but how about using logging?

Use static analysis to discover static calls, and put logging into the reflective invocations to show what is being called. After a few runs you'll know what is being run.

After all the reflective invocation will know what's doing.

Title: Runtime Code Coverage Tools


问:
Python code for AWS Cloudwatch metrics & Kinesis firehose dynamic partitioning
I am using below Lambda (python) code to decode cloudwatch metric stream & then creating dynamic partition based on metric_name field in the stream data. But as i have written this in code, if a stream file has 3 types of metric_name data, its picking only 1st metric name & creating partition based on that & putting all 3 metric_name in same partition. This is not intended output. Can anyone help with this code?

I have got idea from AWS documentation about this code & I changed it based on my stream data.(Reference: https://docs.aws.amazon.com/firehose/latest/dev/dynamic-partitioning.html)

Code:

```<code>from __future__ import print_function
import base64
import json
import datetime

# Signature for all Lambda functions that user must implement
def lambda_handler(firehose_records_input, context):
    print("Received records for processing from DeliveryStream: " + firehose_records_input['deliveryStreamArn']
          + ", Region: " + firehose_records_input['region']
          + ", and InvocationId: " + firehose_records_input['invocationId'])

    # Create return value.
    firehose_records_output = {'records': []}

    # Create result object.
    # Go through records and process them

    for firehose_record_input in firehose_records_input['records']:
        # Get user payload
        payload = base64.b64decode(firehose_record_input['data']).decode('utf-8')

        metrics = list(filter(None, payload.split("\n")))

        if len(metrics) > 1:
            print("Length of array = {}".format(len(metrics)))
            new_payload = []
            for metric in metrics:
                new_payload.append(json.loads(metric))
            json_value = new_payload
            print("Record after processing")
            print(json_value)
            # exit()
            print("\n")
            # Create output Firehose record and add modified payload and record ID to it.
            firehose_record_output = {}

            #working partition_keys

            partition_keys = {"metric_name": json_value[0]['metric_name'] }

            # Create output Firehose record and add modified payload and record ID to it.
            firehose_record_output = {'recordId': firehose_record_input['recordId'],
                                      'data': firehose_record_input['data'],
                                      'result': 'Ok',
                                      'metadata': { 'partitionKeys': partition_keys }}

            # Must set proper record ID
            # Add the record to the list of output records.

            firehose_records_output['records'].append(firehose_record_output)

    # At the end return processed records
    print('**************firehose_records_output**********************')
    print(firehose_records_output)
    print('****************end********************')

    return firehose_records_output
</code>```

Stream data sample:

```<code>{
    "metric_stream_name": "MyMetricStream",
    "account_id": "12345678",
    "region": "us-east-1",
    "namespace": "AWS/EC2",
    "metric_name": "DiskWriteOps",
    "dimensions": {
        "InstanceId": "i1234"
    },
    "timestamp": 1611929698000,
    "value": {
        "count": 3.0,
        "sum": 20.0,
        "max": 18.0,
        "min": 0.0
    },
    "unit": "Seconds"
},
{
    "metric_stream_name": "MyMetricStream",
    "account_id": "12345678",
    "region": "us-east-1",
    "namespace": "AWS/EC2",
    "metric_name": "DiskReadIOps",
    "dimensions": {
        "InstanceId": "i1234"
    },
    "timestamp": 1611929698000,
    "value": {
        "count": 3.0,
        "sum": 20.0,
        "max": 18.0,
        "min": 0.0
    },
    "unit": "Seconds"
},
{
    "metric_stream_name": "MyMetricStream",
    "account_id": "12345678",
    "region": "us-east-1",
    "namespace": "AWS/EC2",
    "metric_name": "CPUUtilization",
    "dimensions": {
        "InstanceId": "i1234"
    },
    "timestamp": 1611929698000,
    "value": {
        "count": 3.0,
        "sum": 20.0,
        "max": 18.0,
        "min": 0.0
    },
    "unit": "Seconds"
}
</code>```

As per above data 3 partition should be created, but its creating 1 partition using 1st metric_name(DiskWriteOps) & pushing all metric inside this (because of this I think partition_keys = {"metric_name": json_value[0]['metric_name'] })

答:
If you are passing that record to firehose, it will be treated as one single json record and hence you see only one partition due to json_value[0]['metric_name'] value

In this case, you need to perform some pre-processing via lambda functions or Kinesis analytics to split that json into 3 separate records and then use dynamic partitioning to use the metric_name to create partitions with right name.

Dynamic partition code will look like this:

```<code> partition_keys = {"metric_name": json_value['metric_name'] }
</code>```

Body:
I am using below Lambda (python) code to decode cloudwatch metric stream & then creating dynamic partition based on metric_name field in the stream data. But as i have written this in code, if a stream file has 3 types of metric_name data, its picking only 1st metric name & creating partition based on that & putting all 3 metric_name in same partition. This is not intended output. Can anyone help with this code?

I have got idea from AWS documentation about this code & I changed it based on my stream data.(Reference: https://docs.aws.amazon.com/firehose/latest/dev/dynamic-partitioning.html)

Code:

from __future__ import print_function
import base64
import json
import datetime

# Signature for all Lambda functions that user must implement
def lambda_handler(firehose_records_input, context):
    print("Received records for processing from DeliveryStream: " + firehose_records_input['deliveryStreamArn']
          + ", Region: " + firehose_records_input['region']
          + ", and InvocationId: " + firehose_records_input['invocationId'])

    # Create return value.
    firehose_records_output = {'records': []}

    # Create result object.
    # Go through records and process them

    for firehose_record_input in firehose_records_input['records']:
        # Get user payload
        payload = base64.b64decode(firehose_record_input['data']).decode('utf-8')

        metrics = list(filter(None, payload.split("\n")))

        if len(metrics) > 1:
            print("Length of array = {}".format(len(metrics)))
            new_payload = []
            for metric in metrics:
                new_payload.append(json.loads(metric))
            json_value = new_payload
            print("Record after processing")
            print(json_value)
            # exit()
            print("\n")
            # Create output Firehose record and add modified payload and record ID to it.
            firehose_record_output = {}

            #working partition_keys

            partition_keys = {"metric_name": json_value[0]['metric_name'] }

            # Create output Firehose record and add modified payload and record ID to it.
            firehose_record_output = {'recordId': firehose_record_input['recordId'],
                                      'data': firehose_record_input['data'],
                                      'result': 'Ok',
                                      'metadata': { 'partitionKeys': partition_keys }}

            # Must set proper record ID
            # Add the record to the list of output records.

            firehose_records_output['records'].append(firehose_record_output)

    # At the end return processed records
    print('**************firehose_records_output**********************')
    print(firehose_records_output)
    print('****************end********************')

    return firehose_records_output

Stream data sample:

{
    "metric_stream_name": "MyMetricStream",
    "account_id": "12345678",
    "region": "us-east-1",
    "namespace": "AWS/EC2",
    "metric_name": "DiskWriteOps",
    "dimensions": {
        "InstanceId": "i1234"
    },
    "timestamp": 1611929698000,
    "value": {
        "count": 3.0,
        "sum": 20.0,
        "max": 18.0,
        "min": 0.0
    },
    "unit": "Seconds"
},
{
    "metric_stream_name": "MyMetricStream",
    "account_id": "12345678",
    "region": "us-east-1",
    "namespace": "AWS/EC2",
    "metric_name": "DiskReadIOps",
    "dimensions": {
        "InstanceId": "i1234"
    },
    "timestamp": 1611929698000,
    "value": {
        "count": 3.0,
        "sum": 20.0,
        "max": 18.0,
        "min": 0.0
    },
    "unit": "Seconds"
},
{
    "metric_stream_name": "MyMetricStream",
    "account_id": "12345678",
    "region": "us-east-1",
    "namespace": "AWS/EC2",
    "metric_name": "CPUUtilization",
    "dimensions": {
        "InstanceId": "i1234"
    },
    "timestamp": 1611929698000,
    "value": {
        "count": 3.0,
        "sum": 20.0,
        "max": 18.0,
        "min": 0.0
    },
    "unit": "Seconds"
}

As per above data 3 partition should be created, but its creating 1 partition using 1st metric_name(DiskWriteOps) & pushing all metric inside this (because of this I think partition_keys = {"metric_name": json_value[0]['metric_name'] })

Body:
If you are passing that record to firehose, it will be treated as one single json record and hence you see only one partition due to json_value[0]['metric_name'] value

In this case, you need to perform some pre-processing via lambda functions or Kinesis analytics to split that json into 3 separate records and then use dynamic partitioning to use the metric_name to create partitions with right name.

Dynamic partition code will look like this:

 partition_keys = {"metric_name": json_value['metric_name'] }


问:
Referencing a yet to be created element in another element's event listener in JavaScript
I have an element created dynamically, for which I have already attached an event listener to, like below:

```<code>radio.addEventListener('click', (event) => {
   document.getElementById(action[1]).style.display = 'block';
});
</code>```

The 'action[1]' is a string which will be the id of an element yet to be created.  I have tried this, and it seems to work.  I know the event listener's function will only be fired on the 'click' event, and by then the 'action[1]' element will exist.  But it seems like I'm attaching an invalid function when the addEventListener is attached to my 'radio' element.  Will this cause problems?

答:
Okay, I want to close this with an answer, but the answer, comes from Barmar, so I don't take credit for it.  As stated in the comment,

The body of a function isn't evaluated until the function is called.
There's no problem with access variables that are assigned between
adding the event listener and triggering the event.

Question is answered.

Body:
I have an element created dynamically, for which I have already attached an event listener to, like below:

radio.addEventListener('click', (event) => {
   document.getElementById(action[1]).style.display = 'block';
});

The 'action[1]' is a string which will be the id of an element yet to be created.  I have tried this, and it seems to work.  I know the event listener's function will only be fired on the 'click' event, and by then the 'action[1]' element will exist.  But it seems like I'm attaching an invalid function when the addEventListener is attached to my 'radio' element.  Will this cause problems?


问:
Angular: Why use Observable in http calls instead of promise as server responds to http calls only once?
I'm currently reading about observables and promises. From what I understand promise only returns a single value whereas observable can return a stream of values.
I understand the concept of of observables in simple cases like following

```<code>const myObservable = of(1, 2, 3);

// Create observer object
const myObserver = {
  next: x => console.log('Observer got a next value: ' + x),
  error: err => console.error('Observer got an error: ' + err),
  complete: () => console.log('Observer got a complete notification'),
};
</code>```

but why use observables in angular http calls? Since server responds to http calls only once ,it returns a single value not a stream of values right?Then what is the advantage of using observables over promises in http calls?

答: Observables are way more powerful. We can easily create code that "retries" http calls, in case the first one failed an similar things. You can't do this with promises at all. In addition, another thing you can't do with promises is cancelling calls. Just think of the use case where you build a type ahead component and with each keystroke you have to throttle 300 ms before you send the actual Api Call. This is very easy with observables, but not only that, with observables we can make sure that we always execute the return call in the right order + we can cancel calls.</p>

Body:
I'm currently reading about observables and promises. From what I understand promise only returns a single value whereas observable can return a stream of values.
I understand the concept of of observables in simple cases like following

const myObservable = of(1, 2, 3);

// Create observer object
const myObserver = {
  next: x => console.log('Observer got a next value: ' + x),
  error: err => console.error('Observer got an error: ' + err),
  complete: () => console.log('Observer got a complete notification'),
};

but why use observables in angular http calls? Since server responds to http calls only once ,it returns a single value not a stream of values right?Then what is the advantage of using observables over promises in http calls?


问:
Cost must be multiple by 5
I am working small application with basic CRUD operation and I have Product Model.
In this model I have something like

```<code>public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int amountAvailable { get; set; }
        public double cost { get; set; }

        [ForeignKey(nameof(User))]
        public int UserId { get; set; }
        public User Users { get; set; }

    }
</code>```

Right now, I need some shortcut or some hack how to make cost (cost of the product), but it should be a multiple of 5, meaning the price can be 5,10,15,20,25,30... etc.
Is there anything which I can force user to put price something like thiss?
I try with [DataAnnotation] and using Range but I think this will not work.

答:
You can use a JS at the end of your view which is probably better as you will have a front end validation rather than posting the form before checking if it’s wrong (sorry I’m using my phone to type the suggested answer so may not be formatted properly) but something like this:</p>
```<code>         <script>
                       document.getElementById("Submit_btn_id").addEventListener('click',function ()
                   {

                    //get the value entered in the input field
                     var userEnterANumber = document.getElementById('input_id').value

                       if (userEnterANumber % 5 == 0)
                      {
                     console.write('This is a multiple of 5')
                         //turn off the required attribute from the input field
                        document.getElementById("input_id").required = false;
                        }

                        else
                        {
                          console.write('Not a multiple of 5')
                          //set the required attribute on the input field
                        document.getElementById("input_id").required = true;
                          }
                        });
                </script>
</code>```

Title: Cost must be multiple by 5

Body:
I am working small application with basic CRUD operation and I have Product Model.
In this model I have something like

public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int amountAvailable { get; set; }
        public double cost { get; set; }

        [ForeignKey(nameof(User))]
        public int UserId { get; set; }
        public User Users { get; set; }

    }

Right now, I need some shortcut or some hack how to make cost (cost of the product), but it should be a multiple of 5, meaning the price can be 5,10,15,20,25,30... etc.
Is there anything which I can force user to put price something like thiss?
I try with [DataAnnotation] and using Range but I think this will not work.

Body:
You can use a JS at the end of your view which is probably better as you will have a front end validation rather than posting the form before checking if it’s wrong (sorry I’m using my phone to type the suggested answer so may not be formatted properly) but something like this:

         <script>
                       document.getElementById("Submit_btn_id").addEventListener('click',function ()
                   {

                    //get the value entered in the input field
                     var userEnterANumber = document.getElementById('input_id').value

                       if (userEnterANumber % 5 == 0)
                      {
                     console.write('This is a multiple of 5')
                         //turn off the required attribute from the input field
                        document.getElementById("input_id").required = false;
                        }

                        else
                        {
                          console.write('Not a multiple of 5')
                          //set the required attribute on the input field
                        document.getElementById("input_id").required = true;
                          }
                        });
                </script>


问:
Fix "Cannot find module 'libnpx' " on react-native init
With a fresh project, after running react-native init {project},
during the phase "Installing required Cocoapods dependencies", this error is thrown:

```<code>Error: Cannot find module 'libnpx'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15)
    at Function.Module._load (internal/modules/cjs/loader.js:575:25)
    at Module.require (internal/modules/cjs/loader.js:705:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npx-cli.js:3:13)
    at Module._compile (internal/modules/cjs/loader.js:799:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10)
    at Module.load (internal/modules/cjs/loader.js:666:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
    at Function.Module._load (internal/modules/cjs/loader.js:598:3)

(node:27038) UnhandledPromiseRejectionWarning: Error: Failed to install CocoaPods dependencies for iOS project, which is required by this template.
Please try again manually: "cd ./RNimage/ios && pod install".
</code>```

Following the suggestion to run pod install, the same error is thrown in addition to

```<code>[!] Invalid 'Podfile' file 767: unexpected token at ''.
 #  from /Users/.../Desktop/Development/RNproject/ios/Podfile:42
 #  -------------------------------------------
 #
 >    use_native_modules!
 #  end
 #  -------------------------------------------
</code>```

I haven't even touched the project why is this happening and how do i fix it?

Before this i ran sudo chown -R 501:20 "/Users/vorousjames/.npm". I dont know if thats significant to this issue but it has broken alot.

答: I had to reset the shell location hash with "hash -r"</p>

Body:
With a fresh project, after running react-native init {project},
during the phase "Installing required Cocoapods dependencies", this error is thrown:

Error: Cannot find module 'libnpx'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15)
    at Function.Module._load (internal/modules/cjs/loader.js:575:25)
    at Module.require (internal/modules/cjs/loader.js:705:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npx-cli.js:3:13)
    at Module._compile (internal/modules/cjs/loader.js:799:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10)
    at Module.load (internal/modules/cjs/loader.js:666:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
    at Function.Module._load (internal/modules/cjs/loader.js:598:3)

(node:27038) UnhandledPromiseRejectionWarning: Error: Failed to install CocoaPods dependencies for iOS project, which is required by this template.
Please try again manually: "cd ./RNimage/ios && pod install".

Following the suggestion to run pod install, the same error is thrown in addition to

[!] Invalid 'Podfile' file 767: unexpected token at ''.
 #  from /Users/.../Desktop/Development/RNproject/ios/Podfile:42
 #  -------------------------------------------
 #
 >    use_native_modules!
 #  end
 #  -------------------------------------------

I haven't even touched the project why is this happening and how do i fix it?

Before this i ran sudo chown -R 501:20 "/Users/vorousjames/.npm". I dont know if thats significant to this issue but it has broken alot.


问:
How to Change Rows of Arrays into Opposite
I have a Sheet with Column A being City and Column B being District, like so:

City
Districts

Accord
103

Albany
109,110,108

Altamont
109

I would like to transform this into the "opposite":

District
Cities

103
Accord

108
Albany

109
Albany, Altamont

110
Albany

I'm pretty sure it's simple.  Thanks !

答:
use:

```<code>=ARRAYFORMULA(QUERY(SPLIT(REGEXREPLACE(TRIM(FLATTEN(
 QUERY(QUERY(SPLIT(FLATTEN(SPLIT(B2:B, ",")&"¤×"&A2:A&","), "×"),
 "select max(Col2) group by Col2 pivot Col1"),,9^9))),
 ",$", ), "¤ ", 0), "where Col2 is not null", 0))
</code>```

Body:
use:

=ARRAYFORMULA(QUERY(SPLIT(REGEXREPLACE(TRIM(FLATTEN(
 QUERY(QUERY(SPLIT(FLATTEN(SPLIT(B2:B, ",")&"¤×"&A2:A&","), "×"),
 "select max(Col2) group by Col2 pivot Col1"),,9^9))),
 ",$", ), "¤ ", 0), "where Col2 is not null", 0))


问:
Best way to use MySQL for image galleries?

Possible Duplicate:

  What is the best way to store a series of images in MySQL?

This is the first website that I built for a friend a few months ago:
http://www.jpsinghphotography.co.uk

I want to rebuild it as my first PHP/MySQL project, but I had a couple of questions regarding how to structure the database.

1) Is it best to put the actual image files in the database using BLOB data types; or store the file names and use these to look up the images from another folder on the server?

2) I'm new to SQL and I'd initially imagined a seperate table for each gallery I want to create. In what ways is one table sorted by category better?

Thanks for any and all advice

答:
Welcome to stackoverflow.

You can put image data in MySQL, but it's usually better to put them as files.  That make them easier to cache and thumbnail, otherwise you have to do them yourself.

One table sorted by category would allow you more flexibility in category names and make it easier to move images between categories as well as get information from multiple categories such as image count of each category.


问:
Simple_form_for many to many with validation

Setup

I have a simple many to many relationship between a Submit and an Answer through SubmitAnswer.

Answers are grouped by a Question (in my case each question has three answers) - think of it as a multiple choice quiz.

I have been trying to use SimpleFormFor to make a form which renders a predetermined set of questions, where each question has a predetermined set of answers.

Something like this:

#form
<%= simple_form_for Submit.new, url: "/questionnaire" do |f| %>

  <% @questions.each do |question| %>
    <%= f.association :answers, collection: question.answers %>
  <% end %>

  <%= f.submit :done %>
<% end %>

#controller
def create
  @submit = Submit.new(submit_params)
  @submit.user = current_user

  if @submit.save
    redirect_to root_path
  else
    render :new
  end
end

def submit_params
  params.require(:submit).permit(answer_ids: [])
end
```
<p>When I submit the form, Rails creates the join table, SubmitAnswers, automatically.</p>
<p>So here is the crux of the matter: Whats the easiest way to re-render the form, errors and all, if not all questions have been answered, ie if <code>@submit.answers.length != @question.length</code> ?</p>
<p>I can add a custom error with <code>errors.add(:answers, 'error here')</code>, but when I re-render, the correctly selected answers arent repopulated, which is suboptimal.</p>
<p>For completions sacke, here are my models:</p>
<pre class="lang-rb prettyprint-override"><code>class Submit < ApplicationRecord
  belongs_to :user

  has_many :submit_answers
  has_many :answers, through: :submit_answers
end
</code>```

class SubmitAnswer < ApplicationRecord
  belongs_to :submit
  belongs_to :answer
end
```
<pre class="lang-rb prettyprint-override"><code>class Answer < ApplicationRecord
  has_many :submit_answers
  has_many :submits, through: :submit_answers
end
</code>```

答:
Alright, after some digging we did find the answer to make the form work, albeit with more pain that we anticipated a simple many-to-many should take.

#model
class Submit < ApplicationRecord
  belongs_to :user

  has_many :submit_answers
  has_many :answers, through: :submit_answers

  accepts_nested_attributes_for :submit_answers
end

#controller
def new
  @submit = Submit.new
  @questions.count.times { @submit.submit_answers.build }
end

def create
  @submit = Submit.new(submit_params)
  @submit.user = current_user
  if @submit.save
    redirect_to root_path
  else
    render :home
  end
end

def submit_params
  params.require(:submit).permit(submit_answers_attributes:[:answer_id])
end

#form
<%= simple_form_for @submit do |f| %>
  <%= f.simple_fields_for :submit_answers do |sa| %>
    <%= sa.input :answer_id,  collection: @answers[sa.options[:child_index]], input_html: { class: "#{'is-invalid' if sa.object.errors.any?}"}, label: @questions[sa.options[:child_index]].name %>

          <% sa.object.errors.full_messages.each do |msg| %>

 <%= msg %>

          <% end %>

    <% end %>
  <%= f.submit :done %>
<% end %>
```
<p>The solution is to use <code>simple_fields_for</code>/<code>fields_for</code>. Note that <code><%= sa.input :answer_id %></code> must be <strong>:answer_id</strong>, not <strong>:answer</strong>, which is something I had tried before.</p>
<p>Also one must allow <code>accepts_nested_attributes_for :submit_answers</code>, where <strong>:submit_answers</strong> is the <strong>join_table</strong>.</p>
<p>I prebuild my SubmitAnswers like so: <code>@questions.count.times { @submit.submit_answers.build }</code> which generates an input field for each question, all of which get saved on the form submit, a la build.</p>
<p>For the strong_params one needs to permit the incoming ids:
<code>params.require(:submit).permit(submit_answers_attributes:[:answer_id])</code>, so in this case <strong>submit_answers_attributes:[:answer_id]</strong>.</p>
<p>For anyone wondering what the params look like:</p>
```{"authenticity_token"=>"[FILTERED]",
 "submit"=>
  {"submit_answers_attributes"=>
    {"0"=>{"answer_id"=>""}, "1"=>{"answer_id"=>""}, "2"=>{"answer_id"=>""}, "3"=>{"answer_id"=>""}, "4"=>{"answer_id"=>""}, "5"=>{"answer_id"=>""}, "6"=>{"answer_id"=>""}}},
 "commit"=>"done"}
```

As for the errors, im sure there might be a better way, but for now I have just manually added them with input_html: { class: "#{'is-invalid' if sa.object.errors.any?}"}.

On a final note, the sa.object # => SubmitAnswer allows me to retrieve the Model, the errors of that Model or whatever else one might want.

Body:
Setup

I have a simple many to many relationship between a Submit and an Answer through SubmitAnswer.

Answers are grouped by a Question (in my case each question has three answers) - think of it as a multiple choice quiz.

I have been trying to use SimpleFormFor to make a form which renders a predetermined set of questions, where each question has a predetermined set of answers.

Something like this:

#form
<%= simple_form_for Submit.new, url: "/questionnaire" do |f| %>

  <% @questions.each do |question| %>
    <%= f.association :answers, collection: question.answers %>
  <% end %>

  <%= f.submit :done %>
<% end %>

#controller
def create
  @submit = Submit.new(submit_params)
  @submit.user = current_user

  if @submit.save
    redirect_to root_path
  else
    render :new
  end
end

def submit_params
  params.require(:submit).permit(answer_ids: [])
end

When I submit the form, Rails creates the join table, SubmitAnswers, automatically.

So here is the crux of the matter: Whats the easiest way to re-render the form, errors and all, if not all questions have been answered, ie if @submit.answers.length != @question.length ?

I can add a custom error with errors.add(:answers, 'error here'), but when I re-render, the correctly selected answers arent repopulated, which is suboptimal.

For completions sacke, here are my models:

class Submit < ApplicationRecord
  belongs_to :user

  has_many :submit_answers
  has_many :answers, through: :submit_answers
end

class SubmitAnswer < ApplicationRecord
  belongs_to :submit
  belongs_to :answer
end

class Answer < ApplicationRecord
  has_many :submit_answers
  has_many :submits, through: :submit_answers
end

Body:
Alright, after some digging we did find the answer to make the form work, albeit with more pain that we anticipated a simple many-to-many should take.

#model
class Submit < ApplicationRecord
  belongs_to :user

  has_many :submit_answers
  has_many :answers, through: :submit_answers

  accepts_nested_attributes_for :submit_answers
end

#controller
def new
  @submit = Submit.new
  @questions.count.times { @submit.submit_answers.build }
end

def create
  @submit = Submit.new(submit_params)
  @submit.user = current_user
  if @submit.save
    redirect_to root_path
  else
    render :home
  end
end

def submit_params
  params.require(:submit).permit(submit_answers_attributes:[:answer_id])
end

#form
<%= simple_form_for @submit do |f| %>
  <%= f.simple_fields_for :submit_answers do |sa| %>
    <%= sa.input :answer_id,  collection: @answers[sa.options[:child_index]], input_html: { class: "#{'is-invalid' if sa.object.errors.any?}"}, label: @questions[sa.options[:child_index]].name %>
      <div class="invalid-feedback d-block">
        <ul>
          <% sa.object.errors.full_messages.each do |msg| %>
            <li> <%= msg %></li>
          <% end %>
        </ul>
      </div>
    <% end %>
  <%= f.submit :done %>
<% end %>

The solution is to use simple_fields_for/fields_for. Note that <%= sa.input :answer_id %> must be :answer_id, not :answer, which is something I had tried before.

Also one must allow accepts_nested_attributes_for :submit_answers, where :submit_answers is the join_table.

I prebuild my SubmitAnswers like so: @questions.count.times { @submit.submit_answers.build } which generates an input field for each question, all of which get saved on the form submit, a la build.

For the strong_params one needs to permit the incoming ids:
params.require(:submit).permit(submit_answers_attributes:[:answer_id]), so in this case submit_answers_attributes:[:answer_id].

For anyone wondering what the params look like:

{"authenticity_token"=>"[FILTERED]",
 "submit"=>
  {"submit_answers_attributes"=>
    {"0"=>{"answer_id"=>""}, "1"=>{"answer_id"=>""}, "2"=>{"answer_id"=>""}, "3"=>{"answer_id"=>""}, "4"=>{"answer_id"=>""}, "5"=>{"answer_id"=>""}, "6"=>{"answer_id"=>""}}},
 "commit"=>"done"}

As for the errors, im sure there might be a better way, but for now I have just manually added them with input_html: { class: "#{'is-invalid' if sa.object.errors.any?}"}.

On a final note, the sa.object # => SubmitAnswer allows me to retrieve the Model, the errors of that Model or whatever else one might want.


问:
Get list of days in the week that reflect locale in JavaScript?
I have this function that returns days of the week:

var SEPARATOR = '  ';
function week_days(lang) {
    var result = [];
    for (var i = 0; i <= 6; ++i) {
        var d = new Date(1970, 1, 1 + i);
        result.push(d.toLocaleString(lang, {weekday: 'short'}).substring(0, 2));
    }
    return result.join(SEPARATOR);
}

console.log("en-us", week_days("en-us"))
console.log("pl-pl", week_days("pl-pl"))```

but it's fixed and starts from Sunday like in the US locale. But in the Polish locale week starts from Monday. There are probably languages that use one or the other.

I can use new Date(1970, 1, 2 + i); and it will work, but how I can make it based on Locale? (e.g. window.navigator.language).

答:
I've found that the spec has no way of knowing this information. It's tracked here:

https://github.com/tc39/ecma402/issues/6

This is an old issue. From the comments, it seems that there is a spec:

https://github.com/tc39/proposal-intl-locale-info

That should handle this.

Body:
I have this function that returns days of the week:

var SEPARATOR = '  ';
function week_days(lang) {
    var result = [];
    for (var i = 0; i <= 6; ++i) {
        var d = new Date(1970, 1, 1 + i);
        result.push(d.toLocaleString(lang, {weekday: 'short'}).substring(0, 2));
    }
    return result.join(SEPARATOR);
}

console.log("en-us", week_days("en-us"))
console.log("pl-pl", week_days("pl-pl"))

but it's fixed and starts from Sunday like in the US locale. But in the Polish locale week starts from Monday. There are probably languages that use one or the other.

I can use new Date(1970, 1, 2 + i); and it will work, but how I can make it based on Locale? (e.g. window.navigator.language).


问:
how to fetch reset password api in front-end Node js
I'm student in web development. Currently, I'm trying to build a basic project, where I'm stack in implementing reset password feature, I really need help in how fetching reset password API in front-end using Axios. In short, the reset password API that I implemented works fine on Postman, but whenever I tried to pass in front-end and fetch the API in order to enable users to enter their new password and passwordValidation I kinda lost, below I share my code snippets:

backend code reset password

resetPassword = async(req, res) => {
  try {
    // Step 1: Get user based on the token
    const validateHashedToken = crypto
                              .createHash('sha256')
                              .update(req.params.token)
                              .digest('hex');

    const user = await User.findOne(
                {
                  passwordResetToken: validateHashedToken,
                  passwordResetExpires: { $gt: Date.now() }
                });

    user.password = req.body.password;
    user.passwordValidation = req.body.passwordValidation;
    user.passwordResetToken = undefined;
    user.passwordResetExpires = undefined;
    await user.save();

    // Step 3: Update the "passwordChangedAt" date
    // Step 4: Log the user in and send a JWT
    genResJWT(user, 200, res);

  } catch (error) {
    console.log('error', error)
  }
};
```
<p>Routes:</p>
<pre class="lang-js prettyprint-override"><code>router
  .route('/api/v1/users/resetpassword/:token')
  .get(viewsController.getResetPasswordUrl)
  .patch(viewsController.resetpassword);
</code>```

controllers

exports.getResetPasswordUrl = async(req, res) => {
  try {
    const { token } = req.params.token;
    const validToken = await User.findOne(
      {
        passwordResetToken: token
      }
    );

    res.status(200).render('resetPassword',
      {
    title: 'resetpassword',
    token: validToken
      });
  } catch (error) {
    console.log(error);
  }
};

exports.resetpassword = (req, res) => {
  // I'm stack here and I really need help
  res.status(200).render('profile', {
    title: 'reset password successfuly'
  });
};
```
<p>front-end fetching api code:</p>
<pre class="lang-js prettyprint-override"><code>import axios from 'axios';

export const resetPassword = async (password, passwordValidation) => {
  try {
    const res = await axios({
      method: 'PATCH',
      url:
        `http://127.0.0.1:3000/api/v1/users/resetpassword/:token`,
      data: {
        password,
        passwordValidation
      }
    });

    if (res.data.status === 'success') {
      window.setTimeout(() => {
    location.replace('/me');
      }, 500);
    }
  } catch (error) {
    console.log('error', error.response.data.message);
  }
};
</code>```

答:
On the front end, you are making a request to http://127.0.0.1:3000/api/v1/users/resetpassword/:token. Since token is a route parameter, you are directly passing in the string ":token" and not the actual value of the token.

Try this instead:

const res = await axios({
    method: 'PATCH',
    url:
        `http://127.0.0.1:3000/api/v1/users/resetpassword/${token}`,
    data: {
        password,
        passwordValidation
    }
  });
```

where token is a variable you need to define.

Assuming that you are using express, here is some documentation about parameter routing: https://expressjs.com/en/guide/routing.html#route-parameters

Body:
I'm student in web development. Currently, I'm trying to build a basic project, where I'm stack in implementing reset password feature, I really need help in how fetching reset password API in front-end using Axios. In short, the reset password API that I implemented works fine on Postman, but whenever I tried to pass in front-end and fetch the API in order to enable users to enter their new password and passwordValidation I kinda lost, below I share my code snippets:

backend code reset password

resetPassword = async(req, res) => {
  try {
    // Step 1: Get user based on the token
    const validateHashedToken = crypto
                              .createHash('sha256')
                              .update(req.params.token)
                              .digest('hex');

    const user = await User.findOne(
                {
                  passwordResetToken: validateHashedToken,
                  passwordResetExpires: { $gt: Date.now() }
                });

    user.password = req.body.password;
    user.passwordValidation = req.body.passwordValidation;
    user.passwordResetToken = undefined;
    user.passwordResetExpires = undefined;
    await user.save();

    // Step 3: Update the "passwordChangedAt" date
    // Step 4: Log the user in and send a JWT
    genResJWT(user, 200, res);

  } catch (error) {
    console.log('error', error)
  }
};

Routes:

router
  .route('/api/v1/users/resetpassword/:token')
  .get(viewsController.getResetPasswordUrl)
  .patch(viewsController.resetpassword);

controllers

exports.getResetPasswordUrl = async(req, res) => {
  try {
    const { token } = req.params.token;
    const validToken = await User.findOne(
      {
        passwordResetToken: token
      }
    );

    res.status(200).render('resetPassword',
      {
    title: 'resetpassword',
    token: validToken
      });
  } catch (error) {
    console.log(error);
  }
};

exports.resetpassword = (req, res) => {
  // I'm stack here and I really need help
  res.status(200).render('profile', {
    title: 'reset password successfuly'
  });
};

front-end fetching api code:

import axios from 'axios';

export const resetPassword = async (password, passwordValidation) => {
  try {
    const res = await axios({
      method: 'PATCH',
      url:
        `http://127.0.0.1:3000/api/v1/users/resetpassword/:token`,
      data: {
        password,
        passwordValidation
      }
    });

    if (res.data.status === 'success') {
      window.setTimeout(() => {
    location.replace('/me');
      }, 500);
    }
  } catch (error) {
    console.log('error', error.response.data.message);
  }
};

Body:
On the front end, you are making a request to http://127.0.0.1:3000/api/v1/users/resetpassword/:token. Since token is a route parameter, you are directly passing in the string ":token" and not the actual value of the token.

Try this instead:

const res = await axios({
    method: 'PATCH',
    url:
        `http://127.0.0.1:3000/api/v1/users/resetpassword/${token}`,
    data: {
        password,
        passwordValidation
    }
  });

where token is a variable you need to define.

Assuming that you are using express, here is some documentation about parameter routing: https://expressjs.com/en/guide/routing.html#route-parameters


问:
LINQ, Where() vs FindAll()
Can someone explain how the LINQ functions Where(..) and FindAll(..) differ? They both seem to do the same thing...</p>

答:
Performance wise FindAll() is better, Here is an example below. The FindAll takes 3millisecs while the Where took 11millisecs.

```<code>    public class SortedSearch
    {
        public static int[] CountNumbersUsingFindAll(int[] sortedArray, int lessThan)
        {
            var smaller = Array.FindAll(sortedArray,x => x < lessThan);
            return smaller;
        }
        public static IEnumerable<int> CountNumbersUsingWhere(int[] sortedArray,int lessThan)
        {
            var smaller = sortedArray.Where(x => x < lessThan);
            return smaller;
        }
   }

class Program
{
        static void Main(string[] args)
        {
            Stopwatch s = Stopwatch.StartNew();
            Console.WriteLine(SortedSearch.CountNumbersUsingFindAll(new int[]{1,3,5,7},4));
            Console.WriteLine(s.ElapsedMilliseconds);
            s.Stop();

            s.Restart();
            Console.WriteLine(SortedSearch.CountNumbersUsingWhere(new int[] { 1, 3, 5, 7 }, 4));
            Console.WriteLine(s.ElapsedMilliseconds);
            s.Stop();
            Console.ReadKey();
        }
}
</code>```

Title: LINQ, Where() vs FindAll()

Body:
Performance wise FindAll() is better, Here is an example below. The FindAll takes 3millisecs while the Where took 11millisecs.

    public class SortedSearch
    {
        public static int[] CountNumbersUsingFindAll(int[] sortedArray, int lessThan)
        {
            var smaller = Array.FindAll(sortedArray,x => x < lessThan);
            return smaller;
        }
        public static IEnumerable<int> CountNumbersUsingWhere(int[] sortedArray,int lessThan)
        {
            var smaller = sortedArray.Where(x => x < lessThan);
            return smaller;
        }
   }

class Program
{
        static void Main(string[] args)
        {
            Stopwatch s = Stopwatch.StartNew();
            Console.WriteLine(SortedSearch.CountNumbersUsingFindAll(new int[]{1,3,5,7},4));
            Console.WriteLine(s.ElapsedMilliseconds);
            s.Stop();

            s.Restart();
            Console.WriteLine(SortedSearch.CountNumbersUsingWhere(new int[] { 1, 3, 5, 7 }, 4));
            Console.WriteLine(s.ElapsedMilliseconds);
            s.Stop();
            Console.ReadKey();
        }
}


问:
JS - Is there a more efficient way to compare values in an array to a target search term
I am aiming to search an array of objects for one that's title is similar or matches a search term exactly. The problem is I would like to prioritise exact matches over matches that only contain the string.

The current code does this by looping multiple times, each time with a different condition, and returns the object if it matches.

class Item {
    constructor(title) {
        this.title = title;
    }
}

function findMatch(term) {
    const items = [new Item("term"), new Item("Longer Term"), new Item("Completely Different Title")];

    // Check if any match the search term exactly
    for (var item of items) {
        if (item.title === term) return item;
    }

    // Check if any match the search term, ignoring case
    for (var item of items) {
        if (item.title.toLowerCase() === term.toLowerCase()) return item;
    }

    // Check if any start with the search term
    for (var item of items) {
        if (item.title.toLowerCase().startsWith(term.toLowerCase())) return item;
    }

    // Check if any end with the search term
    for (var item of items) {
        if (item.title.toLowerCase().endsWith(term.toLowerCase())) return item;
    }

    // Check if any contain the search term
    for (var item of items) {
        if (item.title.toLowerCase().includes(term.toLowerCase())) return item;
    }

    return null;
}

console.log(findMatch("different")); // Item with title "Completely Different Title"
```

Is there a way to do this more efficiently, like in one loop - or is there a better way to search strings?

I have looked into using the Levenshtein algorithm however this does not work for searching "Comp" and getting the Item with title "Completely Different Title", as a lot more is different between "Comp" and "Completely Different Title" than there is between "Comp" and "term" - Is there a way to incorporate the same idea into this search?

答:
If you're looking for efficiency, the only improvement I can think of that would reduce processing would be to lowercase the strings in advance, instead of lowercasing each value inside each loop. Though, it'd probably be a very marginal improvement and be unnoticeable in most cases.

```<code>class Item {
    constructor(title) {
        this.title = title;
        this.lowerTitle = title.toLowerCase();
    }
}
function findMatch(term) {
    const lowerTerm = term.toLowerCase();
    // use item.lowerTitle and lowerTerm when appropriate
</code>```

The logic you want to implement fundamentally requires a loop over all elements looking for one condition, followed by another loop over all elements looking for another, etc. So there's no real way to improve the computational complexity over your current implementation.

You could combine some or all of the conditions with a regular expression, but that would break the priority sequence of match types to be returned.

If you want to make the code shorter and easier to maintain, that's easy enough - you could use an array of callbacks that get called for every item in order:

```<code>const comparers = [
  (a, b) => a === b,
  (a, b) => a.startsWith(b),
  (a, b) => a.endsWith(b),
  (a, b) => a.includes(b),
]
for (const fn of comparers) {
  if (fn(item.lowerTitle, lowerTerm)) return item;
}
</code>```

Is there a way to incorporate the same idea into this search?

Checking the Levenshtein distance would be a bit different. Instead of looping over items and returning one when it matches, you'd need to loop over all items unconditionally and return the best match after the loop finishes.

```<code>let bestItem;
let lowestDistance = Infinity;
for (const item of items) {
  const dist = compare(item.lowerTitle, lowerTerm);
  if (dist < lowestDistance) {
    bestItem = item;
    lowestDistance = dist;
  }
}
return bestItem;
</code>```

You'd do this at least instead of the .includes check at the end. Depending on what logic you want, you might also remove the startsWith and endsWith checks in exchange too.

Body:
I am aiming to search an array of objects for one that's title is similar or matches a search term exactly. The problem is I would like to prioritise exact matches over matches that only contain the string.

The current code does this by looping multiple times, each time with a different condition, and returns the object if it matches.

class Item {
    constructor(title) {
        this.title = title;
    }
}

function findMatch(term) {
    const items = [new Item("term"), new Item("Longer Term"), new Item("Completely Different Title")];

    // Check if any match the search term exactly
    for (var item of items) {
        if (item.title === term) return item;
    }

    // Check if any match the search term, ignoring case
    for (var item of items) {
        if (item.title.toLowerCase() === term.toLowerCase()) return item;
    }

    // Check if any start with the search term
    for (var item of items) {
        if (item.title.toLowerCase().startsWith(term.toLowerCase())) return item;
    }

    // Check if any end with the search term
    for (var item of items) {
        if (item.title.toLowerCase().endsWith(term.toLowerCase())) return item;
    }

    // Check if any contain the search term
    for (var item of items) {
        if (item.title.toLowerCase().includes(term.toLowerCase())) return item;
    }

    return null;
}

console.log(findMatch("different")); // Item with title "Completely Different Title"

Is there a way to do this more efficiently, like in one loop - or is there a better way to search strings?

I have looked into using the Levenshtein algorithm however this does not work for searching "Comp" and getting the Item with title "Completely Different Title", as a lot more is different between "Comp" and "Completely Different Title" than there is between "Comp" and "term" - Is there a way to incorporate the same idea into this search?

Body:
If you're looking for efficiency, the only improvement I can think of that would reduce processing would be to lowercase the strings in advance, instead of lowercasing each value inside each loop. Though, it'd probably be a very marginal improvement and be unnoticeable in most cases.

class Item {
    constructor(title) {
        this.title = title;
        this.lowerTitle = title.toLowerCase();
    }
}
function findMatch(term) {
    const lowerTerm = term.toLowerCase();
    // use item.lowerTitle and lowerTerm when appropriate

The logic you want to implement fundamentally requires a loop over all elements looking for one condition, followed by another loop over all elements looking for another, etc. So there's no real way to improve the computational complexity over your current implementation.

You could combine some or all of the conditions with a regular expression, but that would break the priority sequence of match types to be returned.

If you want to make the code shorter and easier to maintain, that's easy enough - you could use an array of callbacks that get called for every item in order:

const comparers = [
  (a, b) => a === b,
  (a, b) => a.startsWith(b),
  (a, b) => a.endsWith(b),
  (a, b) => a.includes(b),
]
for (const fn of comparers) {
  if (fn(item.lowerTitle, lowerTerm)) return item;
}

Is there a way to incorporate the same idea into this search?

Checking the Levenshtein distance would be a bit different. Instead of looping over items and returning one when it matches, you'd need to loop over all items unconditionally and return the best match after the loop finishes.

let bestItem;
let lowestDistance = Infinity;
for (const item of items) {
  const dist = compare(item.lowerTitle, lowerTerm);
  if (dist < lowestDistance) {
    bestItem = item;
    lowestDistance = dist;
  }
}
return bestItem;

You'd do this at least instead of the .includes check at the end. Depending on what logic you want, you might also remove the startsWith and endsWith checks in exchange too.


问:
Respond to slack channel message in thread with dialogs
I want to be able to respond in a thread to a message using a dialog. I can accomplish this without using a dialog by creating a reply using the activity and setting the channel data. I am not seeing a way to do this with dialogs.

The bot I am creating needs to be able to respond in thread as it will be a user specific thread, but I want to use dialogs as others on team are not as well versed in C#. I have accomplished this with the reply to initial message and use channel data with the ts.

答: So to do this we need to pull the channel data from slack and grab the ts. We then need to update the Id property of the Conversation to append the ts to the end of the Id using a semicolon. The Conversation is a property on the activity.</p>


问:
How do you find the sum of specific items in a 2d array with a foreach loop?
I have this list:
my_list = [('a',1), ('b',2), ('c',3)]

How can i write a foreach loop to find the sum of 1+2+3?

答:
Short approach using a comprehension:

items = [('a', 1), ('b', 2), ('c', 3)]
print(sum(item[1] for item in items))
```

Please avoid naming your list list, it's the name of the list type in Python, so you're "hiding" the list type, which can cause strange bugs if you need the real list later.

Body:
Short approach using a comprehension:

items = [('a', 1), ('b', 2), ('c', 3)]
print(sum(item[1] for item in items))

Please avoid naming your list list, it's the name of the list type in Python, so you're "hiding" the list type, which can cause strange bugs if you need the real list later.


问:
Hibernate and SQLite : Set unique constraint on creation
I'm using Hibernate to create SQLite tables.

I have a table as such

@Entity
class Person(

    @Column(unique = true, nullable = false)
    val name: String,

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int? = null,
)
```
<p>I see that when the database is created, the <code>unique</code> constraint is added later on via an ALTER request</p>
```Hibernate: create table Person (id  integer, name varchar(255) not null, primary key (id))
Hibernate: alter table Person add constraint UK_is4vd0f6kw9sw4dxyie5cy9fa unique (name)
```

Except that SQLite does not seem to support ALTER requests modifying constraints on tables.

So my question is : Is there a way to literally indicate Hibernate to set that uniqueness constraint on table creation? What would be the best way to do it?

I can ensure uniqueness easily later on via code, but I'd rather use the power of the database if I can.

I should add that this is for a personal small application so so far I'm using the update setting for hibernate.hbm2ddl.auto so Hibernate generates the SQL itself. I'm open to other methods but I'd rather avoid them if I can to reduce maintenance.

答:
Gonna answer my own question given that it's not getting much traction :).

SQLite indeed does not support ALTER with constraints, and Hibernate does not (to my knowledge) offer a clean way to use custom SQL.
On top of this, it is not recommended to use Hibernate: hbm2ddl.auto=update in production.

For those reasons, I decided to turn myself to Flyway and write my own SQL. The good news is that adding Flyway provides my database migrations. The bad news is that it's one more dependency to maintain.

What I've done:

Added the flyway dependency in my build.gradle.kts

```<code>    implementation("org.flywaydb:flyway-core:8.4.3")
</code>```

Instantiated flyway before hibernate in my code, pointing to the same database:

```<code>    val flyway = Flyway
        .configure()
        .dataSource("jdbc:sqlite:test.db", null, null).load()
    flyway.migrate()
</code>```

Added a handwritten SQL migration file in resources/V1__Create_person_and_entries_table.sql

```<code>create table Person
(
    id   integer primary key,
    name varchar(255) not null UNIQUE
);
</code>```

Et voilà!

I wrote a blog post over here with more details and some more reasons to use something like Flyway.

Body:
I'm using Hibernate to create SQLite tables.

I have a table as such

@Entity
class Person(

    @Column(unique = true, nullable = false)
    val name: String,

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int? = null,
)

I see that when the database is created, the unique constraint is added later on via an ALTER request

Hibernate: create table Person (id  integer, name varchar(255) not null, primary key (id))
Hibernate: alter table Person add constraint UK_is4vd0f6kw9sw4dxyie5cy9fa unique (name)

Except that SQLite does not seem to support ALTER requests modifying constraints on tables.

So my question is : Is there a way to literally indicate Hibernate to set that uniqueness constraint on table creation? What would be the best way to do it?

I can ensure uniqueness easily later on via code, but I'd rather use the power of the database if I can.

I should add that this is for a personal small application so so far I'm using the update setting for hibernate.hbm2ddl.auto so Hibernate generates the SQL itself. I'm open to other methods but I'd rather avoid them if I can to reduce maintenance.

Body:
Gonna answer my own question given that it's not getting much traction :).

SQLite indeed does not support ALTER with constraints, and Hibernate does not (to my knowledge) offer a clean way to use custom SQL.
On top of this, it is not recommended to use Hibernate: hbm2ddl.auto=update in production.

For those reasons, I decided to turn myself to Flyway and write my own SQL. The good news is that adding Flyway provides my database migrations. The bad news is that it's one more dependency to maintain.

What I've done:

Added the flyway dependency in my build.gradle.kts

    implementation("org.flywaydb:flyway-core:8.4.3")

Instantiated flyway before hibernate in my code, pointing to the same database:

    val flyway = Flyway
        .configure()
        .dataSource("jdbc:sqlite:test.db", null, null).load()
    flyway.migrate()

Added a handwritten SQL migration file in resources/V1__Create_person_and_entries_table.sql

create table Person
(
    id   integer primary key,
    name varchar(255) not null UNIQUE
);

Et voilà!

I wrote a blog post over here with more details and some more reasons to use something like Flyway.


问:
Android - multi-line linear layout
I need a multi-line layout, which would behave as horizontal linear layout, but when there is not enough space to place new widget it would expand to next line, just like words in text. Widgets would be added there at runtime, and should go with wrap_content. Actually, there would be buttons.

Is there any widgets with such behaviour? Or give a suggestion about how to write such layout by myself.

Finally it should look like this:

答:
Assuming you have Constraint Layout version 2.0.0 or higher, I believe you could use a ConstraintLayout with a androidx.constraintlayout.helper.widget.Flow child. The flow could have app:flow_wrapMode=chain or aligned depending on how you would like the layout to look.

Each of the list elements would be siblings of your Flow (ie. nested within the ConstraintLayout but without any constraints). Each element would have to have an id and those ids would have to be listed in the value for the Flow's app:constraint_referenced_ids property.

For more information you can check out these resources:

https://developer.android.com/reference/androidx/constraintlayout/helper/widget/Flow

https://proandroiddev.com/awesomeness-of-constraintlayout-flow-aa0b5edd5df

https://youtu.be/tZVjF8zVGx0

Title: Android - multi-line linear layout


问:
How to get the tallest height of a div in every 3
I want to get the tallest height of a div in blocks of 3 - as I have a 3 column layout -

```<code>var maxHeight = 0;
$(".grid-item .inner .content").each(function() {
if ($(this).outerHeight() > maxHeight) {
  maxHeight = $(this).outerHeight();
}
}).height(maxHeight);
</code>```

This gets the tallest height of ".grid-item .inner .content" - but I want to get the tallest height of the first 3 ".grid-item .inner .content" divs, then set those 3 to the tallest height, then get the tallest height of the next 3 - set it again, etc etc...

Any thoughts on how to achieve this?

so i was thinking of looking at divs 1-3 - setting a var for that tallest height - then applying that to divs 1-3, then looking at divs 4-6, again get the tallest height in a var, set that var to the height of divs 4-6 but I cant get my head around how...

.content {
border: 1px solid red;
}
.grid-item {
width: 33%;
display: inline-block;
vertical-align: top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>

   function logicCall() {

    var maxHeight = 0;
       $(".grid-item .inner .content").each(function() {
        if ($(this).outerHeight() > maxHeight) {
        maxHeight = $(this).outerHeight();
        }
       }).height(maxHeight);

   }

    logicCall();

</script>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here, so this one is gonna be taller than the 1st and 3rd one...</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here for 3rd item</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>4th Content goes here</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>5th item is this one</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>6th item</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>8th item is this one</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>9th item</p>
</div>
</div>
</div></code>```

答:
While this is possible with jQuery (and JavaScript, of course) I would advise using CSS and actually using grid layout:

/* basic simple reset: */
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

.feedWrapper {
  /* here we use display: grid: */
  display: grid;
  /* a gap between adjacent rows/columns: */
  gap: 0.5em;
  /* here we define 3 columns, each taking
     an equal amount of space (so 3 columns,
     each taking 33% of the total space), but
     setting a minimum size of 10px (adjust to
     suit your preference): */
  grid-template-columns: repeat(3, minmax(10px, 1fr));
}

.inner {
  /* again, using CSS Grid layout: */
  display: grid;
  /* taking the full height of the parent: */
  height: 100%;
}

.content {
  border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="feedWrapper">

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here, so this one is gonna be taller than the 1st and 3rd one...</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here for 3rd item</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>4th Content goes here</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>5th item is this one</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>6th item</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>8th item is this one</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>9th item</p>
      </div>
    </div>
  </div>

</div></code>```

JS Fiddle demo.

There is, of course, the option to use flex layout:

/* basic simple reset: */
*,
::before,
::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

.feedWrapper {
  /* using flex layout: */
  display: flex;
  /* allowing the content to wrap to new
     lines as necessary: */
  flex-wrap: wrap;
  /* setting a gap between adjacent elements: */
  gap: 0.75em;
  justify-content: space-between;
}

.grid-item {
  /* not 33%, in order to allow some space to
     appear between adjacent columns: */
  flex-basis: 32%;
  /* spreading any leftover space between the
     elements on the same 'row': */
  justify-content: space-between;
}

.inner {
  /* using flex layout: */
  display: flex;
  /* taking all available space vertically: */
  height: 100%;
}

.content {
  border: 1px solid red;
  /* allowing the element to grow to occupy the
     full horizontal space*/
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="feedWrapper">

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here, so this one is gonna be taller than the 1st and 3rd one...</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here for 3rd item</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>4th Content goes here</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>5th item is this one</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>6th item</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>8th item is this one</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>9th item</p>
      </div>
    </div>
  </div>

</div></code>```

JS Fiddle demo.

Body:
I want to get the tallest height of a div in blocks of 3 - as I have a 3 column layout -

var maxHeight = 0;
$(".grid-item .inner .content").each(function() {
if ($(this).outerHeight() > maxHeight) {
  maxHeight = $(this).outerHeight();
}
}).height(maxHeight);

This gets the tallest height of ".grid-item .inner .content" - but I want to get the tallest height of the first 3 ".grid-item .inner .content" divs, then set those 3 to the tallest height, then get the tallest height of the next 3 - set it again, etc etc...

Any thoughts on how to achieve this?

so i was thinking of looking at divs 1-3 - setting a var for that tallest height - then applying that to divs 1-3, then looking at divs 4-6, again get the tallest height in a var, set that var to the height of divs 4-6 but I cant get my head around how...

.content {
border: 1px solid red;
}
.grid-item {
width: 33%;
display: inline-block;
vertical-align: top;
}

Content goes here

Content goes here, so this one is gonna be taller than the 1st and 3rd one...

Content goes here for 3rd item

4th Content goes here

5th item is this one

6th item

7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,

8th item is this one

9th item

Body:
While this is possible with jQuery (and JavaScript, of course) I would advise using CSS and actually using grid layout:

/* basic simple reset: */
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

.feedWrapper {
  /* here we use display: grid: */
  display: grid;
  /* a gap between adjacent rows/columns: */
  gap: 0.5em;
  /* here we define 3 columns, each taking
     an equal amount of space (so 3 columns,
     each taking 33% of the total space), but
     setting a minimum size of 10px (adjust to
     suit your preference): */
  grid-template-columns: repeat(3, minmax(10px, 1fr));
}

.inner {
  /* again, using CSS Grid layout: */
  display: grid;
  /* taking the full height of the parent: */
  height: 100%;
}

.content {
  border: 1px solid red;
}

<div class="feedWrapper">

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here, so this one is gonna be taller than the 1st and 3rd one...</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here for 3rd item</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>4th Content goes here</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>5th item is this one</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>6th item</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>8th item is this one</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>9th item</p>
      </div>
    </div>
  </div>

</div>

JS Fiddle demo.

There is, of course, the option to use flex layout:

/* basic simple reset: */
*,
::before,
::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

.feedWrapper {
  /* using flex layout: */
  display: flex;
  /* allowing the content to wrap to new
     lines as necessary: */
  flex-wrap: wrap;
  /* setting a gap between adjacent elements: */
  gap: 0.75em;
  justify-content: space-between;
}

.grid-item {
  /* not 33%, in order to allow some space to
     appear between adjacent columns: */
  flex-basis: 32%;
  /* spreading any leftover space between the
     elements on the same 'row': */
  justify-content: space-between;
}

.inner {
  /* using flex layout: */
  display: flex;
  /* taking all available space vertically: */
  height: 100%;
}

.content {
  border: 1px solid red;
  /* allowing the element to grow to occupy the
     full horizontal space*/
  flex-grow: 1;
}

<div class="feedWrapper">

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here, so this one is gonna be taller than the 1st and 3rd one...</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>Content goes here for 3rd item</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>4th Content goes here</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>5th item is this one</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>6th item</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>8th item is this one</p>
      </div>
    </div>
  </div>

  <div class="grid-item">
    <div class="inner">
      <div class="content">
        <p>9th item</p>
      </div>
    </div>
  </div>

</div>

JS Fiddle demo.


问:
ERR_SSL_VERSION_OR_CIPHER_MISMATCH error on Chrome only
While opening my private website, I am getting the following error in CHROME only.  in internet explorer its working without any issue.

I tried resetting chrome, delete all cache but no luck. nothing changed from backend site and error was started as of sudden.

weird thing is, if I open Fiddler 4 at the same time then its working. don't know what Fiddler is doing to fix that prob but when I close it again, then its again giving the same error.

答: This has started happening with Chrome v98. If you downgrade to Chrome v97 it will work again. I'm not sure what changed between versions.</p>


问:
Map of List: Sum all the values of the list class
I have this class

```<code>public Car(Colour colour, int passengers) {
    this.colour = colour;
    this.passengers = passengers;
}
</code>```

Where Colour is an enum:

```<code>   public enum Colour {
    RED, YELLOW, GREEN, BLACK, WHITE, BLUE, GREY
}
</code>```

I have created this map:

```<code>Map<Colour, List<Car>> colourListMap = new HashMap<>();
</code>```

Imagine we populate the map of lists:

```<code>Car yellowCar = new Car(Colour.YELLOW, 4);
Car blueCar = new Car(Colour.BLUE, 1);
Car blackCar = new Car(Colour.BLACK, 3);

Map<Colour, List<Car>> map = carMemory.addCarByColour(yellowCar);
carMemory.addCarByColour(blueCar);
carMemory.addCarByColour(blackCar);
</code>```

As well with 2 instances of the same colour:

```<code>Car redCar = new Car(Colour.RED, 2);
Car redCar2 = new Car(Colour.RED, 6);
Map<Colour, List<Car>> map = carMemory.addCarByColour(redCar);
carMemory.addCarByColour(redCar2);
</code>```

Is there a simple way to sum all the passengers from the Car class? Instead to call the key by Colour? I was thinking to Java 8 Stream... but I m not very confident.

I know this isn't correct.

```<code>int size =  map.values()
                .stream()
                .mapToInt(Collection::size)
                .sum();
</code>```

答:
If you need a sum of all the passengers for all cars in the map that will do the job:

```<code>            map.values()
                .stream()
                .flatMap(List::stream) // Stream of car objects
                .mapToInt(Car::getPassengers)
                .sum();
</code>```

Example for filtering colors:

```<code>           map.entrySet()
                .stream()
                .filter(entry -> entry.getKey() == Colour.RED ||
                                 entry.getKey() == Colour.BLACK) // only entries for BLACK and RED will remain
                .map(Map.Entry::getValue) // Stream<List<Car>>
                .flatMap(List::stream) // Stream<Car>
                .mapToInt(Car::getPassengers)
                .sum();
</code>```

Side note:

instead of HashMap for a Map with enum-keys use EnumMap, this special-purpose implementation is designed to be used only with enums and has better performance.

Body:
I have this class

public Car(Colour colour, int passengers) {
    this.colour = colour;
    this.passengers = passengers;
}

Where Colour is an enum:

   public enum Colour {
    RED, YELLOW, GREEN, BLACK, WHITE, BLUE, GREY
}

I have created this map:

Map<Colour, List<Car>> colourListMap = new HashMap<>();

Imagine we populate the map of lists:

Car yellowCar = new Car(Colour.YELLOW, 4);
Car blueCar = new Car(Colour.BLUE, 1);
Car blackCar = new Car(Colour.BLACK, 3);

Map<Colour, List<Car>> map = carMemory.addCarByColour(yellowCar);
carMemory.addCarByColour(blueCar);
carMemory.addCarByColour(blackCar);

As well with 2 instances of the same colour:

Car redCar = new Car(Colour.RED, 2);
Car redCar2 = new Car(Colour.RED, 6);
Map<Colour, List<Car>> map = carMemory.addCarByColour(redCar);
carMemory.addCarByColour(redCar2);

Is there a simple way to sum all the passengers from the Car class? Instead to call the key by Colour? I was thinking to Java 8 Stream... but I m not very confident.

I know this isn't correct.

int size =  map.values()
                .stream()
                .mapToInt(Collection::size)
                .sum();

Body:
If you need a sum of all the passengers for all cars in the map that will do the job:

            map.values()
                .stream()
                .flatMap(List::stream) // Stream of car objects
                .mapToInt(Car::getPassengers)
                .sum();

Example for filtering colors:

           map.entrySet()
                .stream()
                .filter(entry -> entry.getKey() == Colour.RED ||
                                 entry.getKey() == Colour.BLACK) // only entries for BLACK and RED will remain
                .map(Map.Entry::getValue) // Stream<List<Car>>
                .flatMap(List::stream) // Stream<Car>
                .mapToInt(Car::getPassengers)
                .sum();

Side note:

instead of HashMap for a Map with enum-keys use EnumMap, this special-purpose implementation is designed to be used only with enums and has better performance.


问:
Google Cloud translate JSON file
I would like to translate the fields of a composite JSON object using Google Cloud Platform, instead of translating every single sentence on its own. Is it possible?

Example (from English to Italian):

Origin JSON file:

```<code>{job_description: {
    name: "Taxi driver",
    description: "like the movie"
    }
}
</code>```

Output JSON file:

```<code>{job_description: {
    name: "Tassista",
    description: "Come nel film"
    }
}
</code>```

答:
{
"meta": {
"language": "German",
"language_locale": "Deutsch",
"author": "Maskabor (www.kvor.net)",
"gameversion": "1.0"
},
"stats": {
"ammoCost": "Munitionskosten",
"battleTier": "Gefechtsstufe",
"battles": "Gefechte",
"battlesInVehicle": "Gefechte im Panzer",
"battlesWon": "Gefechte gewonnen",
"bonds": "Anleihen",
"bondsCost": "Anleihen ausgeg.",
"bondsIncome": "Anleihen erhalten",
"bondsNett": "Anleihen Gewinn",
"bondsSpent": "Anleihen ausgeg.", # Shortened
"capturePoints": "Eroberungspunkte",
"classicBattles": "Gefechte:",
"classicDef": "Abgewehrt:",
"classicDmg": "Schaden:",
"classicEconomy": "Gesamt",
"classicGold": "Gold",
"classicKills": "Abschüsse:",
"classicLabelAvg": "Durchschnitt:",
"classicLabelTotal": "Gesamt:",
"classicLabelXpc": "XPC:",
"classicSpot": "Aufgeklärt:",
"classicTier": "Stufe",
"classicWN8": "WN8:",
"classicXP": "Erfahrung:",
"consumableCost": "Ausrüstung Kosten",
"creditsGross": "Kredit erhalten",
"creditsNett": "Kredit Gewinn",
"creditsSpent": "Kredit ausgegeben",
"crewXP": "Besatzung Erfahr.", # Shortened
"damage": "Schaden",
"damageAssisted": "Unterstütz. schaden", # Shortened
"damageSniper": "Schaden über 300m",
"damageSpot": "Schaden aufgeklärt",
"damageTrack": "Schaden fahrwerk", # Changed
"defencePoints": "Verteidigungspunkte",
"freeXP": "Freie Erfahrung",
"goldGross": "Gold erhalten",
"goldNett": "Gold Gewinn",
"goldSpent": "Gold ausgegeben",
"kills": "Abschüsse",
"moe": "Erfolgsmark. Wert",
"moeChange": "Erfolgsmark. Änder.", # Shortened
"moeChangeFirst": "Erfolgsmark. Wert", # Shortened
"moeChangeLast": "Erfolgsmark. Wert", # Shortened
"moeDamage": "Erfolgsmark. Schaden", # Shortened
"moeDamageWithReq": "Erfolgsmark.", # Shortened
"moeDmgNeeded65": "1. Erfolgsmark.", # Shortened
"moeDmgNeeded85": "2. Erfolgsmark.", # Shortened
"moeDmgNeeded95": "3. Erfolgsmark.", # Shortened
"moeDmgNeededNextMark": "Nächste Erfolgsmark.", # Shortened
"originalXP": "Erfahrungspunkte",
"placeInTeam": "Platz im Team",
"potentialDamageReceived": "Pot. Schaden erhalten.", # Potentieller Schaden erhalten
"repairCost": "Reparaturkosten",
"shotsReceivedGold": "Premium Munition Treffer erhalten", # Too long
"shotsReceivedCredits": "Treffer erhalten Kreditpunkte", # Too long
"spot": "Aufgeklärt",
"survived": "Überlebt",
"tier": "Stufe",
"tier1Below": "Stufe - 1",
"tier2Below": "Stufe - 2",
"tierDiff1": "1. Stufe Unterschied",
"tierDiff2": "2. Stufe Unterschied",
"tierDiff3": "3. Stufe Unterschied",
"tierTop": "Top Stufe", # changed
"WN8": "WN8",
"wn8ExpectedDamage": "WN8 erwarteter Schaden",
"wn8ExpectedKills": "WN8 erwartete Abschüsse",
"xp": "Erfahrung"
},
"interface": {
"battleTypeEpic": "Großgefechte",
"battleTypeFrontline": "Frontlinie",
"battleTypeRandom": "Zufallsgefecht",
"battleTypeRanked": "Gewertet",
"battleTypeStrongholdMap": "Festung:Gefechte",
"battleTypeStrongholdSkirmishes": "Bollwerk",
"battleTypeTeamUnranked": "Team Gefecht",
"battleTypesShown": "Gefechtsart Anzeigen",
"buttonInfo": "Schaltfläche Zusatzinformation",
"buttonInfoBlank": "Nichts",
"buttonInfoClock": "Uhr",
"buttonInfoDefault": "Standard",
"buttonInfoWN8": "WN8",
"font": "Schriftart",
"fontSelect": "Schriftart wählen",
"fontSizeSelect": "Schriftgröße wählen",
"liveStatsDragText": "STRG drücken CTRL\nicht drücken",
"liveStatsMOE": "FTM",
"liveStatsWN8": "WN8",
"noBattlesPlayed": "Gefechte gespielt",
"reloadConfig": "Konfiguration laden",
"reset": "Zurücksetzen",
"restore": "Wiederherstellen",
"setup": "EINSTELLUNGEN",
"actual": "Aktuell",
"expected": "Erwartet",
"total": "Gesamt",
"average": "Durchschnitt",
"wn8SourceDistribution": "WN8 Quelle",
"tierPlacement": "Stufe",
"tierDifference": "Stufen Unterschied",
"wn8Expected": "WN8 erwartet",
"export": "Export",
"exportSelect": "Exportpfad: ",
"exportSavedTo": "Export gespeichert unter:",
"session": "Sitzung",
"buildInSessionStats": "Eingebaute Sitzungs-Statistik",
"buildInSessionStatsShow": "Zeigen",
"buildInSessionStatsHide": "Verbergen",
"language": "Sprache", # computer translated
"localesSelect": "Sprache auswählen" # computer translated
}
}</p>

Title: Google Cloud translate JSON file

Body:
I would like to translate the fields of a composite JSON object using Google Cloud Platform, instead of translating every single sentence on its own. Is it possible?

Example (from English to Italian):

Origin JSON file:

{job_description: {
    name: "Taxi driver",
    description: "like the movie"
    }
}

Output JSON file:

{job_description: {
    name: "Tassista",
    description: "Come nel film"
    }
}