问:
Snakemake on gatk VariantRecalibrator
I am new in using snakemake, I have an issue when doing the step gatk VariantRecalibrator on snakemake, it generated error but the script can run without error when not in snakemake format.

```<code>import snakemake.io
import os

REF="/data/data/reference/refs/ucsc.hg19.fasta"
HM="/data/data/variant_call/hapmap_3.3.hg19.sites.vcf"
OMNI="/data/data/variant_call/1000G_omni2.5.hg19.sites.vcf"
SNPS="/data/data/variant_call/1000G_phase1.snps.high_confidence.hg19.sites.vcf"
DBSNP="/data/data/variant_call/dbsnp_138.hg19.vcf"

NAME="CHS"

rule all:
  input:  "VCFs/{name}.recal.vcf".format(name=NAME),
          "VCFs/{name}.output.tranches".format(name=NAME)

rule vqsr:
  input:  vcf="VCFs/SRS008640.raw.vcf",
          ref=REF,
          hm=HM,
          omni=OMNI,
          snps=SNPS,
          dbsnp=DBSNP
  output: recal="VCFs/{name}.recal.vcf".format(name=NAME),
          tranches="VCFs/{name}.output.tranches".format(name=NAME),
          rscript="VCFs/{name}.output.plots.R".format(name=NAME)
  params: java_opts="-Xmx16g"
  shell: "gatk --java-options -Xmx16g VariantRecalibrator \
  -R {input.ref} \
  -V {input.vcf} \
  --resource:hapmap,known=false,training=true,truth=true,prior=15.0 {input.hm} \
  --resource:omni,known=false,training=true,truth=false,prior=12.0 {input.omni} \
  --resource:1000G,known=false,training=true,truth=false,prior=10.0 {input.snps} \
  --resource:dbsnp,known=true,training=false,truth=false,prior=2.0 {input.dbsnp} \
  -an QD -an MQ -an MQRankSum -an ReadPosRankSum -an FS -an SOR \
  -mode SNP \
  -O {output.recal} \
  --tranches-file {output.tranches} \
  --rscript-file {output.rscript}"
</code>```

Error:
Set the system property GATK_STACKTRACE_ON_USER_EXCEPTION (--java-options '-DGATK_STACKTRACE_ON_USER_EXCEPTION=true') to p rint the stack trace.
    [Thu May 30 08:05:30 2019]
    Error in rule vqsr:
        jobid: 1
        output: VCFs/CHS.recal.vcf, VCFs/CHS.output.tranches, VCFs/CHS.output.plots.R

```<code>RuleException:
CalledProcessError in line 28 of /data/data/Samples/snakemake-example/WGS-test/step7.smk:
    Command ' set -euo pipefail;  gatk --java-options -Xmx16g VariantRecalibrator   -R /data/data/reference/refs/ucsc.hg19.fas ta   -V VCFs/SRS008640.raw.vcf   --resource:hapmap,known=false,training=true,truth=true,prior=15.0 /data/data/variant_call /hapmap_3.3.hg19.sites.vcf   --resource:omni,known=false,training=true,truth=false,prior=12.0 /data/data/variant_call/1000 G_omni2.5.hg19.sites.vcf   --resource:1000G,known=false,training=true,truth=false,prior=10.0 /data/data/variant_call/1000G _phase1.snps.high_confidence.hg19.sites.vcf   --resource:dbsnp,known=true,training=false,truth=false,prior=2.0 /data/data/ variant_call/dbsnp_138.hg19.vcf   -an QD -an MQ -an MQRankSum -an ReadPosRankSum -an FS -an SOR   -mode SNP   -O VCFs/CHS. recal.vcf   --tranches-file VCFs/CHS.output.tranches   --rscript-file VCFs/CHS.output.plots.R ' returned non-zero exit sta tus 2.
      File "/data/data/Samples/snakemake-example/WGS-test/step7.smk", line 28, in __rule_vqsr
      File "/root/miniconda3/envs/bioinfo/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    Removing output files of failed job vqsr since they might be corrupted:
    VCFs/CHS.recal.vcf, VCFs/CHS.output.tranches, VCFs/CHS.output.plots.R
    Shutting down, this might take some time.
    Exiting because a job execution failed. Look above for error message
    Complete log: /data/data/Samples/snakemake-example/WGS-test/.snakemake/log/2019-05-30T065011.676785.snakemake.log
</code>```

If I use the same code, I can run to create the recal file and tranches and can go to the next step applyvqsr, however if I put it in the snakemake it has error and line 27 is gatk --java-options -Xmx16g VariantRecalibrator is error but I don't know what error is it. Please advice.

答:
I would advise you to run Snakemake with the --printshellcmds parameter. That would give you exact command that it runs in your shell (not the one that you get in the exception which comes from python guts). You may copy that command and run manually.

Let me clarify this: Snakemake runs the command not as you specify it in the shell section, but it runs a subprocess, adds additional parameters and sets the environment variables (both differ depending on the shell and OS), then it uses python facilities to run an application. Running Snakemake with the --printshellcmds parameter would allow you to see the command free of formatting issues (when all wildcards are resolved) but without the overhead of details like set -euo pipefail;.

Title: Snakemake on gatk VariantRecalibrator

Body:
I am new in using snakemake, I have an issue when doing the step gatk VariantRecalibrator on snakemake, it generated error but the script can run without error when not in snakemake format.

import snakemake.io
import os

REF="/data/data/reference/refs/ucsc.hg19.fasta"
HM="/data/data/variant_call/hapmap_3.3.hg19.sites.vcf"
OMNI="/data/data/variant_call/1000G_omni2.5.hg19.sites.vcf"
SNPS="/data/data/variant_call/1000G_phase1.snps.high_confidence.hg19.sites.vcf"
DBSNP="/data/data/variant_call/dbsnp_138.hg19.vcf"

NAME="CHS"

rule all:
  input:  "VCFs/{name}.recal.vcf".format(name=NAME),
          "VCFs/{name}.output.tranches".format(name=NAME)

rule vqsr:
  input:  vcf="VCFs/SRS008640.raw.vcf",
          ref=REF,
          hm=HM,
          omni=OMNI,
          snps=SNPS,
          dbsnp=DBSNP
  output: recal="VCFs/{name}.recal.vcf".format(name=NAME),
          tranches="VCFs/{name}.output.tranches".format(name=NAME),
          rscript="VCFs/{name}.output.plots.R".format(name=NAME)
  params: java_opts="-Xmx16g"
  shell: "gatk --java-options -Xmx16g VariantRecalibrator \
  -R {input.ref} \
  -V {input.vcf} \
  --resource:hapmap,known=false,training=true,truth=true,prior=15.0 {input.hm} \
  --resource:omni,known=false,training=true,truth=false,prior=12.0 {input.omni} \
  --resource:1000G,known=false,training=true,truth=false,prior=10.0 {input.snps} \
  --resource:dbsnp,known=true,training=false,truth=false,prior=2.0 {input.dbsnp} \
  -an QD -an MQ -an MQRankSum -an ReadPosRankSum -an FS -an SOR \
  -mode SNP \
  -O {output.recal} \
  --tranches-file {output.tranches} \
  --rscript-file {output.rscript}"

Error:
Set the system property GATK_STACKTRACE_ON_USER_EXCEPTION (--java-options '-DGATK_STACKTRACE_ON_USER_EXCEPTION=true') to p rint the stack trace.
    [Thu May 30 08:05:30 2019]
    Error in rule vqsr:
        jobid: 1
        output: VCFs/CHS.recal.vcf, VCFs/CHS.output.tranches, VCFs/CHS.output.plots.R

RuleException:
CalledProcessError in line 28 of /data/data/Samples/snakemake-example/WGS-test/step7.smk:
    Command ' set -euo pipefail;  gatk --java-options -Xmx16g VariantRecalibrator   -R /data/data/reference/refs/ucsc.hg19.fas ta   -V VCFs/SRS008640.raw.vcf   --resource:hapmap,known=false,training=true,truth=true,prior=15.0 /data/data/variant_call /hapmap_3.3.hg19.sites.vcf   --resource:omni,known=false,training=true,truth=false,prior=12.0 /data/data/variant_call/1000 G_omni2.5.hg19.sites.vcf   --resource:1000G,known=false,training=true,truth=false,prior=10.0 /data/data/variant_call/1000G _phase1.snps.high_confidence.hg19.sites.vcf   --resource:dbsnp,known=true,training=false,truth=false,prior=2.0 /data/data/ variant_call/dbsnp_138.hg19.vcf   -an QD -an MQ -an MQRankSum -an ReadPosRankSum -an FS -an SOR   -mode SNP   -O VCFs/CHS. recal.vcf   --tranches-file VCFs/CHS.output.tranches   --rscript-file VCFs/CHS.output.plots.R ' returned non-zero exit sta tus 2.
      File "/data/data/Samples/snakemake-example/WGS-test/step7.smk", line 28, in __rule_vqsr
      File "/root/miniconda3/envs/bioinfo/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    Removing output files of failed job vqsr since they might be corrupted:
    VCFs/CHS.recal.vcf, VCFs/CHS.output.tranches, VCFs/CHS.output.plots.R
    Shutting down, this might take some time.
    Exiting because a job execution failed. Look above for error message
    Complete log: /data/data/Samples/snakemake-example/WGS-test/.snakemake/log/2019-05-30T065011.676785.snakemake.log

If I use the same code, I can run to create the recal file and tranches and can go to the next step applyvqsr, however if I put it in the snakemake it has error and line 27 is gatk --java-options -Xmx16g VariantRecalibrator is error but I don't know what error is it. Please advice.


来源: stackexchange

答:
For MySQL 8:

```<code>with recursive rcte(dt_id, col, value) as (
  (
    select dt_id, col, value
    from mytable
    order by dt_id
    limit 1
  )
  union all
  select r.dt_id + interval 1 day
       , coalesce(t.col, r.col)
       , coalesce(t.value, r.value)
  from rcte r
  left join mytable t on t.dt_id = r.dt_id + interval 1 day
  where r.dt_id < (select max(dt_id) from mytable)
)
select r.col, r.dt_id, r.value
from rcte r
order by r.dt_id
</code>```

db-fiddle

The recursive query will build row by row incrementing the date starting from the first date until the last. The value (and col) is taken from the original table, which is left joined on date. If the original table doesn't have a row for a date, the value of the last row in the recursion is taken instead.

For older versions you can use your calendar table and a subquery in the left joins ON clause to get last existing values:

```<code>select b.col, c.date_id, b.value
from time_table c
left join balance b on b.dt_id = (
  select max(dt_id)
  from balance b1
  where b1.dt_id <= c.date_id
)
where c.date_id >= (select min(dt_id) from balance)
  and c.date_id <= (select max(dt_id) from balance)
</code>```

db-fiddle

Update

Since the question has changed:

```<code>select b.col, c.date_id, b.value
from (
  select col, min(dt_id) as min_dt, max(dt_id) as max_dt
  from balance
  group by col
) i
join time_table c
  on  c.date_id >= i.min_dt
  and c.date_id <= i.max_dt
left join balance b
  on  b.col = i.col
  and b.dt_id = (
    select max(dt_id)
    from balance b1
    where b1.dt_id <= c.date_id
      and b1.col = i.col
)
order by b.col, c.date_id
</code>```

db-fiddle

Make sure you have an index on (col, dt_id). In best case it would be the primary key. date_id in the time_table should also be indexed or the primary key.

ContentLicense: CC BY-SA 4.0

Title: mysql generate missing dates with previous value

Body:
Below is a mysql table which has sparse dates.

col dt_id  value
A1 2018-05-28 30
A1 2018-05-30 20
A1 2018-05-31 50
A1 2018-06-01 50
A1 2018-06-04 80
A1 2018-06-05 50

The output should be something like below where missing dates are populated along with the last value.

col dt_id  value
A1 2018-05-28 30
A1 2018-05-29 30
A1 2018-05-30 20
A1 2018-05-31 50
A1 2018-06-01 50
A1 2018-06-02 50
A1 2018-06-03 50
A1 2018-06-04 80
A1 2018-06-05 50

here the following were generated.

A1 2018-05-29 30
A1 2018-06-02 50
A1 2018-06-03 50

I know solutions with oracle using last_value() over (partition by.., but since this is mysql, its a bit tricky.

Here is what i've tried:

create a time table and populate with data:

CREATE TABLE `time_table` (date_id date not null);
create table ints ( i tinyint ); insert into ints values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);

insert into time_table (date_id) select date('2016-09-01')+ interval a.i*10000 + b.i*1000 + c.i*100 + d.i*10 + e.i day
from ints a
join ints b
join ints c
join ints d
join ints e
where (a.i*10000 + b.i*1000 + c.i*100 + d.i*10 + e.i) <= 11322 order by 1;

select * from time_table limit 10;
+------------+
| date_id    |
+------------+
| 2018-09-22 |
| 2018-09-21 |
| 2018-09-20 |
| 2018-09-19 |
| 2018-09-18 |
| 2018-09-17 |
| 2018-09-16 |
| 2018-09-15 |
| 2018-09-14 |
| 2018-09-13 |
+------------+

Here is the data for the balance table:
Here is the data
+------+------------+-------+
| A1   | 2018-05-28 |    30 |
| A1   | 2018-05-30 |    20 |
| A1   | 2018-05-31 |    50 |
| A1   | 2018-06-01 |    50 |
| A1   | 2018-06-04 |    80 |
| A1   | 2018-06-05 |    50 |
| B1   | 2018-05-28 |    30 |
| B1   | 2018-05-30 |    20 |
| B1   | 2018-05-31 |    50 |
| B1   | 2018-06-01 |    50 |
| B1   | 2018-06-04 |    80 |
| B1   | 2018-06-05 |    50 |
| C1   | 2018-05-28 |    30 |
| C1   | 2018-05-30 |    20 |
| C1   | 2018-05-31 |    50 |
| C1   | 2018-06-01 |    50 |
| C1   | 2018-06-04 |    80 |
| C1   | 2018-06-05 |    50 |
| D1   | 2018-06-28 |    30 |
| D1   | 2018-07-02 |    20 |
| D1   | 2018-07-04 |    50 |
| D1   | 2018-07-08 |    80 |
| D1   | 2018-07-19 |    50 |
+------+------------+-------+

mysql> select b.id, ab.id, tt.`date_id` as cal_date, b.`mx` as ex_date, val
    -> from time_table tt
    -> inner join (select id, min(date_id) mi, max(date_id) mx from balance group by id) b
    -> on tt.`date_id` >= b.`mi`
    -> and tt.`date_id` <= b.mx
    -> left join (select id, date_id, sum(value) val from balance group by id, date_id) ab
    -> on ab.id = b.id and tt.`date_id` = ab.date_id
    -> order by cal_date;
+------+------+------------+------------+------+
| id   | id   | cal_date   | ex_date    | val  |
+------+------+------------+------------+------+
| A1   | A1   | 2018-05-28 | 2018-06-05 |   30 |
| A1   | NULL | 2018-05-29 | 2018-06-05 | NULL |
| A1   | A1   | 2018-05-30 | 2018-06-05 |   20 |
| A1   | A1   | 2018-05-31 | 2018-06-05 |   50 |
| A1   | A1   | 2018-06-01 | 2018-06-05 |   50 |
| A1   | NULL | 2018-06-02 | 2018-06-05 | NULL |
| A1   | NULL | 2018-06-03 | 2018-06-05 | NULL |
| A1   | A1   | 2018-06-04 | 2018-06-05 |   80 |
| A1   | A1   | 2018-06-05 | 2018-06-05 |   50 |
+------+------+------------+------------+------+

Body:
For MySQL 8:

with recursive rcte(dt_id, col, value) as (
  (
    select dt_id, col, value
    from mytable
    order by dt_id
    limit 1
  )
  union all
  select r.dt_id + interval 1 day
       , coalesce(t.col, r.col)
       , coalesce(t.value, r.value)
  from rcte r
  left join mytable t on t.dt_id = r.dt_id + interval 1 day
  where r.dt_id < (select max(dt_id) from mytable)
)
select r.col, r.dt_id, r.value
from rcte r
order by r.dt_id

db-fiddle

The recursive query will build row by row incrementing the date starting from the first date until the last. The value (and col) is taken from the original table, which is left joined on date. If the original table doesn't have a row for a date, the value of the last row in the recursion is taken instead.

For older versions you can use your calendar table and a subquery in the left joins ON clause to get last existing values:

select b.col, c.date_id, b.value
from time_table c
left join balance b on b.dt_id = (
  select max(dt_id)
  from balance b1
  where b1.dt_id <= c.date_id
)
where c.date_id >= (select min(dt_id) from balance)
  and c.date_id <= (select max(dt_id) from balance)

db-fiddle

Update

Since the question has changed:

select b.col, c.date_id, b.value
from (
  select col, min(dt_id) as min_dt, max(dt_id) as max_dt
  from balance
  group by col
) i
join time_table c
  on  c.date_id >= i.min_dt
  and c.date_id <= i.max_dt
left join balance b
  on  b.col = i.col
  and b.dt_id = (
    select max(dt_id)
    from balance b1
    where b1.dt_id <= c.date_id
      and b1.col = i.col
)
order by b.col, c.date_id

db-fiddle

Make sure you have an index on (col, dt_id). In best case it would be the primary key. date_id in the time_table should also be indexed or the primary key.


问:
How to authenticate to Google Analytics Reporting API v4
I'm into trouble to authenticate to Google Analytics Reporting API v4 using Node.js client library.
I tried all methods, starting with JWT (Service Tokens : JSON & P12), API Keys and OAuth 2.0, but i've never successfully been authenticated.

I activated the API in my developer console, created IDs and granted the rights on my google analytics property and view.
I successfully get authorization and an access token for my service account but i don't know how to use it to authenticate to Analytics Reporting API v4.

I'm stuck in front of an 401 error message : "The request does not have valid authentication credentials".
I tried using JWT impersonate user, but then the service account is unauthorized.

Using Node.js client library and JWT Authentication :

```<code>var google = require('googleapis.js');

var viewID = 'XXXXXXXXX'; // Google Analytics view ID
var key = require('service_account.json'); // Service account

var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/analytics.readonly'], null);
var oauth2Client = new google.auth.OAuth2();

jwtClient.authorize(function(err, result) {
  if (err) {
    console.log('Unauthorize');
    console.log(err);
    return;
  }

  oauth2Client.setCredentials({
    access_token: result.access_token
  });

  //Need to authenticate somewhere near here
  var analytics = google.analyticsreporting('v4');
  //Or here

  var req = {
    reportRequests: [
      {
        viewId: viewID,
        dateRanges: [
          {
            startDate: '2016-05-01',
            endDate: '2016-06-30',
          },],
        metrics: [
          {
            expression: 'ga:users',
          }, {
            expression: 'ga:sessions',
          },],
      },],
  };

  //Maybe here
  analytics.reports.batchGet(req,
    function(err, response) {
      if (err) {
        console.log('Fail');
        console.log(err);
        return;
      }
      console.log('Success');
      console.log(response);
    }
  );
});
</code>```

Previous releases of Node.js client library seems to have a method to specify the client but it disappeared, maybe deprecated.

```<code>withAuthClient(oauth2Client)
</code>```

I've tried to pass the client or the token in the API call or in the request, but none works.

```<code>google.analyticsreporting({ version: 'v4', auth: oauth2Client });
google.analyticsreporting({ version: 'v4', access_token: result.access_token });
</code>```

Maybe it's a noob question but i don't know how to do it, i don't see anything related to Analytics Reporting v4 authentication in the google api or client library documentation, and most examples i found uses Google Analytics API v3.

If someone managed to successfully authenticate to Analytics Reporting API v4, please help :/

答:
This is how I was able to do it:

You will need to create your credentials for your application here: https://console.developers.google.com/apis. This will give you a client ID and client secret (Note - please make sure https://developers.google.com/oauthplayground as an authorized redirect uri). Then go to https://developers.google.com/oauthplayground to create authorization tokens. The access token you are given should be sent to the Google API through the header and value: "Authorization" : "Bearer {{AccessToken}}". If your token expires, you can retrieve a new one by hitting the OAUTH api (https://www.googleapis.com/oauth2/v4/token), sending refresh_token, client_id, client_secret, grant_type and access_type in the query and 'user-agent': 'google-oauth-playground' in the header.

If you get stuck, implement the google API the way they describe here: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-js. You can then use developer tools in a browser to see exactly what values are being sent where.

Hope this helps. :)

ContentLicense: CC BY-SA 3.0

Body:
I'm into trouble to authenticate to Google Analytics Reporting API v4 using Node.js client library.
I tried all methods, starting with JWT (Service Tokens : JSON & P12), API Keys and OAuth 2.0, but i've never successfully been authenticated.

I activated the API in my developer console, created IDs and granted the rights on my google analytics property and view.
I successfully get authorization and an access token for my service account but i don't know how to use it to authenticate to Analytics Reporting API v4.

I'm stuck in front of an 401 error message : "The request does not have valid authentication credentials".
I tried using JWT impersonate user, but then the service account is unauthorized.

Using Node.js client library and JWT Authentication :

var google = require('googleapis.js');

var viewID = 'XXXXXXXXX'; // Google Analytics view ID
var key = require('service_account.json'); // Service account

var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/analytics.readonly'], null);
var oauth2Client = new google.auth.OAuth2();

jwtClient.authorize(function(err, result) {
  if (err) {
    console.log('Unauthorize');
    console.log(err);
    return;
  }

  oauth2Client.setCredentials({
    access_token: result.access_token
  });

  //Need to authenticate somewhere near here
  var analytics = google.analyticsreporting('v4');
  //Or here

  var req = {
    reportRequests: [
      {
        viewId: viewID,
        dateRanges: [
          {
            startDate: '2016-05-01',
            endDate: '2016-06-30',
          },],
        metrics: [
          {
            expression: 'ga:users',
          }, {
            expression: 'ga:sessions',
          },],
      },],
  };

  //Maybe here
  analytics.reports.batchGet(req,
    function(err, response) {
      if (err) {
        console.log('Fail');
        console.log(err);
        return;
      }
      console.log('Success');
      console.log(response);
    }
  );
});

Previous releases of Node.js client library seems to have a method to specify the client but it disappeared, maybe deprecated.

withAuthClient(oauth2Client)

I've tried to pass the client or the token in the API call or in the request, but none works.

google.analyticsreporting({ version: 'v4', auth: oauth2Client });
google.analyticsreporting({ version: 'v4', access_token: result.access_token });

Maybe it's a noob question but i don't know how to do it, i don't see anything related to Analytics Reporting v4 authentication in the google api or client library documentation, and most examples i found uses Google Analytics API v3.

If someone managed to successfully authenticate to Analytics Reporting API v4, please help :/


问:
Django SESSION_COOKIE_DOMAIN error
I'm trying to using SESSION_COOKIE_DOMAIN, but I get an error in any browser I try when I try to log into the admin:

```<code>Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.
</code>```

Any idea?

答: One thing you might want to look into is the setting SESSION_COOKIE_SECURE.  If it's set to True make sure you are using https.  Otherwise, set it to False and use http.

ContentLicense: CC BY-SA 2.5

Title: Django SESSION_COOKIE_DOMAIN error

Body:
I'm trying to using SESSION_COOKIE_DOMAIN, but I get an error in any browser I try when I try to log into the admin:

Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.

Any idea?


问:
Convert convert int to alphabetical value
i would like to convert int's between 1-26 to the corresponding alphabetical char letter

i saw somewhere i could use char outPut = (char)currentValue; or Convert.ToChar(currentValue however both do not seem to work. i am testing this by having the program print the char to the console. both attempts have resulted in a empty character being printed

i am making a program that takes in a char letter, converts it to an int to do some maths to it and then converts the final int back to a char letter and prints the char to the console

答:
You can offset by a character you want. In this case, I use 'a'.

```<code>Console.WriteLine((char)(5 + 'a'));
</code>```

As your range starts with 1, you need to use 'a'-1.

Body:
You can offset by a character you want. In this case, I use 'a'.

Console.WriteLine((char)(5 + 'a'));

As your range starts with 1, you need to use 'a'-1.


答:
int and char can be converted back and forth by using the ASCII table

ASCII value for A is 65. So you can get char A by doing

```<code>char a = (char) 65;
</code>```

to convert it back using the 1-26 representation just do

```<code>int num = a - 65 + 1;
</code>```

You would need to do some boundary check to make sure the number is within range of course.

Title: Convert convert int to alphabetical value

Body:
i would like to convert int's between 1-26 to the corresponding alphabetical char letter

i saw somewhere i could use char outPut = (char)currentValue; or Convert.ToChar(currentValue however both do not seem to work. i am testing this by having the program print the char to the console. both attempts have resulted in a empty character being printed

i am making a program that takes in a char letter, converts it to an int to do some maths to it and then converts the final int back to a char letter and prints the char to the console

Body:
int and char can be converted back and forth by using the ASCII table

ASCII value for A is 65. So you can get char A by doing

char a = (char) 65;

to convert it back using the 1-26 representation just do

int num = a - 65 + 1;

You would need to do some boundary check to make sure the number is within range of course.


问:
Spring-mvc controller and exception handling
Would like to ask you a best practice question where a spring-mvc controller is concerned. Please review the code below:

```<code>    @Autowired
    SomeService service;

    @RequestMapping (...)
    public @ResponseBody Response createSomething () {

       try {

            serviceResponse = service.doSomething();

            //create a success response and return

       }
       catch (SomeServiceException e) {
             //create an error response and return
       }

}
</code>```

Is the error handling to be done at the controller level normal practice? Or should the service class not be throwing exceptions like shown above. Please review and let me know.

答: A good practice with exception handling is to throw early and catch late. In your case, that would mean catching the error at the controller instead of the service. The advantage here is that you can code different controllers based on the client request (SOAP/REST/JSON...), to handle the exceptions differently. But if that logic is in the service, you have less flexibility over how to handle the return from the service, in your response to different clients.</p>

Body:
Would like to ask you a best practice question where a spring-mvc controller is concerned. Please review the code below:

    @Autowired
    SomeService service;

    @RequestMapping (...)
    public @ResponseBody Response createSomething () {

       try {

            serviceResponse = service.doSomething();

            //create a success response and return

       }
       catch (SomeServiceException e) {
             //create an error response and return
       }

}

Is the error handling to be done at the controller level normal practice? Or should the service class not be throwing exceptions like shown above. Please review and let me know.


问:
Why child process returns exit status = 32512 in unix?
In my program I'm executing given command and getting result (log, and exit status). Also my program have to support shell specific commands (i.e. commands which contains shell specific characters ~(tild),|(pipe),*). But when I try to run sh -c ls | wc in my home directory via my program it failed and its exit status was 32512, also in stderr stream "sh: ls | wc: command not found" was printed.

But the interesting thing is that the command sh -c ls | wc works correct if I run it in shell.

What is the problem? Or more preferable how can I run shell specific commands via my program (i.ec which command with which parameters should I run)?

The code part bellow is in child part after fork(). It executs the command.

tokenized_command is std::vector<std::string> where in my case "sh", "-c", "ls", "|", "wc" are stored, also I have tried to store there "sh", "-c", "\"ls | wc\"" but result is same. command is char * where full command line is stored.

```<code>        boost::shared_array<const char *> bargv(new const char *[tokenized_command.size() + 1]);
        const char **argv = bargv.get();
        for(int i = 0; i < tokenized_command.size(); ++i)
        {
            argv[i] = tokenized_command[i].c_str();
            printf("argv[%d]: %s\n", i, argv[i]); //trace
        }
        argv[tokenized_command.size()] = NULL;

        if(execvp(argv[0], (char * const *)argv) == -1)
        {
            fprintf(stderr, "Failed to execute command %s: %s", command, strerror(errno));
            _exit(EXIT_FAILURE);
        }
</code>```

P.S.

I know that using system(command) instead execvp can solve my problem. But system() waits until command is finished, and this is not good enough for my program. And also I'm sure that in implementation of system() one of exec-family functions is used, so the problem can be solved via exec as well, but I don't know how.

答:
You should execute sh -c 'ls | wc'.

Option -c expects a command in form of string. In shell of course it is working, because there is no difference between spawning ls and redirecting output to wc and launching ls | wc in separate shell.

Body:
In my program I'm executing given command and getting result (log, and exit status). Also my program have to support shell specific commands (i.e. commands which contains shell specific characters ~(tild),|(pipe),*). But when I try to run sh -c ls | wc in my home directory via my program it failed and its exit status was 32512, also in stderr stream "sh: ls | wc: command not found" was printed.

But the interesting thing is that the command sh -c ls | wc works correct if I run it in shell.

What is the problem? Or more preferable how can I run shell specific commands via my program (i.ec which command with which parameters should I run)?

The code part bellow is in child part after fork(). It executs the command.

tokenized_command is std::vector<std::string> where in my case "sh", "-c", "ls", "|", "wc" are stored, also I have tried to store there "sh", "-c", "\"ls | wc\"" but result is same. command is char * where full command line is stored.

        boost::shared_array<const char *> bargv(new const char *[tokenized_command.size() + 1]);
        const char **argv = bargv.get();
        for(int i = 0; i < tokenized_command.size(); ++i)
        {
            argv[i] = tokenized_command[i].c_str();
            printf("argv[%d]: %s\n", i, argv[i]); //trace
        }
        argv[tokenized_command.size()] = NULL;

        if(execvp(argv[0], (char * const *)argv) == -1)
        {
            fprintf(stderr, "Failed to execute command %s: %s", command, strerror(errno));
            _exit(EXIT_FAILURE);
        }

P.S.

I know that using system(command) instead execvp can solve my problem. But system() waits until command is finished, and this is not good enough for my program. And also I'm sure that in implementation of system() one of exec-family functions is used, so the problem can be solved via exec as well, but I don't know how.


问:
Consolidate Perforce `add` and `edit` file operations
To automate Perforce staging, I face a dilemma that add and edit are two different ops and they work on files of different SCM status, i.e., "already under SCM or not".

This is different from git where staging is uniformly add.

I'd like to have something like pseudo-code:

```<code>filepath = '/path/to/myfile.ext'
if p4.is_under_scm(filepath):
    p4.edit(filepath)
else:
    p4.add(filepath)
</code>```

or better yet, simply hide the detail with:

```<code>p4.staging(filepath)
</code>```

How should I achieve this with calling p4 command-line program?. I'm not using any programming-language bindings right now.

答:
You might want to use the p4 reconcile command, which automatically opens workspace files for an action that matches their current state relative to the depot.

Keep in mind if you go this route that reconcile operates only on unopened files that are different from the depot version, so it's meant to be used after making local modifications (this is different from the standard workflow where you open a file with p4 edit prior to editing it -- the idea is that you use reconcile to fix things after the fact if you've had to work disconnected or something like that).  In addition, if you change your mind about what you're doing with the file (e.g. you delete the local copy after it's been opened for edit but before you submit), you may need to revert -k it and re-reconcile to ensure that it's open for the correct action.

For something that matches the pseudocode in your question, you probably want the p4 have command, which tells you if a local file corresponds to a depot revision (and if so which one).  p4 edit only works on a file that you have, whereas p4 add would be for a file in your workspace that does not correspond to an existing depot file.  (A very subtle point here -- it's possible for the file to map to a depot file despite not having been synced from the depot!  If that's the case you'll hit a conflict when you go to submit your add.)

Body:
To automate Perforce staging, I face a dilemma that add and edit are two different ops and they work on files of different SCM status, i.e., "already under SCM or not".

This is different from git where staging is uniformly add.

I'd like to have something like pseudo-code:

filepath = '/path/to/myfile.ext'
if p4.is_under_scm(filepath):
    p4.edit(filepath)
else:
    p4.add(filepath)

or better yet, simply hide the detail with:

p4.staging(filepath)

How should I achieve this with calling p4 command-line program?. I'm not using any programming-language bindings right now.


答:
```<code>char outPut = (char)currentValue;
</code>```

would give you a char that represents some whitespace character (since those are represented as integers up to 32.)

What you actually want is a char representing a letter. The following code will give you the ith letter of the alphabet in lowercase:

```<code>char c = (char)((int)'a' + i - 1);
</code>```

Or in uppercase:

```<code>char c = (char)((int)'A' + i - 1);
</code>```

It uses the fact that letters are represented by consecutive integers.

Body:
char outPut = (char)currentValue;

would give you a char that represents some whitespace character (since those are represented as integers up to 32.)

What you actually want is a char representing a letter. The following code will give you the ith letter of the alphabet in lowercase:

char c = (char)((int)'a' + i - 1);

Or in uppercase:

char c = (char)((int)'A' + i - 1);

It uses the fact that letters are represented by consecutive integers.


问:
change python 3.7.2 to 3.7.1 in windows
currently I am using python 3.7.2 ,I want to to change my python version with
3.7.1 ,I want only 3.7.1 not both how can I do that without changing settings
of environment variables .I have pip installed in my pc.

I have searched on many blog but they were regarding using multiple python version.

My main target is to install python vs 3.7.1 with Django 2.1.5

答:
I believe you  can specify python version when running things:

```<code>py -3 setup.py # run latest Python 3
py -2 setup.py # run latest Python 2
py -3.3
py -2.7-32 # use 32-bit version
py # run default version
</code>```

But if you want to completely get rid of the other version just uninstall and reinstall that other version....

Reminder: This is for Windows CLI only.

And like @Reez0 said, you should really look into using Virtual Environments.

Title: change python 3.7.2 to 3.7.1 in windows

Body:
I believe you  can specify python version when running things:

py -3 setup.py # run latest Python 3
py -2 setup.py # run latest Python 2
py -3.3
py -2.7-32 # use 32-bit version
py # run default version

But if you want to completely get rid of the other version just uninstall and reinstall that other version....

Reminder: This is for Windows CLI only.

And like @Reez0 said, you should really look into using Virtual Environments.


问:
Placeholder not showing on dropdown, can anybody tell me why?
I am trying to render a Dropdown with a placeholder but the placeholder doesnt render. I'm not sure why. My Dropdown is as follows.

```<code><Dropdown
  loading={loading}
  error={!!error}
  inline
  value={this.props.entityId || null}
  onChange={(e, { value }) => {
    client.writeData({data: {teamBudget: value, __typename: 'TeamBudget'}})
  }}
  options={options}
  placeholder={options ? 'Select Draft' : 'Error!'}
/>
</code>```

when I comment out value the placeholder displays as expected. Can value not be defined along with placeholder?

答:
I don't know the component you are using,
but the common convention is,

value={the value you are expecting to display inside the dropdown field}

which should be in a label value pair

eg: [{ value: '1', label: 'one' }]

i can only suspect your this.props.entityId isn't in this format.
also, that could be the reason it sabotages the placeholder.

FYI: usually, if you don't mention value={} in props, it handles it by default,
 which could be the reason it works properly when ommits...

Body:
I am trying to render a Dropdown with a placeholder but the placeholder doesnt render. I'm not sure why. My Dropdown is as follows.

<Dropdown
  loading={loading}
  error={!!error}
  inline
  value={this.props.entityId || null}
  onChange={(e, { value }) => {
    client.writeData({data: {teamBudget: value, __typename: 'TeamBudget'}})
  }}
  options={options}
  placeholder={options ? 'Select Draft' : 'Error!'}
/>

when I comment out value the placeholder displays as expected. Can value not be defined along with placeholder?


问:
Match Regular Expression in string
I'm trying to match a page location using regular expressions in JavaScript. Basically, I want to check if the string is /dashboard + any character, e.g., /dashboard, /dashboard/activity/, /dashboard/myaccount...

I tried to do it using .*: /dashboard${/.*/} but got no luck.

How should I do it?

Thanks in advance

答:
const regex = /\/dashboard(\/\w+)*/;

const test = "/dashboard/hello".match(regex)
const testA = "/dashboard/hello/world".match(regex)
const testB = "/dashboard".match(regex)
const testC = "/hello/world".match(regex)

console.log(test);
console.log(testA);
console.log(testB);
console.log(testC);```

Title: Match Regular Expression in string


问:
How can I test Component with Tapestry Testify
I am doing some tests with the tapestry-testify librairy. But I have a question about its documentation : http://tapestry.formos.com/nightly/tapestry-testify/testing-components.html

I would like to pass different value to a parameter of my component.
Could someone explain to me how can i do that.

I have the same project structure as in the documentation.

myComponent.java

public class myComponent {
    @Parameter
    @Property
    private String myParam;
}
```

<p><strong>myComponent.tml</strong></p>

<pre class="lang-html prettyprint-override"><code><fieldset xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">
    <p>test ${myParam}</p>
</fieldset>
</code>```

myComponentDemo.java

public class MyComponentDemo {
    @Inject
    @Service("myParam")
    @Property
    private String myParam;
}
```

<p><strong>myComponentDemo.tml</strong></p>

<pre class="lang-html prettyprint-override"><code><html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">
    <head>
        <title>DayMonthYearDateInputTestPage</title>
    </head>
    <body>
        <h1 id="h2">DayMonthYearDateInputTestPage</h1>

        <div t:type="myC/MyComponent" t:id="myComponent" t:myParam="myParam"/>
    </body>
</html>
</code>```

myComponentTest.java

import Perso.monAppli.demo.DemoModule;

import com.formos.tapestry.testify.core.ForComponents;
import com.formos.tapestry.testify.core.TapestryTester;
import com.formos.tapestry.testify.junit3.TapestryTest;

public class MyComponentTest extends TapestryTest {

    @ForComponents(value="myParam")
    private String myParam;

    private static final TapestryTester SHARED_TESTER = new TapestryTester("app", DemoModule.class);

    public MyComponentTest() {
        super(SHARED_TESTER);
    }

    @Test
    public void testElementIsOnPage() {
        Document page = tester.renderPage("demo/MyComponentDemo");
        System.out.println("### HTML " + page.getRootElement().getChildMarkup());
        Assert.assertTrue(page.getRootElement().getChildMarkup().contains("testMyParam"));
    }
}
```

Do I have to create a service for passing value to my component ?

Thank you for your help.

答:
I'm not sure of this, but did you try to change name of "myParam"?

For instance:

myComponentDemo.java

@Inject
@Service("myParamService")
@Property
private String myParamValue;
```

<p>myComponentDemo.tml</p>

<pre class="lang-html prettyprint-override"><code><div t:type="myC/MyComponent" t:id="myComponent" t:myParam="myParamValue"/>
</code>```

myComponentTest.java

@ForComponents("myParamService")
private String myParam;
```

Body:
I am doing some tests with the tapestry-testify librairy. But I have a question about its documentation : http://tapestry.formos.com/nightly/tapestry-testify/testing-components.html

I would like to pass different value to a parameter of my component.
Could someone explain to me how can i do that.

I have the same project structure as in the documentation.

myComponent.java

public class myComponent {
    @Parameter
    @Property
    private String myParam;
}

myComponent.tml

<fieldset xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">

test ${myParam}

</fieldset>

myComponentDemo.java

public class MyComponentDemo {
    @Inject
    @Service("myParam")
    @Property
    private String myParam;
}

myComponentDemo.tml

        <title>DayMonthYearDateInputTestPage</title>

DayMonthYearDateInputTestPage

myComponentTest.java

import Perso.monAppli.demo.DemoModule;

import com.formos.tapestry.testify.core.ForComponents;
import com.formos.tapestry.testify.core.TapestryTester;
import com.formos.tapestry.testify.junit3.TapestryTest;

public class MyComponentTest extends TapestryTest {

    @ForComponents(value="myParam")
    private String myParam;

    private static final TapestryTester SHARED_TESTER = new TapestryTester("app", DemoModule.class);

    public MyComponentTest() {
        super(SHARED_TESTER);
    }

    @Test
    public void testElementIsOnPage() {
        Document page = tester.renderPage("demo/MyComponentDemo");
        System.out.println("### HTML " + page.getRootElement().getChildMarkup());
        Assert.assertTrue(page.getRootElement().getChildMarkup().contains("testMyParam"));
    }
}

Do I have to create a service for passing value to my component ?

Thank you for your help.

Body:
I'm not sure of this, but did you try to change name of "myParam"?

For instance:

myComponentDemo.java

@Inject
@Service("myParamService")
@Property
private String myParamValue;

myComponentDemo.tml

<div t:type="myC/MyComponent" t:id="myComponent" t:myParam="myParamValue"/>

myComponentTest.java

@ForComponents("myParamService")
private String myParam;


问:
Compare a two column with the same table to remove duplicate
A sample table with two column and I need to compare the column 1 and column 2 to the same table records and need to remove the column 1 + column 2 = column 2+column 1.

I tried to do self join and case condition. But its not working

答:
I am posting the answer based on oracle database and also the columns are string/varchar:

delete from table where rowid in (
select rowid from table
where column1 || column2 =column2 || column1 )

Feel free to provide more input and we can tweak the answer.


问:
Insert if not exists?
I'm prompting a user to add an item to an SQLiteDb. When they click add, I want to check if that item already exists... if it doesn't then I want to insert it.

I make the call

```<code>mDbHelper.createNote(inputLine.getText().toString().trim(), mTable[i]);
</code>```

Which calls...

```<code>public long createNote(String value, String table) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(table, value);

        return mDb.insert(table, null, initialValues);
    }
</code>```

Thats works but it doesn't check if the item already exists, so it still inserts duplicates. So I tried

```<code>return mDb.insertWithOnConflict(table, null, initialValues, SQLiteDatabase.CONFLICT_FAIL);
</code>```

However, it doesn't appear to recognize insertWIthOnConflict or SQLiteDatabase.CONFLICT_FAIL...

How can I get this to work?

Edit: it's 1 table, 2 rows. table name = note, rows = _id, note.

答: Have you tried using a primary key that isn't set to auto-increment?  That might be why the REPLACE command isn't working</p>

Title: Insert if not exists?

Body:
I'm prompting a user to add an item to an SQLiteDb. When they click add, I want to check if that item already exists... if it doesn't then I want to insert it.

I make the call

mDbHelper.createNote(inputLine.getText().toString().trim(), mTable[i]);

Which calls...

public long createNote(String value, String table) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(table, value);

        return mDb.insert(table, null, initialValues);
    }

Thats works but it doesn't check if the item already exists, so it still inserts duplicates. So I tried

return mDb.insertWithOnConflict(table, null, initialValues, SQLiteDatabase.CONFLICT_FAIL);

However, it doesn't appear to recognize insertWIthOnConflict or SQLiteDatabase.CONFLICT_FAIL...

How can I get this to work?

Edit: it's 1 table, 2 rows. table name = note, rows = _id, note.


问:
Regex in Java for "greater than" or "less than" without using bracket "<|>" symbols
I need a regular expression for Java Pattern.compile("<|>") that would match greater than and less than symbols without actually using bracket symbols. Is there some special character that would mean ">" or "<" symbol?

Additional info: The reason is that my legacy system passes regular expressions from a resource file that first gets parsed using some html tags, and extra brackets confuse the parser, so it errors out. The solution is to substitute ">" and "<" with something else that Java Pattern would interpret as ">" and "<".

What I tried: Pattern.compile("&grt;") does not get interpreted as ">"

答:
You can simply escape those characters like:

```<code>Pattern.compile("\\<|\\>")
</code>```

By using the backslashes, you are telling regex that "use that character as is!"

For more about escaping characters, see https://www.baeldung.com/java-regexp-escape-char

Body:
You can simply escape those characters like:

Pattern.compile("\\<|\\>")

By using the backslashes, you are telling regex that "use that character as is!"

For more about escaping characters, see https://www.baeldung.com/java-regexp-escape-char


问:
How to convert wide data to long data based on three variables
I have a dataframe that is structure as such:

```<code>Item FY20 FY21 FY22 ...
Case High Low Base
Multiple 1.2 2.3 3.4
Cash 1.1 1.4 1.2
</code>```

I need the data to look like this:

```<code>Item Date Case Value
Cash FY20 High 1.1
Cash FY21 Low 1.4
Cash FY22 Base 1.2
</code>```

So I essentially want to transform the data from wide format to a long format based on "Case", the "FY"s and the item.

I've already tried using multi indexes and messed around a bit with pd.pivot but i'm honestly stumped here.

答:
Let's start from creation of your source DataFrame:

```<code>df = pd.DataFrame(data=[
    [ 'Item',     'FY20', 'FY21', 'FY22' ],
    [ 'Case',     'High', 'Low',  'Base' ],
    [ 'Multiple', 1.2,    2.3,    3.4    ],
    [ 'Cash',     1.1,    1.4,    1.2    ]])
</code>```

The result is:

```<code>          0     1     2     3
0      Item  FY20  FY21  FY22
1      Case  High   Low  Base
2  Multiple   1.2   2.3   3.4
3      Cash   1.1   1.4   1.2
</code>```

Then we have to:

transpose this DataFrame,

convert the first row into column names,

change the first column name:

To do this, run:

```<code>df2 = df.transpose()
df2.columns = df2.iloc[0].tolist()
df2.drop(index=0, inplace=True)
df2.rename(columns={'Item': 'Date'})
</code>```

The result is:

```<code>   Date  Case Multiple Cash
1  FY20  High      1.2  1.1
2  FY21   Low      2.3  1.4
3  FY22  Base      3.4  1.2
</code>```

And to get your result, run:

```<code>df2.melt(id_vars=['Date', 'Case'], value_vars=['Cash'],
    var_name='Name', value_name='Value')
</code>```

and you will receive:

```<code>   Date  Case  Name Value
0  FY20  High  Cash   1.1
1  FY21   Low  Cash   1.4
2  FY22  Base  Cash   1.2
</code>```

Or maybe the result should include also melting of Multiple column?
To achieve this, remove value_vars=['Cash'].
This way melting will include all remaining columns (other than
included in id_vars).

Body:
I have a dataframe that is structure as such:

Item FY20 FY21 FY22 ...
Case High Low Base
Multiple 1.2 2.3 3.4
Cash 1.1 1.4 1.2

I need the data to look like this:

Item Date Case Value
Cash FY20 High 1.1
Cash FY21 Low 1.4
Cash FY22 Base 1.2

So I essentially want to transform the data from wide format to a long format based on "Case", the "FY"s and the item.

I've already tried using multi indexes and messed around a bit with pd.pivot but i'm honestly stumped here.

Body:
Let's start from creation of your source DataFrame:

df = pd.DataFrame(data=[
    [ 'Item',     'FY20', 'FY21', 'FY22' ],
    [ 'Case',     'High', 'Low',  'Base' ],
    [ 'Multiple', 1.2,    2.3,    3.4    ],
    [ 'Cash',     1.1,    1.4,    1.2    ]])

The result is:

          0     1     2     3
0      Item  FY20  FY21  FY22
1      Case  High   Low  Base
2  Multiple   1.2   2.3   3.4
3      Cash   1.1   1.4   1.2

Then we have to:

transpose this DataFrame,

convert the first row into column names,

change the first column name:

To do this, run:

df2 = df.transpose()
df2.columns = df2.iloc[0].tolist()
df2.drop(index=0, inplace=True)
df2.rename(columns={'Item': 'Date'})

The result is:

   Date  Case Multiple Cash
1  FY20  High      1.2  1.1
2  FY21   Low      2.3  1.4
3  FY22  Base      3.4  1.2

And to get your result, run:

df2.melt(id_vars=['Date', 'Case'], value_vars=['Cash'],
    var_name='Name', value_name='Value')

and you will receive:

   Date  Case  Name Value
0  FY20  High  Cash   1.1
1  FY21   Low  Cash   1.4
2  FY22  Base  Cash   1.2

Or maybe the result should include also melting of Multiple column?
To achieve this, remove value_vars=['Cash'].
This way melting will include all remaining columns (other than
included in id_vars).


问:
Show text vertically and counter-clockwise in any table cells
I have the following CSS and table with choice 3 and choice 4 vertically displayed but clockwise. I would like to show choice 3 and choice 4 vertically and counter-clockwise. I am not able to find style values for text-orientation for my need.

Note that text choice 3 and choice 4 are just examples, and the real texts could be quite long. I am looking for a solution that can apply to any cells in a table (and preferably center the text horizontally if a cell's space is quite wide).

.rotate {
  writing-mode: vertical-rl;
  text-orientation: mixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td></td>
    <td>choice 1</td>
    <td>choice 2</td>
    <td>total</td>
  </tr>
  <tr>
    <td>
      <div class="rotate">choice 3</div>
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>
      <div class="rotate">choice 4</div>
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>total</td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table></code>```

Update
Here is my real table.

Here is a pic of testing display: flex

答:
Another possible solution would be to have class for both  and
 so you can give margins and give transform which supports all browsers like this:

div.rotate{
  transform: rotate(-90deg);
 -webkit-transform: rotate(-90deg); /* Safari/Chrome */
 -moz-transform: rotate(-90deg); /* Firefox */
 -o-transform: rotate(-90deg); /* Opera */
 -ms-transform: rotate(-90deg);
}

td.rotate{
  height: 60px;
  line-height: 14px;
  padding-bottom: 20px;
  text-align: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td></td>
    <td colspan="1">choice 1</td>
    <td colspan="1">choice 2</td>
    <td>total</td>
  </tr>
  <tr>
    <td class="rotate" colspan="1">
      <div class="rotate">choice 3</div>
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td class="rotate" colspan="1">
      <div class="rotate">choice 4</div>
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>total</td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table></code>```

You have have a look here for more information: https://www.broculos.net/2013/12/vertical-text-for-table-headers-with-css.html

Body:
I have the following CSS and table with choice 3 and choice 4 vertically displayed but clockwise. I would like to show choice 3 and choice 4 vertically and counter-clockwise. I am not able to find style values for text-orientation for my need.

Note that text choice 3 and choice 4 are just examples, and the real texts could be quite long. I am looking for a solution that can apply to any cells in a table (and preferably center the text horizontally if a cell's space is quite wide).

.rotate {
  writing-mode: vertical-rl;
  text-orientation: mixed;
}

    choice 1
    choice 2
    total

choice 3

choice 4

    total

Update
Here is my real table.

Here is a pic of testing display: flex

Body:
Another possible solution would be to have class for both <td> and <div> so you can give margins and give transform which supports all browsers like this:

div.rotate{
  transform: rotate(-90deg);
 -webkit-transform: rotate(-90deg); /* Safari/Chrome */
 -moz-transform: rotate(-90deg); /* Firefox */
 -o-transform: rotate(-90deg); /* Opera */
 -ms-transform: rotate(-90deg);
}

td.rotate{
  height: 60px;
  line-height: 14px;
  padding-bottom: 20px;
  text-align: inherit;
}

<table>
  <tr>
    <td></td>
    <td colspan="1">choice 1</td>
    <td colspan="1">choice 2</td>
    <td>total</td>
  </tr>
  <tr>
    <td class="rotate" colspan="1">
      <div class="rotate">choice 3</div>
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td class="rotate" colspan="1">
      <div class="rotate">choice 4</div>
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>total</td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

You have have a look here for more information: https://www.broculos.net/2013/12/vertical-text-for-table-headers-with-css.html


问:
Using Python in vimscript: How to export a value from a python script back to vim?
I'm struggling with Python in vim.

I still haven't found out how I can import a value from a python script (in a vim function) back to vim p.e.

```<code>function! myvimscript()

  python << endpython
    import vim, random, sys
    s = vim.eval("mylist")
    # do operation with variable "s" in python
  endpython

  " import variable "s" from above
  " do operation with "s" in vimscript
endfunction
</code>```

1) How can I use "s" again in vim (how can I import "s" from the python code back to vim)?

I can't find out as well how to use vim.current.buffer with a selection.

```<code>function! myvimscript()
  let startline = line("'<")
  let endline = line("'>")

  python << endpython
    start = vim.eval("startline")
    end = vim.eval("endline")
    cb = vim.current.buffer
    l = cb[start:end]
  endpython
endfunction
</code>```

2) How can I assign the dynamic value "start" and "end" to "l"

答:
As of v7.3.569, vim built-in functions pyeval() and py3eval() allow you to evaluate a python expression, and return its result as a vimscript value. It can handle simple scalar values, but also lists and dictionaries - see :help pyeval()

On 1): For using a python-defined variable in vim:

```<code>python << endPython
py_var = 8
endPython

let vim_var = pyeval('py_var')
</code>```

On 2): I assume you want the buffer lines last highlighted in visual mode, as a list of strings in vimscript:

```<code>python << endPython
import vim
cb = vim.current.buffer
start = int(vim.eval("""line("'<")"""))
end = int(vim.eval("""line("'>")"""))
lines = cb[(start - 1) : end]
endPython
let lines = pyeval('lines')
</code>```

Note: This is a somewhat contrived example, as you could get the same directly in vimscript:

```<code>let lines = getline("'<", "'>")
</code>```

Body:
I'm struggling with Python in vim.

I still haven't found out how I can import a value from a python script (in a vim function) back to vim p.e.

function! myvimscript()

  python << endpython
    import vim, random, sys
    s = vim.eval("mylist")
    # do operation with variable "s" in python
  endpython

  " import variable "s" from above
  " do operation with "s" in vimscript
endfunction

1) How can I use "s" again in vim (how can I import "s" from the python code back to vim)?

I can't find out as well how to use vim.current.buffer with a selection.

function! myvimscript()
  let startline = line("'<")
  let endline = line("'>")

  python << endpython
    start = vim.eval("startline")
    end = vim.eval("endline")
    cb = vim.current.buffer
    l = cb[start:end]
  endpython
endfunction

2) How can I assign the dynamic value "start" and "end" to "l"

Body:
As of v7.3.569, vim built-in functions pyeval() and py3eval() allow you to evaluate a python expression, and return its result as a vimscript value. It can handle simple scalar values, but also lists and dictionaries - see :help pyeval()

On 1): For using a python-defined variable in vim:

python << endPython
py_var = 8
endPython

let vim_var = pyeval('py_var')

On 2): I assume you want the buffer lines last highlighted in visual mode, as a list of strings in vimscript:

python << endPython
import vim
cb = vim.current.buffer
start = int(vim.eval("""line("'<")"""))
end = int(vim.eval("""line("'>")"""))
lines = cb[(start - 1) : end]
endPython
let lines = pyeval('lines')

Note: This is a somewhat contrived example, as you could get the same directly in vimscript:

let lines = getline("'<", "'>")


问:
external IP not being generated for elastic
I followed the commands mentioned on this page...

https://www.elastic.co/guide/en/cloud-on-k8s/current/index.html

elastic service is stared successfully. But I do not see external-ip

```<code>#  /usr/local/bin/kubectl --kubeconfig="wzone2.yaml" get service
NAME                      TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes                ClusterIP   10.245.0.1      <none>        443/TCP    10m
quickstart-es             ClusterIP   10.245.97.209   <none>        9200/TCP   3m11s
quickstart-es-discovery   ClusterIP   None            <none>        9300/TCP   3m11s
</code>```

I tried port forwarding command but that did not help.

kubectl port-forward service/quickstart-es 9200

How do I connect to this elastic server?

答: Outside of using a LoadBalancer like @coderanger suggested, you can also use a service of type NodePort.  This will allow you to connect to your service using the node IP address and without depending on cloud providers.</p>

Body:
I followed the commands mentioned on this page...

https://www.elastic.co/guide/en/cloud-on-k8s/current/index.html

elastic service is stared successfully. But I do not see external-ip

#  /usr/local/bin/kubectl --kubeconfig="wzone2.yaml" get service
NAME                      TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes                ClusterIP   10.245.0.1      <none>        443/TCP    10m
quickstart-es             ClusterIP   10.245.97.209   <none>        9200/TCP   3m11s
quickstart-es-discovery   ClusterIP   None            <none>        9300/TCP   3m11s

I tried port forwarding command but that did not help.

kubectl port-forward service/quickstart-es 9200

How do I connect to this elastic server?


问:
How to pick proper video dimension based on device resolution
We've a demo video provided by design team with three different dimension (1024*768), (2048*1536) and (2732, 2048). I'm trying to pick proper video based on current device resolution (supported format).

For eg: If it its first generation iPad its resolution is (1024 * 768) it can play video format upto 720p more than that it will not play, likewise iPad3 (Retina) resolution is (2048 * 1536) but it can play video format upto 1080p. Similar iPad pro I guess it will play upto 4k videos.

I afraid system will not pick proper video on its own if we name it to 1x, 2x or 3x like in image.

If we are passing high dimension video to low resolution devices it is not playing. So what is the general approach in iOS to pick proper video based on its support format.

答: I created a working solution for this problem by embedded m4v video data inside a PNG and then decoding and resaving the .m4v file in the tmp dir on device. Have a peek at this SO answer for details: https://stackoverflow.com/a/56383999/763355</p>


问:
How does toArray() function make sure that a list of long type can't be converted to array of Integer
```<code>    public <T> T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size,
                                     (Class<? extends T[]>) a.getClass());
            System.arraycopy(this.a, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
    }

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
</code>```

Not getting why the third parameter type for function copyOf() is Class<? extends T[]> and not simply Class<T[]> . What make's the difference between them here. Is this constraint making sure that one type of list can't be converted to other type of array.

答:
In java, Array is covariance

In Java, Integer[] is a subclass of Number[], and they are both subclasses of Object[]. This is called covariance.

In your case, that means it accept all array which is subtype of T as parameter. Obviously, more flexible than T[].

Body:
    public <T> T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size,
                                     (Class<? extends T[]>) a.getClass());
            System.arraycopy(this.a, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
    }

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

Not getting why the third parameter type for function copyOf() is Class<? extends T[]> and not simply Class<T[]> . What make's the difference between them here. Is this constraint making sure that one type of list can't be converted to other type of array.


问:
How was I able to change imported value in ES6?
```<code>//lib-es6.js

export let counter = 3;
export function incCounter() {
  counter++;
}
</code>```

From 16.7.2 section, its given that, even if we import a module via asterisk (*) the imported value cant be changed.

```<code>//main-es6.js

import * as lib from './lib-es6'; // imported via asterisk(*)

// The imported value `counter` is live
console.log(lib.counter); // 3 . => I expected this
lib.incCounter();
console.log(lib.counter); // 4 . => I expected this

/****************************************/
// But I was able to change lib.counter.
// Question: Can we change imported value in ES6 if we import it via asterisk (*)?
lib.counter++; // Not an error. ==> I DID NOT expected this.
console.log(lib.counter); // 5
/****************************************/
</code>```

答:
You are not really executing an ES module, you are executing a CommonJS module (that was transpiled from an ES module). You should get the expected result if you run this code natively:

On Node.js 12 with --experimental-modules: The new ECMAScript module support in Node.js 12

In a modern browser.

Body:
//lib-es6.js

export let counter = 3;
export function incCounter() {
  counter++;
}

From 16.7.2 section, its given that, even if we import a module via asterisk (*) the imported value cant be changed.

//main-es6.js

import * as lib from './lib-es6'; // imported via asterisk(*)

// The imported value `counter` is live
console.log(lib.counter); // 3 . => I expected this
lib.incCounter();
console.log(lib.counter); // 4 . => I expected this

/****************************************/
// But I was able to change lib.counter.
// Question: Can we change imported value in ES6 if we import it via asterisk (*)?
lib.counter++; // Not an error. ==> I DID NOT expected this.
console.log(lib.counter); // 5
/****************************************/


问:
Is there an xhtml.xsd equivalent available for HTML5?
I am developing an appplication based on Mozilla XULRunner.

I am using the xhmtl1-strict.xsd provided by the W3C to fetch the attribute. Now the requirement came to add the <video> tag to my application, but my application is not supporting any HTML5 elements or attributes.

So, any suggestions?

答:
HTML5 does not have a doctype definition or an XML schema definition. This is because, although it shares the same syntax as its predecessor HTML 4, HTML5 itself is neither based on SGML nor XML. It's a markup language in its own right.

If you are looking to implement a browser with HTML5 capabilities using Mozilla technologies, the latest version of the Gecko layout engine supports HTML5. Get the Gecko/XULRunner SDK here.


问:
BindRequired on DateTime
I have an issue with [BindRequired] attribute, it does not invalidate my model state:

```<code>public class PostModel
{
    [BindRequired]
    public DateTime Date { get; set; }
}
</code>```

Controller:

```<code>[ApiController]
public class BindTestController : ControllerBase
{
    [HttpPost("test")]
    public IActionResult SetValue([FromBody] PostModel request)
    {
        if (!ModelState.IsValid)
            return BadRequest();

        return Ok();
    }
}
</code>```

if I post a body like this:

```<code>{}
</code>```

My modelstate is valid.
What is the good way of validating that Date is present on my body, and invalidate the model ?

Thanks

答:
Add the RequiredAttribute to your DateTime property, then you need to make the DateTime nullable, otherwise you will get the default value for DateTime which is {0001-01-01T00:00:00}.

So basically do the followings:

public class PostModel
{
    [Required]
    public DateTime? Date { get; set; }
}
```

Regarding why the BindRequired did not work, I think (not 100% sure, it is just what i think) that since you are using [ApiController], it first would use [FromBody] by default, then the binding would happen after the Json.NET deserialization, so when the deserialization happens the DateTime value would be set to the Default(DateTime). To solve this you can use the old way as shown above instead of using BindRequired, or add [JsonRequired].

Note: when you use [JsonRequired] with [ApiController], validation happens before it hits your endpoint. Also note that BindRequired works well with normal MVC Controller.

Title: BindRequired on DateTime

Body:
I have an issue with [BindRequired] attribute, it does not invalidate my model state:

public class PostModel
{
    [BindRequired]
    public DateTime Date { get; set; }
}

Controller:

[ApiController]
public class BindTestController : ControllerBase
{
    [HttpPost("test")]
    public IActionResult SetValue([FromBody] PostModel request)
    {
        if (!ModelState.IsValid)
            return BadRequest();

        return Ok();
    }
}

if I post a body like this:

{}

My modelstate is valid.
What is the good way of validating that Date is present on my body, and invalidate the model ?

Thanks

Body:
Add the RequiredAttribute to your DateTime property, then you need to make the DateTime nullable, otherwise you will get the default value for DateTime which is {0001-01-01T00:00:00}.

So basically do the followings:

public class PostModel
{
    [Required]
    public DateTime? Date { get; set; }
}

Regarding why the BindRequired did not work, I think (not 100% sure, it is just what i think) that since you are using [ApiController], it first would use [FromBody] by default, then the binding would happen after the Json.NET deserialization, so when the deserialization happens the DateTime value would be set to the Default(DateTime). To solve this you can use the old way as shown above instead of using BindRequired, or add [JsonRequired].

Note: when you use [JsonRequired] with [ApiController], validation happens before it hits your endpoint. Also note that BindRequired works well with normal MVC Controller.


问:
Angular Firebase scroll issue in chrome due to images
Angular 6:  Images takes time to load in chrome

This issue is specifically in chrome and not in any other browser.

We have used Firebase in our project, and  used snapshotchange method to fetch the image to angular project from the same, the image urls are like this https://firebasestorage.googleapis.com/v0/b/test-4a5d9.appspot.com/o/download.jpg?alt=media&token=a78321fc-eb9c-496a-a690-e8b2ccddf6c6 . There is something wrong due to which, image loads very slowly and the screen becomes blank when we scroll up and down in the browser, here we have used "ngx-infinite-scroll".

I have also tried by concatenating .jpg extension after the image but the scenario remains the same.

First, I thought the problem is with the size of image which is affecting the loading speed, so then I have replaced the images with https://upload.wikimedia.org/wikipedia/commons/b/b9/Pizigani_1367_Chart_1MB.jpg which is a heavy size of image, but here the website run's smoothly without any issue.

But it does not scroll smoothly when image urls are like this https://firebasestorage.googleapis.com/v0/b/test-4a5d9.appspot.com/o/download.jpg?alt=media&token=a78321fc-eb9c-496a-a690-e8b2ccddf6c6

Here is the code to set images in one list item:

```<code><div class="slider">
                      <div class="slideshow-container" id="{{works.id}}_" *ngIf="works.media">
                        <div class="imgSlides imgsss active" *ngIf="works.media.aFront != undefined">
                          <div class="content">
                            <div>

                              <img src="{{works.media.aFront}}" alt="front img" />
                            </div>
                          </div>
                        </div>
                        <div class="imgSlides imgsss" *ngIf="works.media.bBack != undefined">
                          <div class="content">
                            <div>
                              <img src="{{works.media.bBack}}" alt="back img" />
                            </div>

                          </div>
                        </div>
                        <div class="imgSlides imgsss" *ngIf="works.media.cLeft != undefined">
                          <div class="content">
                            <div>

                              <img src="{{works.media.cLeft}}" alt="left img" />
                            </div>

                          </div>
                        </div>
                        <div class="imgSlides imgsss" *ngIf="works.media.dRight != undefined">
                          <div class="content">
                            <div>

                              <img src="{{works.media.dRight}}" alt="right img" />
                            </div>

                          </div>
                        </div>
                        <div class="imgSlides imgsss" *ngIf="works.media.ePanoroma != undefined">
                          <div class="content">
                            <div>

                              <img src="{{works.media.ePanoroma}}" alt="panoroma img" />
                            </div>
                          </div>
                        </div>
                        <div class="imgSlides imgsss" *ngIf="works.media.fDetail != undefined">
                          <div class="content">
                            <div>

                              <img src="{{works.media.fDetail}}" alt="detail img" />
                            </div>
                          </div>
                        </div>
                        <!-- arrow -->
                        <div *ngIf="works.imageCount>1">
                          <a class="next arrow-control" (click)="plusSlide(1,works.id + '_')"> <img src="assets/image/backward.png" alt="previous arrow" /> </a>
                          <a class="prev arrow-control" (click)="plusSlide(-1,works.id + '_')">  <img src="assets/image/forward.png" alt="next arrow" /> </a>
                        </div>
                        <p class="sold-btn" *ngIf="works.isSold">{{'Sold'}}</p>
                      </div>
                      <div class="slideshow-container" *ngIf="isEmptyObject(works.media)">
                        <div class="content">
                          <div [ngStyle]="{'background-image': 'url(' + defaultimg + ')'}" class="img-thumb"></div>
                        </div>
                      </div>

                      <div style="text-align:center;display:none;" class="bullets">

                      </div>
                    </div>
</code>```

Here is the video of the problem:

https://drive.google.com/file/d/1Ipl-34rOE2ZcscF3jrPYw2C9WfgnA29U/view?usp=sharing

答:
Do the images need to be private?

You don't have any caching enabled on your images.
If you check the headers for the image they have Cache-Control: private.

Since the browser isn't allowed to cache the images, it might affect the performance quite a bit.

Potential fix

I would suggest allowing the user to cache the images for at least an hour.
You will need to set the correct cache headers when uploading the images.
But you can easily via googles gsutil set the headers for all files in a folder

This is what I use:
Where in this case we cache the images for 1year and make them immutable causing the browser to always use the cached version

gsutil -m setmeta -h "Cache-Control:public,max-age=31536000,immutable" 'gs://my-storage-bucket-name/myimagefolder/**/*.{jpg,png}'
```

Hopefully this could make the app more performant, but you will have to try to know.

Body:
Angular 6:  Images takes time to load in chrome

This issue is specifically in chrome and not in any other browser.

We have used Firebase in our project, and  used snapshotchange method to fetch the image to angular project from the same, the image urls are like this https://firebasestorage.googleapis.com/v0/b/test-4a5d9.appspot.com/o/download.jpg?alt=media&token=a78321fc-eb9c-496a-a690-e8b2ccddf6c6 . There is something wrong due to which, image loads very slowly and the screen becomes blank when we scroll up and down in the browser, here we have used "ngx-infinite-scroll".

I have also tried by concatenating .jpg extension after the image but the scenario remains the same.

First, I thought the problem is with the size of image which is affecting the loading speed, so then I have replaced the images with https://upload.wikimedia.org/wikipedia/commons/b/b9/Pizigani_1367_Chart_1MB.jpg which is a heavy size of image, but here the website run's smoothly without any issue.

But it does not scroll smoothly when image urls are like this https://firebasestorage.googleapis.com/v0/b/test-4a5d9.appspot.com/o/download.jpg?alt=media&token=a78321fc-eb9c-496a-a690-e8b2ccddf6c6

Here is the code to set images in one list item:

1">

{{'Sold'}}

Here is the video of the problem:

https://drive.google.com/file/d/1Ipl-34rOE2ZcscF3jrPYw2C9WfgnA29U/view?usp=sharing

Body:
Do the images need to be private?

You don't have any caching enabled on your images.
If you check the headers for the image they have Cache-Control: private.

Since the browser isn't allowed to cache the images, it might affect the performance quite a bit.

Potential fix

I would suggest allowing the user to cache the images for at least an hour.
You will need to set the correct cache headers when uploading the images.
But you can easily via googles gsutil set the headers for all files in a folder

This is what I use:
Where in this case we cache the images for 1year and make them immutable causing the browser to always use the cached version

gsutil -m setmeta -h "Cache-Control:public,max-age=31536000,immutable" 'gs://my-storage-bucket-name/myimagefolder/**/*.{jpg,png}'

Hopefully this could make the app more performant, but you will have to try to know.


问:
Why is powershell changing the variable data? Can i make it stop?
My script takes the content of 2 files, which have an id in the first element of each line. I'm trying to take the id of each line in file 1, find a matching line in file 2, then compare the file 1 line to the file 2 line. If they are different, that difference will be sent to a database file to update. For some reason, the variables holding my data just decide to not hold data anymore. In the following example, the CompareData loses the value of $web and $data, sometime after the first if ($web -match) statement. </p>

```<code>function CompareData($web, $data)
{
    $webs = $web -split "@@@"
    $datas = $data -split "@@@"
    if ($web -match "1862185823")
    {
      write-host "$web"
      ###this will display the full line of the web file, and was only
      #added to show what i'm talking about
    }
##########################The value of web seems to break sometime after these
##########################variable declarations.
    $wid = $webs[0];$wit = $webs[1];$wst = $webs[2];$wpr = $webs[3];$won = $webs[4];$wsd = $webs[5];$wtd = $webs[6];$wcd = $webs[7];$weh = $webs[8];$wdh = $webs[9];$wah = $webs[10];$wac = $webs[11];$wpd = $webs[12]
    $did = $datas[0];$dit = $datas[1];$dst = $datas[2];$dpr = $datas[3];$don = $datas[4];$dsd = $datas[5];$dtd = $datas[6];$dcd = $datas[7];$deh = $datas[8];$ddh = $datas[9];$dah = $datas[10];$dac = $datas[11];$dpd = $datas[12]
    $wehstr = [string]$weh;$wdhstr = [string]$wdh;$wahstr = [string]$wah;$dehstr = [string]$deh;$dahstr = [string]$dah;$ddhstr = [string]$ddh
    $wdCount = $wit.Length / 2
    $dtCount = $wit.Length / 2
    $newWtitle = $wit.Substring(0, $wdCount)
    $newDtitle = $dit.Substring(0, $dtCount)
    if ($web -match "1862185823")
    {

        #the actual contents of $web are now wrong!!!!!!!!!!!!!!!!
    }
    if ($wehstr.Length -gt $dehstr.Length){$dehstr = $dehstr.PadRight($dehstr.Length + 1, "0")}
    if ($wdhstr.Length -gt $ddhstr.Length){$ddhstr = $ddhstr.PadRight($ddhstr.Length + 1, "0")}
    if ($wahstr.Length -gt $dahstr.Length){$dahstr = $dahstr.PadRight($dahstr.Length + 1, "0")}
    if ($dehstr.Length -gt $wehstr.Length){$wehstr = $wehstr.PadRight($wehstr.Length + 1, "0")}
    if ($dahstr.Length -gt $wahstr.Length){$wahstr = $wahstr.PadRight($wahstr.Length + 1, "0")}
    if ($ddhstr.Length -gt $wdhstr.Length){$wdhstr = $wdhstr.PadRight($wdhstr.Length + 1, "0")}

    if ($newWtitle -match $newDtitle -and $wehstr -match $dehstr -and $wahstr -match $dahstr -and $ddhstr -match $wdhstr -and $wsd -match $dsd -and $wtd -match $dtd -and $wcd -match $dcd -and $won -match $don -and $wst -match $dst -and $wpr -match $dpr -and $wac -match $dac -and $wpd -match $dpd)
    {
        #write-host "$wid and $did match"
    }
    else
    {
        write-host "they didn't match"
    }
    $wid = "";$wit = "";$wst = "";$wpr = "";$won = "";$wsd = "";$wtd = "";$wcd = "";$weh = "";$wdh = "";$wah = "";$wac = "";$wpd = "";
    $did = "";$dit = "";$dst = "";$dpr = "";$don = "";$dsd = "";$dtd = "";$dcd = "";$deh = "";$ddh = "";$dah = "";$dac = "";$dpd = "";
    $webs = ""
    $datas = ""
}

$dc = gc "${DatabaseFile}"
$wc = gc "${WebFile}"
write-host "Started"
foreach ($w in $wc)
{
    try
    {
        $x = 0
        $ws = $w -split "@@@"#custom delimiter since people are using tabs pipes and everything else in the titles....
        $webid = $ws[0]

        $result = select-string -Path "${DatabaseFile}" -pattern $webid

        if ($result -ne $null)
        {

            $newresult = $result -replace "D\:\\phi\\phs\\Oversight\\Projects\\Database.txt:\d{1,}:", ""
            $doublecheck = $newresult -split "@@@"
            if ($doublecheck[0] -eq $webid)
            {

                CompareData $w $newresult

            }
            else
            {
                write-host "Found a mismatch id, searching individual records line by line for a matching id"
                foreach ($d in $dc)#this slow method is only called when someone has another ID in the title in addition to the
                {#first element which is also id. Select-string grabs a match in the entire document, so this is here for single
                #searching each record for a matching id in the first element
                    $ds = $d -split "@@@"
                    $did = $ds[0]
                    $found = 0
                    if ($did -eq $webid)
                    {
                        CompareData $w $d
                        $found = 1
                        break
                    }
                    if ($found -eq 0)
                    {
                        write-host "Added $w to Insert file"
                        $w|out-file -append "${InsertFile}"
                    }

                }
            }
        }
        else
        {
            write-host "Added $w to Insert file"
            $w|out-file -append "${InsertFile}"
        }
    }
    catch
    {

    }
}
</code>```

答:
It turns out, the bug in this instance was with the lines

```<code>$wdCount = $wit.Length / 2
$dtCount = $wit.Length / 2
$newWtitle = $wit.Substring(0, $wdCount)
$newDtitle = $dit.Substring(0, $dtCount)
</code>```

These actually take the length of the title element then halve it. I don't need an exact title comparison, just the first half of it's letters just incase someone did infact change the title completely. The new code has corrected this issue, and things are working again.

```<code>$wtl = $wit.length
$dtl = $dit.length
$sublength = 0
if ($wtl -ge $dtl)
{
    $sublength = $dtl / 2
}
else
{
    $sublength = $wtl / 2
}
$newWtitle = $wit.Substring(0, $sublength)
$newDtitle = $dit.Substring(0, $sublength)
</code>```

Body:
My script takes the content of 2 files, which have an id in the first element of each line. I'm trying to take the id of each line in file 1, find a matching line in file 2, then compare the file 1 line to the file 2 line. If they are different, that difference will be sent to a database file to update. For some reason, the variables holding my data just decide to not hold data anymore. In the following example, the CompareData loses the value of $web and $data, sometime after the first if ($web -match) statement.

function CompareData($web, $data)
{
    $webs = $web -split "@@@"
    $datas = $data -split "@@@"
    if ($web -match "1862185823")
    {
      write-host "$web"
      ###this will display the full line of the web file, and was only
      #added to show what i'm talking about
    }
##########################The value of web seems to break sometime after these
##########################variable declarations.
    $wid = $webs[0];$wit = $webs[1];$wst = $webs[2];$wpr = $webs[3];$won = $webs[4];$wsd = $webs[5];$wtd = $webs[6];$wcd = $webs[7];$weh = $webs[8];$wdh = $webs[9];$wah = $webs[10];$wac = $webs[11];$wpd = $webs[12]
    $did = $datas[0];$dit = $datas[1];$dst = $datas[2];$dpr = $datas[3];$don = $datas[4];$dsd = $datas[5];$dtd = $datas[6];$dcd = $datas[7];$deh = $datas[8];$ddh = $datas[9];$dah = $datas[10];$dac = $datas[11];$dpd = $datas[12]
    $wehstr = [string]$weh;$wdhstr = [string]$wdh;$wahstr = [string]$wah;$dehstr = [string]$deh;$dahstr = [string]$dah;$ddhstr = [string]$ddh
    $wdCount = $wit.Length / 2
    $dtCount = $wit.Length / 2
    $newWtitle = $wit.Substring(0, $wdCount)
    $newDtitle = $dit.Substring(0, $dtCount)
    if ($web -match "1862185823")
    {

        #the actual contents of $web are now wrong!!!!!!!!!!!!!!!!
    }
    if ($wehstr.Length -gt $dehstr.Length){$dehstr = $dehstr.PadRight($dehstr.Length + 1, "0")}
    if ($wdhstr.Length -gt $ddhstr.Length){$ddhstr = $ddhstr.PadRight($ddhstr.Length + 1, "0")}
    if ($wahstr.Length -gt $dahstr.Length){$dahstr = $dahstr.PadRight($dahstr.Length + 1, "0")}
    if ($dehstr.Length -gt $wehstr.Length){$wehstr = $wehstr.PadRight($wehstr.Length + 1, "0")}
    if ($dahstr.Length -gt $wahstr.Length){$wahstr = $wahstr.PadRight($wahstr.Length + 1, "0")}
    if ($ddhstr.Length -gt $wdhstr.Length){$wdhstr = $wdhstr.PadRight($wdhstr.Length + 1, "0")}

    if ($newWtitle -match $newDtitle -and $wehstr -match $dehstr -and $wahstr -match $dahstr -and $ddhstr -match $wdhstr -and $wsd -match $dsd -and $wtd -match $dtd -and $wcd -match $dcd -and $won -match $don -and $wst -match $dst -and $wpr -match $dpr -and $wac -match $dac -and $wpd -match $dpd)
    {
        #write-host "$wid and $did match"
    }
    else
    {
        write-host "they didn't match"
    }
    $wid = "";$wit = "";$wst = "";$wpr = "";$won = "";$wsd = "";$wtd = "";$wcd = "";$weh = "";$wdh = "";$wah = "";$wac = "";$wpd = "";
    $did = "";$dit = "";$dst = "";$dpr = "";$don = "";$dsd = "";$dtd = "";$dcd = "";$deh = "";$ddh = "";$dah = "";$dac = "";$dpd = "";
    $webs = ""
    $datas = ""
}

$dc = gc "${DatabaseFile}"
$wc = gc "${WebFile}"
write-host "Started"
foreach ($w in $wc)
{
    try
    {
        $x = 0
        $ws = $w -split "@@@"#custom delimiter since people are using tabs pipes and everything else in the titles....
        $webid = $ws[0]

        $result = select-string -Path "${DatabaseFile}" -pattern $webid

        if ($result -ne $null)
        {

            $newresult = $result -replace "D\:\\phi\\phs\\Oversight\\Projects\\Database.txt:\d{1,}:", ""
            $doublecheck = $newresult -split "@@@"
            if ($doublecheck[0] -eq $webid)
            {

                CompareData $w $newresult

            }
            else
            {
                write-host "Found a mismatch id, searching individual records line by line for a matching id"
                foreach ($d in $dc)#this slow method is only called when someone has another ID in the title in addition to the
                {#first element which is also id. Select-string grabs a match in the entire document, so this is here for single
                #searching each record for a matching id in the first element
                    $ds = $d -split "@@@"
                    $did = $ds[0]
                    $found = 0
                    if ($did -eq $webid)
                    {
                        CompareData $w $d
                        $found = 1
                        break
                    }
                    if ($found -eq 0)
                    {
                        write-host "Added $w to Insert file"
                        $w|out-file -append "${InsertFile}"
                    }

                }
            }
        }
        else
        {
            write-host "Added $w to Insert file"
            $w|out-file -append "${InsertFile}"
        }
    }
    catch
    {

    }
}

Body:
It turns out, the bug in this instance was with the lines

$wdCount = $wit.Length / 2
$dtCount = $wit.Length / 2
$newWtitle = $wit.Substring(0, $wdCount)
$newDtitle = $dit.Substring(0, $dtCount)

These actually take the length of the title element then halve it. I don't need an exact title comparison, just the first half of it's letters just incase someone did infact change the title completely. The new code has corrected this issue, and things are working again.

$wtl = $wit.length
$dtl = $dit.length
$sublength = 0
if ($wtl -ge $dtl)
{
    $sublength = $dtl / 2
}
else
{
    $sublength = $wtl / 2
}
$newWtitle = $wit.Substring(0, $sublength)
$newDtitle = $dit.Substring(0, $sublength)


问:
how to calculate velocity of leg using kinect
I have group of skeleton joints, for example 4 joints of leg. Each joint have (x, y, z) coordinates. So I want to find the combine speed or velocity of these group of joints because i believe I need to calculate velocity of each four joints of leg in order to find out the velocity of leg, please correct me If I'm wrong.
So what would be best possible way to calculate?

I'm using this formula

velocity= Sqrt((x[n]−x[n − 1] )2 + (y[n]−y[n − 1] )2 + (z[n]−z[n − 1] )2)

答:
There is a simpler equation: Average Velocity = (Delta Distance)/(Delta Time)

If you want to know the average velocity at some point in the leg, calculate the location before it moved & the location on impact. Divide the magnitude of the vector of the difference between the 2 points by the amount of time it took to move between those points.


问:
Why do designers use sIFR if they can use @font-face?
Why do designers use sIFR if they can use @font-face ?

What is wrong with @font-face ?

```<code>@font-face {
    font-family: "Hacen Tehran_eot";
    src: url('Hacen Tehran.eot');
}

@font-face {
    font-family: "Hacen Tehran_ttf";
    src: url('Hacen Tehran.ttf');
}

p {
    font-family:"Hacen Tehran_eot", "Hacen Tehran_ttf", sans-serif;
    font-size:40px;
}
</code>```

答: You cannot do complicated gradient effects such as horizontal colour scaling with sIFR whereas this can be quickly put together in a flash file.</p>

Body:
Why do designers use sIFR if they can use @font-face ?

What is wrong with @font-face ?

@font-face {
    font-family: "Hacen Tehran_eot";
    src: url('Hacen Tehran.eot');
}

@font-face {
    font-family: "Hacen Tehran_ttf";
    src: url('Hacen Tehran.ttf');
}

p {
    font-family:"Hacen Tehran_eot", "Hacen Tehran_ttf", sans-serif;
    font-size:40px;
}


问:
Upload a product image using PrestaShop Web-service with Node
I'm trying to upload a Product image using the PrestaShop Web-service.

It is always returning the same error:

  <?xml version="1.0" encoding="UTF-8"?>
  <prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <errors>
      <error>
        <![CDATA[66]]>
        <message><![CDATA[Unable to save this image]]></message>
      </error>
    </errors>
  </prestashop>
```

<p><strong>My current code looks like this:</strong></p>

<pre class="lang-js prettyprint-override"><code>const url = this.options.url
    + '/api/images/products/'
    + piezaSchema.querySelector('product>id').childNodes[0].nodeValue
    + '?ws_key='
    + this.options.api;

const file = require('fs').readFileSync(require('path')
        .resolve(this.options.ruta
            + '/images/'
            + image.getAttribute('fichero')));

const resp = await fetch(url, {
    method: 'POST',
    body: 'image=' + file,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});
</code>```

I've tried with different encoding options, sending as 'Content-Type': 'image/jpeg', etc.

Thank you all for your time.

答:
This error is triggered by the writePostedImageOnDisk() method in /classes/webservice/WebserviceSpecificManagementImages.php.

Usually it can be due to:

Lack of permissions on your PHP /tmp folder and/or _PS_TMP_IMG_DIR_

$_FILES['image']['tmp_name'] being empty

Some issues with the customized_data table (in case this image is attached to a customized product)

This works for me (using PHP, not Node.js though):

```<code><?php

include(__DIR__.'/config/config.inc.php');

/* Connect to the PrestaShop Web-service */
define('PS_SHOP_URL', 'http://localhost/prestashop');
define('PS_WS_AUTH_KEY', 'YOURWSKEY');

/* Local path to the image to upload */
$image_path = './test.png'; // Can  either be JPEG, PNG, etc.

/* Image upload */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, PS_SHOP_URL.'/api/images/products/1');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, PS_WS_AUTH_KEY.':');
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => curl_file_create($image_path)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
echo '```'.print_r($response).'```'; // Should echo '1'
curl_close($ch);
</code>```

I hope this helps!

Body:
I'm trying to upload a Product image using the PrestaShop Web-service.

It is always returning the same error:

  <?xml version="1.0" encoding="UTF-8"?>
  <prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <errors>
      <error>
        <![CDATA[66]]>
        <message><![CDATA[Unable to save this image]]></message>
      </error>
    </errors>
  </prestashop>

My current code looks like this:

const url = this.options.url
    + '/api/images/products/'
    + piezaSchema.querySelector('product>id').childNodes[0].nodeValue
    + '?ws_key='
    + this.options.api;

const file = require('fs').readFileSync(require('path')
        .resolve(this.options.ruta
            + '/images/'
            + image.getAttribute('fichero')));

const resp = await fetch(url, {
    method: 'POST',
    body: 'image=' + file,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});

I've tried with different encoding options, sending as 'Content-Type': 'image/jpeg', etc.

Thank you all for your time.

Body:
This error is triggered by the writePostedImageOnDisk() method in /classes/webservice/WebserviceSpecificManagementImages.php.

Usually it can be due to:

Lack of permissions on your PHP /tmp folder and/or _PS_TMP_IMG_DIR_

$_FILES['image']['tmp_name'] being empty

Some issues with the customized_data table (in case this image is attached to a customized product)

This works for me (using PHP, not Node.js though):

<?php

include(__DIR__.'/config/config.inc.php');

/* Connect to the PrestaShop Web-service */
define('PS_SHOP_URL', 'http://localhost/prestashop');
define('PS_WS_AUTH_KEY', 'YOURWSKEY');

/* Local path to the image to upload */
$image_path = './test.png'; // Can  either be JPEG, PNG, etc.

/* Image upload */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, PS_SHOP_URL.'/api/images/products/1');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, PS_WS_AUTH_KEY.':');
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => curl_file_create($image_path)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
echo '<pre>'.print_r($response).'</pre>'; // Should echo '1'
curl_close($ch);

I hope this helps!


问:
Spring data JPA and parameters that can be null
My understanding is, that with Spring data JPA I cannot have a query method to fetch all rows where a column equals a given non-null method parameter and use the same method to fetch all rows where this column is NULL when the method parameter is null.

Is that correct?

So I have to distinguish this in my JAVA code and I must use a separate query method explicitly asking for null values, like in the example below?

```<code>// Query methods
List<Something> findByParameter(Parameter parameter);
List<Something> findByParameterIsNull();

...

List<Something> result = new ArrayList<>();

if (parameter == null)
  result = findByParameterIsNull();
else
  result = findByParameter(parameter);
</code>```

That's bad, if I have 4 parameters which could be null and would have to code 16 different query methods.

答:
In my case membershipNumber is nullable, and I have handled it this way. This will handle all the cases where table.membershipNumber is null too.</p>

```<code>      @Query(value = "SELECT pr FROM ABCTable pr " +
            "WHERE LOWER(pr.xyz) = LOWER(:xyz) " +
            "and LOWER(pr.subscriptionReference) = LOWER(:subscriptionReference) " +
            "and pr.billId = :billId " +
            "and ((pr.membershipNumber = :membershipId) or (pr.membershipNumber = null and :membershipId = null))")
    List<PaymentRequest> getSomething (@Param("xyz") String xyz,
                                                 @Param("subscriptionReference") String subscriptionReference,
                                                 @Param("billId") Integer billId,
                                                 @Param("membershipId") String membershipNumber);

</code>```

Body:
My understanding is, that with Spring data JPA I cannot have a query method to fetch all rows where a column equals a given non-null method parameter and use the same method to fetch all rows where this column is NULL when the method parameter is null.

Is that correct?

So I have to distinguish this in my JAVA code and I must use a separate query method explicitly asking for null values, like in the example below?

// Query methods
List<Something> findByParameter(Parameter parameter);
List<Something> findByParameterIsNull();

...

List<Something> result = new ArrayList<>();

if (parameter == null)
  result = findByParameterIsNull();
else
  result = findByParameter(parameter);

That's bad, if I have 4 parameters which could be null and would have to code 16 different query methods.

Body:
In my case membershipNumber is nullable, and I have handled it this way. This will handle all the cases where table.membershipNumber is null too.

      @Query(value = "SELECT pr FROM ABCTable pr " +
            "WHERE LOWER(pr.xyz) = LOWER(:xyz) " +
            "and LOWER(pr.subscriptionReference) = LOWER(:subscriptionReference) " +
            "and pr.billId = :billId " +
            "and ((pr.membershipNumber = :membershipId) or (pr.membershipNumber = null and :membershipId = null))")
    List<PaymentRequest> getSomething (@Param("xyz") String xyz,
                                                 @Param("subscriptionReference") String subscriptionReference,
                                                 @Param("billId") Integer billId,
                                                 @Param("membershipId") String membershipNumber);