问:
Calculate if two lines are symmetrical
I'm developing an app to check if a draw is symmetric or not. All the users line are stored into an ArrayList composed by a list of points, structured as well:

```<code>private ArrayList<ArrayList<Pair<Float,Float>>> segments = new ArrayList<>();
</code>```

This is how I build the drawing area:

The black shape is part of the background and I don't need to consider it when I have to check the symmetry. I only need its center (which I store as a single coordinate) since I need to consider checking the symmetry by it. Since the draws are made by children, I also need to consider a bit of flexibility since the lines will never be exactly symmetric. I implemented a method which divides each segments in 10 parts and then check if the coordinates of each part have a similare increase/decrease:

```<code>private boolean checkShape (int z, ArrayList<Pair<Float,Float>> points) {
    ArrayList<Pair<Float,Float>> copia = segments.get(z);
    int nGroupsFirstShape = (segments.get(z).size()*10)/100;
    int nValuesFirstShape[] = new int[10];
    for (int j=0, j2=0; j<10; j++, j2+=nGroupsFirstShape) {
        int sumValues=0;
        sumValues+=copia.get(j2).first-copia.get(j2+nGroupsFirstShape-1).first;
        sumValues+=copia.get(j2).second-copia.get(j2+nGroupsFirstShape-1).second;
        nValuesFirstShape[j] = sumValues;
    }
    ArrayList<Pair<Float,Float>> copia2 = points;
    int nGroupSecondShape = (copia2.size()*10)/100;
    int nValuesSecondShape[] = new int[10];
    for (int j=0, j2=0; j<10; j++, j2+=nGroupSecondShape) {
        int sumValues=0;
        sumValues+=copia2.get(j2).first-copia2.get(j2+nGroupSecondShape-1).first;
        sumValues+=copia2.get(j2).second-copia2.get(j2+nGroupSecondShape-1).second;
        nValuesSecondShape[j] = sumValues;
    }
    int differences[] = new int[10];
    int numberOf = 0;
    for (int index=0; index<10; index++) {
        differences[index] = nValuesFirstShape[index] - nValuesSecondShape[index];
        if (differences[index]<0) differences[index] = -differences[index];
        if (differences[index]<nGroupsFirstShape*2.5) numberOf++;
    }
    if (numberOf>=6) return true; else return false;
}
</code>```

If this is verified for at least 6 parts, then I can considerer the segments symmetric. The huge problem of this method is that the lines can have different sizes. Do you know any methods to calculate the symmetry of a drawing area? Since I save the image as a bitmap, I also tried to find a method to calculate it directly on the image file, but I didn't find anything

答:
I did not code Java for years and do not have that much time right now. Because of that this answer does not contain running Java code, but only the ideas and some pseudo-code. I hope this helps you, anyway.

One has given two curves curve1 and curve2, and a center of reflection c.
You want to compute if the one curve is a point reflection of the other within a given threshold maxDist.

The function to compute this could look like that:

function checkSymmetry(Curve curve1, Curve curve2, Vector c, float maxDist) {
    // reflect one curve
    Curve curve2refl = reflect(curve2, c);
    // compute curve distance
    float d = dist(curve1, curve2refl);
    // check if distance is below threshold
    return d < maxDist;
```

<p>(I did introduce some classes instead of your ArrayLists of ArrayLists of Pairs of … for better readability. I would recommend you to do the same in your code.)</p>

<h2>Point Reflection</h2>

<p>The formula of a point reflection can be found on Wikipedia: the reflection of a point <code>p</code> with reflection center <code>c</code> is: <code>2*c - p</code>.</p>

<p>To reflect a curve you have to reflect all its vertices.</p>

<h2>Distance Curve–Curve</h2>

<p>When the two red curves are (almost) symmetrical then after the reflection of one of them they should be (almost) identical, i.e. have a distance of (almost) zero. But what is the distance of two curves?</p>

<p>In mathematical set theory there exists a Hausdorff distance. It is a little bit complicated for Non-Mathematicians. But it gives the idea to define the distance of your curves: the maximum distance of a vertex of one curve to the other curve: </p>

<pre class="lang-java prettyprint-override"><code>function dist(Curve curve1, Curve curve2) {
    d = 0;
    for (Vector p : curve1.vertices) {
        d = max(d, dist(curve2, p));
    }
    for (Vector p : curve2.vertices) {
        d = max(d, dist(curve1, p));
    }
    return d;
}
</code>```

Distance Point–Curve

So we did reduce the problem to compute the distance of a point to a curve. This is the minimum distance of the point to any of the curve segments:

function dist(Curve curve, Vector p) {
    d = dist(p, curve.vertices.get(0));
    for (int i = 1, n = curve.vertices.size(); i < n; ++i) {
        Vector p1 = curve.vertices.get(i-1);
        Vector p2 = curve.vertices.get(i);
        d = min(d, dist(new Segment(p1, p2), p));
    }
    return d;
}
```

Distance Point–Segment

For the distance of a point to a segment you find lots of questions with good answers on stackoverflow, e.g. here.

Title: Calculate if two lines are symmetrical

Body:
I'm developing an app to check if a draw is symmetric or not. All the users line are stored into an ArrayList composed by a list of points, structured as well:

private ArrayList<ArrayList<Pair<Float,Float>>> segments = new ArrayList<>();

This is how I build the drawing area:

The black shape is part of the background and I don't need to consider it when I have to check the symmetry. I only need its center (which I store as a single coordinate) since I need to consider checking the symmetry by it. Since the draws are made by children, I also need to consider a bit of flexibility since the lines will never be exactly symmetric. I implemented a method which divides each segments in 10 parts and then check if the coordinates of each part have a similare increase/decrease:

private boolean checkShape (int z, ArrayList<Pair<Float,Float>> points) {
    ArrayList<Pair<Float,Float>> copia = segments.get(z);
    int nGroupsFirstShape = (segments.get(z).size()*10)/100;
    int nValuesFirstShape[] = new int[10];
    for (int j=0, j2=0; j<10; j++, j2+=nGroupsFirstShape) {
        int sumValues=0;
        sumValues+=copia.get(j2).first-copia.get(j2+nGroupsFirstShape-1).first;
        sumValues+=copia.get(j2).second-copia.get(j2+nGroupsFirstShape-1).second;
        nValuesFirstShape[j] = sumValues;
    }
    ArrayList<Pair<Float,Float>> copia2 = points;
    int nGroupSecondShape = (copia2.size()*10)/100;
    int nValuesSecondShape[] = new int[10];
    for (int j=0, j2=0; j<10; j++, j2+=nGroupSecondShape) {
        int sumValues=0;
        sumValues+=copia2.get(j2).first-copia2.get(j2+nGroupSecondShape-1).first;
        sumValues+=copia2.get(j2).second-copia2.get(j2+nGroupSecondShape-1).second;
        nValuesSecondShape[j] = sumValues;
    }
    int differences[] = new int[10];
    int numberOf = 0;
    for (int index=0; index<10; index++) {
        differences[index] = nValuesFirstShape[index] - nValuesSecondShape[index];
        if (differences[index]<0) differences[index] = -differences[index];
        if (differences[index]<nGroupsFirstShape*2.5) numberOf++;
    }
    if (numberOf>=6) return true; else return false;
}

If this is verified for at least 6 parts, then I can considerer the segments symmetric. The huge problem of this method is that the lines can have different sizes. Do you know any methods to calculate the symmetry of a drawing area? Since I save the image as a bitmap, I also tried to find a method to calculate it directly on the image file, but I didn't find anything

Body:
I did not code Java for years and do not have that much time right now. Because of that this answer does not contain running Java code, but only the ideas and some pseudo-code. I hope this helps you, anyway.

One has given two curves curve1 and curve2, and a center of reflection c.
You want to compute if the one curve is a point reflection of the other within a given threshold maxDist.

The function to compute this could look like that:

function checkSymmetry(Curve curve1, Curve curve2, Vector c, float maxDist) {
    // reflect one curve
    Curve curve2refl = reflect(curve2, c);
    // compute curve distance
    float d = dist(curve1, curve2refl);
    // check if distance is below threshold
    return d < maxDist;

(I did introduce some classes instead of your ArrayLists of ArrayLists of Pairs of … for better readability. I would recommend you to do the same in your code.)

Point Reflection

The formula of a point reflection can be found on Wikipedia: the reflection of a point p with reflection center c is: 2*c - p.

To reflect a curve you have to reflect all its vertices.

Distance Curve–Curve

When the two red curves are (almost) symmetrical then after the reflection of one of them they should be (almost) identical, i.e. have a distance of (almost) zero. But what is the distance of two curves?

In mathematical set theory there exists a Hausdorff distance. It is a little bit complicated for Non-Mathematicians. But it gives the idea to define the distance of your curves: the maximum distance of a vertex of one curve to the other curve:

function dist(Curve curve1, Curve curve2) {
    d = 0;
    for (Vector p : curve1.vertices) {
        d = max(d, dist(curve2, p));
    }
    for (Vector p : curve2.vertices) {
        d = max(d, dist(curve1, p));
    }
    return d;
}

Distance Point–Curve

So we did reduce the problem to compute the distance of a point to a curve. This is the minimum distance of the point to any of the curve segments:

function dist(Curve curve, Vector p) {
    d = dist(p, curve.vertices.get(0));
    for (int i = 1, n = curve.vertices.size(); i < n; ++i) {
        Vector p1 = curve.vertices.get(i-1);
        Vector p2 = curve.vertices.get(i);
        d = min(d, dist(new Segment(p1, p2), p));
    }
    return d;
}

Distance Point–Segment

For the distance of a point to a segment you find lots of questions with good answers on stackoverflow, e.g. here.


来源: stackexchange

问:
primeNg calendar Uncaught (in promise): Missing number at position 0
Dates on my Mongodb are saved in the format:

```<code> "toDate": {
    "$date": "2018-01-24T18:30:00.000Z"
},
"fromDate": {
    "$date": "2018-01-11T18:30:00.000Z"
}
</code>```

when am trying to set date to p-calendar Like

```<code><p-calendar name="toDate"  [(ngModel)]="productId.toDate" class="form-control" [showIcon]="true"></p-calendar>
</code>```

Error:Uncaught (in promise): Missing number at position 0

What i tried?
changing date format Like:

```<code> post.fromDate=new Date(post.fromDate).toUTCString();
 post.toDate=new Date(post.toDate).toUTCString();
</code>```

date changes to format Wed, 24 Jan 2018 18:30:00 GMT
but Same error persists,

any help will be great, thanks

答:
I had similar issue: Error:Uncaught (in promise): Missing number at position 0

Check your date format:

```<code><p-calendar [(ngModel)]="dateValue" dateFormat="dd.mm.yy"></p-calendar>
</code>```

Also i was passing milliseconds as string ('123456'), which is not acceptable and gives Invalid date

P.S.
dateFormat can be: dd.mm.yy, dd/mm/yyyy, dd-mm-yyyy and etc.

ContentLicense: CC BY-SA 3.0

Body:
Dates on my Mongodb are saved in the format:

 "toDate": {
    "$date": "2018-01-24T18:30:00.000Z"
},
"fromDate": {
    "$date": "2018-01-11T18:30:00.000Z"
}

when am trying to set date to p-calendar Like

Error:Uncaught (in promise): Missing number at position 0

What i tried?
changing date format Like:

 post.fromDate=new Date(post.fromDate).toUTCString();
 post.toDate=new Date(post.toDate).toUTCString();

date changes to format Wed, 24 Jan 2018 18:30:00 GMT
but Same error persists,

any help will be great, thanks

Body:
I had similar issue: Error:Uncaught (in promise): Missing number at position 0

Check your date format:

<p-calendar [(ngModel)]="dateValue" dateFormat="dd.mm.yy"></p-calendar>

Also i was passing milliseconds as string ('123456'), which is not acceptable and gives Invalid date

P.S.
dateFormat can be: dd.mm.yy, dd/mm/yyyy, dd-mm-yyyy and etc.

ContentLicense: CC BY-SA 4.0


问:
Replace null values in query with a previous value
I'm creating a query through SSMS, working on SQL Server 2012.

Part of my query is to find the supervisor for the associates.  My issue is that for the table containing supervisor names it doesn't make a new daily record.  Because there is no record for that day my query shows up as NULL for supervisor.

How can I fill these NULL values with the last Supervisor they reported to in the table?

Supervisor Table

```<code>MeasureDate    Associate            Supervisor
2019-09-02     Goodman, Michelle    Moody, Robin
2019-09-01     Goodman, Michelle    Moody, Robin
2019-08-20     Goodman, Michelle    Henry, Jack
2019-08-19     Goodman, Michelle    Henry, Jack
</code>```

Current Query Output

```<code>Date        Supervisor     Associate
2019-09-01  Moody, Robin   Goodman, Michelle
2019-08-21  NULL           Goodman, Michelle
2019-08-20  Henry, Jack    Goodman, Michelle
</code>```

Improved Query Output

```<code>Date        Supervisor     Associate
2019-09-01  Moody, Robin   Goodman, Michelle
2019-08-21  Henry, Jack    Goodman, Michelle
2019-08-20  Henry, Jack    Goodman, Michelle
</code>```

Current Query

```<code>SELECT
z.Date,
z.Supervisor,
z.Associate,
CAST('XXX' AS char) AS [Group],
z.Task,
Sum(z.Minutes) as Minutes,
Sum(z.Count) as Cases

FROM
(
SELECT
a.DS_LOAD_DT AS Date,
c.CASE_TASK_TYPE_NM AS Task,
b.AssociateName AS Associate,
d.Supervisor,
(CONVERT(decimal,a.DURATIONSEC)/60) AS Minutes,
COUNT(*) AS Count

FROM DW_RawData_XXXDetail a
LEFT JOIN DW_Dim_AssociateMapping b ON a.XXX_EMP_ID = b.XXX_ID AND a.DS_LOAD_DT = b.ScheduleDate
LEFT JOIN DW_Dim_XXX_Case_Types c ON left(a.MSG_TYPE_CD, patindex('%[0-9][^0-9]%', a.MSG_TYPE_CD)) =
c.CASE_TASK_TYPE_ID
LEFT JOIN OperationScoreCard_Daily_Associates d ON b.AssociateName = d.Associate AND b.ScheduleDate =
d.MeasureDate

WHERE b.MUID = '400'
AND a.DS_LOAD_DT >= '2019-08-01'

GROUP BY
a.DS_LOAD_DT,
c.CASE_TASK_TYPE_NM,
b.AssociateName,
d.Supervisor,
(CONVERT(decimal,a.DURATIONSEC)/60)
) z

GROUP BY
z.Date,
z.Task,
z.Associate,
z.Supervisor
</code>```

答:
You can use lag function to get previous value of supervisor by using partitioning over associate.
For more info refer: https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver15

Below is an example:

```<code>    CREATE TABLE LogicalConnection (
  `cpId` VARCHAR(11),
  `sequenceNumber` VARCHAR(11)
);

INSERT INTO LogicalConnection
  (`cpId`, `sequenceNumber`)
VALUES
  ('1', '10'),
  ('1', NULL),
  ('2', '20');

    SELECT t.cpId,
    case when t.sequenceNumber is null then lag(t.sequenceNumber) over (partition by t.cpId) else t.sequenceNumber end
from LogicalConnection t
</code>```

Body:
I'm creating a query through SSMS, working on SQL Server 2012.

Part of my query is to find the supervisor for the associates.  My issue is that for the table containing supervisor names it doesn't make a new daily record.  Because there is no record for that day my query shows up as NULL for supervisor.

How can I fill these NULL values with the last Supervisor they reported to in the table?

Supervisor Table

MeasureDate    Associate            Supervisor
2019-09-02     Goodman, Michelle    Moody, Robin
2019-09-01     Goodman, Michelle    Moody, Robin
2019-08-20     Goodman, Michelle    Henry, Jack
2019-08-19     Goodman, Michelle    Henry, Jack

Current Query Output

Date        Supervisor     Associate
2019-09-01  Moody, Robin   Goodman, Michelle
2019-08-21  NULL           Goodman, Michelle
2019-08-20  Henry, Jack    Goodman, Michelle

Improved Query Output

Date        Supervisor     Associate
2019-09-01  Moody, Robin   Goodman, Michelle
2019-08-21  Henry, Jack    Goodman, Michelle
2019-08-20  Henry, Jack    Goodman, Michelle

Current Query

SELECT
z.Date,
z.Supervisor,
z.Associate,
CAST('XXX' AS char) AS [Group],
z.Task,
Sum(z.Minutes) as Minutes,
Sum(z.Count) as Cases

FROM
(
SELECT
a.DS_LOAD_DT AS Date,
c.CASE_TASK_TYPE_NM AS Task,
b.AssociateName AS Associate,
d.Supervisor,
(CONVERT(decimal,a.DURATIONSEC)/60) AS Minutes,
COUNT(*) AS Count

FROM DW_RawData_XXXDetail a
LEFT JOIN DW_Dim_AssociateMapping b ON a.XXX_EMP_ID = b.XXX_ID AND a.DS_LOAD_DT = b.ScheduleDate
LEFT JOIN DW_Dim_XXX_Case_Types c ON left(a.MSG_TYPE_CD, patindex('%[0-9][^0-9]%', a.MSG_TYPE_CD)) =
c.CASE_TASK_TYPE_ID
LEFT JOIN OperationScoreCard_Daily_Associates d ON b.AssociateName = d.Associate AND b.ScheduleDate =
d.MeasureDate

WHERE b.MUID = '400'
AND a.DS_LOAD_DT >= '2019-08-01'

GROUP BY
a.DS_LOAD_DT,
c.CASE_TASK_TYPE_NM,
b.AssociateName,
d.Supervisor,
(CONVERT(decimal,a.DURATIONSEC)/60)
) z

GROUP BY
z.Date,
z.Task,
z.Associate,
z.Supervisor

Body:
You can use lag function to get previous value of supervisor by using partitioning over associate.
For more info refer: https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver15

Below is an example:

    CREATE TABLE LogicalConnection (
  `cpId` VARCHAR(11),
  `sequenceNumber` VARCHAR(11)
);

INSERT INTO LogicalConnection
  (`cpId`, `sequenceNumber`)
VALUES
  ('1', '10'),
  ('1', NULL),
  ('2', '20');

    SELECT t.cpId,
    case when t.sequenceNumber is null then lag(t.sequenceNumber) over (partition by t.cpId) else t.sequenceNumber end
from LogicalConnection t


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
Why not List<T>?

From the Eric Lippert post mentioned by others, I thought I will highlight this:

If I need a sequence I’ll use
  IEnumerable<T>, if I need a mapping
  from contiguous numbers to data I’ll
  use a List<T>, if I need a mapping
  across arbitrary data I’ll use a
  Dictionary<K,V>, if I need a set I’ll
  use a HashSet<T>. I simply don’t need
  arrays for anything, so I almost never
  use them. They don’t solve a problem I
  have better than the other tools at my
  disposal.

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Gulzar

LastEditorDisplayName: Gulzar


问:
filter dataframe columns as you iterate through rows and create dictionary
I have the following table of data in a spreadsheet:

```<code>Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8
</code>```

I'm reading the spreadsheet and passing the data as a dataframe.

I need to transform this table of data to json following a specific schema.

I have the following script:

```<code>for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            print(row.to_dict())
</code>```

which return:

```<code>{'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}
</code>```

I want to be able to filter out a specific column. For example, to return this:

```<code>{'Name': 'bar', 'Description': 'foofoo'}
</code>```

I know that I can print only the columns I want with this print(row['Name'],row['Description']) however this is only returning me values when I also want to return the key.

How can I do this?

答:
You can try this:

```<code>import io
import pandas as pd

s="""Name,Description,Value
foo,foobar,5
baz,foobaz,4
bar,foofoo,8
"""

df = pd.read_csv(io.StringIO(s))

for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
        print(row[['Name', 'Description']].to_dict())
</code>```

Result:

```<code>{'Name': 'bar', 'Description': 'foofoo'}
</code>```

Body:
I have the following table of data in a spreadsheet:

Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8

I'm reading the spreadsheet and passing the data as a dataframe.

I need to transform this table of data to json following a specific schema.

I have the following script:

for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            print(row.to_dict())

which return:

{'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}

I want to be able to filter out a specific column. For example, to return this:

{'Name': 'bar', 'Description': 'foofoo'}

I know that I can print only the columns I want with this print(row['Name'],row['Description']) however this is only returning me values when I also want to return the key.

How can I do this?

Body:
You can try this:

import io
import pandas as pd

s="""Name,Description,Value
foo,foobar,5
baz,foobaz,4
bar,foofoo,8
"""

df = pd.read_csv(io.StringIO(s))

for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
        print(row[['Name', 'Description']].to_dict())

Result:

{'Name': 'bar', 'Description': 'foofoo'}


问:
CloudFormation syntax for ParameterOverrides
I'm getting stuck on overriding multiple parameters within a CloudFormation that is passing them to CodePipeline.

I can successful override a single parameter like this:

```<code>ParameterOverrides: "{ \"StageName\": \"stage\" }"
</code>```

But when I try this:

```<code>ParameterOverrides: '{ "StageName": "prod", "EnvValue", "prod" }'
</code>```

I have also tried these combinations:

```<code>ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\", \"prod\"}"
</code>```

Codepipeline throws an error of: ParameterOverrides property is not valid

I have looked at this help article a half a dozen times and it seems I'm following the format to the T.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-parameter-override-functions.html

What am I missing? Does anyone have this working in a CloudFormation template?

答:
I found out what the problem was, fat fingered.
I put this:

```<code>ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\", \"prod\"}"
</code>```

and it should have been this:

```<code>ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\": \"prod\"}"
</code>```

NOTICE: the missing colon on after the second key.

Body:
I'm getting stuck on overriding multiple parameters within a CloudFormation that is passing them to CodePipeline.

I can successful override a single parameter like this:

ParameterOverrides: "{ \"StageName\": \"stage\" }"

But when I try this:

ParameterOverrides: '{ "StageName": "prod", "EnvValue", "prod" }'

I have also tried these combinations:

ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\", \"prod\"}"

Codepipeline throws an error of: ParameterOverrides property is not valid

I have looked at this help article a half a dozen times and it seems I'm following the format to the T.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-parameter-override-functions.html

What am I missing? Does anyone have this working in a CloudFormation template?

Body:
I found out what the problem was, fat fingered.
I put this:

ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\", \"prod\"}"

and it should have been this:

ParameterOverrides: "{\"StageName\": \"prod\", \"EnvValue\": \"prod\"}"

NOTICE: the missing colon on after the second key.


问:
How to write a If, Else if in assembly
I need to convert the following C code to its equivalent in Assembly. I've only taken a few classes on assembly and don't really have a grasp of the language yet.

```<code>
int x = 45
int y = 27
while (x != y) {
   if (x > y)
      x = x - y;
   else if (y > x)
      y = y - x;
}
return x;  // Sends exit code containing GCD
</code>```

I have written what i believe to work and am about to use a debugger to find inevitable flaws but wanted to ask if i am headed in the right direction with the if else statement.

```<code>    .global _start
    _start

    mov R1, #45  @R1 = 45
    mov R2, #27  @R2 = 27

    loopTop:
    cmp R1, R2
    beq allDone
    bge R1,R2
    sub R1,R1,R0
    bge R2,R1
    sub R2,R2,R1
    b loopTop

    allDone:
    SWI R1

</code>```

Any help/tips would be greatly appreciated!
Thanks!

答:
Here's your solution:

```<code>mov R1, #45 @x
mov R2, #27 @y

loop:
    cmp R1, R2  @compare R1 with R2
    bne label1  @is R1 not equals to R2? "Branch is Not Equal" to label1, else...

    @<replace with the return R1 statement here>

    label1:
        cmp R1, R2
        bgt sub_xy  @"Branch on Greater Than"
        cmp R1, R2
        blt sub_yx  @"Branch on Lower Than"

    sub_xy:
        sub R1, R1, R2  @R1 = R1 - R2
        b loop  @branch to loop

    sub_yx:
        sub R2, R2, R1  @R2 = R2 - R1
        b loop
</code>```

Came up with this as a newb x86_64 programmer trying to code for ARM for the first time.

EDIT: Corrections/ explanations are in the comments.

Title: How to write a If, Else if in assembly

Body:
I need to convert the following C code to its equivalent in Assembly. I've only taken a few classes on assembly and don't really have a grasp of the language yet.

int x = 45
int y = 27
while (x != y) {
   if (x > y)
      x = x - y;
   else if (y > x)
      y = y - x;
}
return x;  // Sends exit code containing GCD

I have written what i believe to work and am about to use a debugger to find inevitable flaws but wanted to ask if i am headed in the right direction with the if else statement.

    .global _start
    _start

    mov R1, #45  @R1 = 45
    mov R2, #27  @R2 = 27

    loopTop:
    cmp R1, R2
    beq allDone
    bge R1,R2
    sub R1,R1,R0
    bge R2,R1
    sub R2,R2,R1
    b loopTop

    allDone:
    SWI R1

Any help/tips would be greatly appreciated!
Thanks!

Body:
Here's your solution:

mov R1, #45 @x
mov R2, #27 @y

loop:
    cmp R1, R2  @compare R1 with R2
    bne label1  @is R1 not equals to R2? "Branch is Not Equal" to label1, else...

    @<replace with the return R1 statement here>

    label1:
        cmp R1, R2
        bgt sub_xy  @"Branch on Greater Than"
        cmp R1, R2
        blt sub_yx  @"Branch on Lower Than"

    sub_xy:
        sub R1, R1, R2  @R1 = R1 - R2
        b loop  @branch to loop

    sub_yx:
        sub R2, R2, R1  @R2 = R2 - R1
        b loop

Came up with this as a newb x86_64 programmer trying to code for ARM for the first time.

EDIT: Corrections/ explanations are in the comments.


问:
Use the sum() on a result set returned by a subquery
This query returns the two lowests grades {9,10}

```<code>select TOP 2 grades.grade
from grades
where grades.studentno = 1
order by grade ASC
</code>```

And I want to sum the result of grades with the sum() function and set the result of the sum() function to the variable @sumLowerGrades

I have attempted with this query

```<code>set @sumLowerGrades = sum(select TOP 2 grades.grade from grades
        where grades.studentno = 1 order by grade ASC)
</code>```

But it fails with the following message:

Incorrect syntax near the keyword 'select'.

  Incorrect syntax near ')'.

答:
Use a subquery:</p>

```<code>select @sumLowerGrades = sum(grade)
from (select TOP 2 grades.grade
      from grades
      where grades.studentno = 1
      order by grade ASC
     ) g;
</code>```

Body:
This query returns the two lowests grades {9,10}

select TOP 2 grades.grade
from grades
where grades.studentno = 1
order by grade ASC

And I want to sum the result of grades with the sum() function and set the result of the sum() function to the variable @sumLowerGrades

I have attempted with this query

set @sumLowerGrades = sum(select TOP 2 grades.grade from grades
        where grades.studentno = 1 order by grade ASC)

But it fails with the following message:

Incorrect syntax near the keyword 'select'.

  Incorrect syntax near ')'.

Body:
Use a subquery:

select @sumLowerGrades = sum(grade)
from (select TOP 2 grades.grade
      from grades
      where grades.studentno = 1
      order by grade ASC
     ) g;


问:
Why can't static classes have non-static methods and variables?
Why can't static classes have non-static methods and variables when non-static classes can have static methods and variables?

What is the advantage of having static methods and variables in a non static class? Though having a static constructor in a non-static class is understandable.

答:
Say you have a class Person that has a field name.  And let's suppose, for the sake of argument, that Java did allow static methods to directly access non-static member variables.  We might then specify a getName static method for our Person like so:

```<code>class Person {
  private final String name;

  public Person(String name) {
    this.name = name;
  }

  public static String getName() {
    return name;
  }
}
</code>```

Now let's try using this class in an example:

```<code>public static void main(String[] args) {
  Person alice = new Person("Alice");
  Person bob = new Person("Bob");
  System.out.println("name: " + Person.getName());
}
</code>```

So tell me, what on earth would we expect Person.getName() to print in this example?  Alice?  Bob?  Null?

There's no right answer.  It makes no sense, because a name is something that belongs to an individual (an instance), not the class as a whole.  So clearly we cannot have a static method access non-static members because we have no way of knowing which non-static members we should be accessing.

Body:
Say you have a class Person that has a field name.  And let's suppose, for the sake of argument, that Java did allow static methods to directly access non-static member variables.  We might then specify a getName static method for our Person like so:

class Person {
  private final String name;

  public Person(String name) {
    this.name = name;
  }

  public static String getName() {
    return name;
  }
}

Now let's try using this class in an example:

public static void main(String[] args) {
  Person alice = new Person("Alice");
  Person bob = new Person("Bob");
  System.out.println("name: " + Person.getName());
}

So tell me, what on earth would we expect Person.getName() to print in this example?  Alice?  Bob?  Null?

There's no right answer.  It makes no sense, because a name is something that belongs to an individual (an instance), not the class as a whole.  So clearly we cannot have a static method access non-static members because we have no way of knowing which non-static members we should be accessing.


问:
Kubernetes Volume Binding results in stale data
My Kubernetes Deployment is composed like this:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: "{{ .Release.Name }}-{{ .Values.web.service.name }}"
  namespace: "{{ .Values.namespace }}"
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      name: "{{ .Values.web.deployment.selector }}"
  template:
    metadata:
      labels:
        name: "{{ .Values.web.deployment.selector }}"
    spec:
      {{- if $.Values.vault.serviceAccount }}
      serviceAccountName: "{{ $.Release.Name }}-vault-auth"
      automountServiceAccountToken: true
      {{- end }}
      volumes:
        - name: shared-data
          emptyDir: {}
        - name: vault-token
          emptyDir:
            medium: Memory
        - name: company-config
          configMap:
            name: "{{ .Release.Name }}-config"
            items:
              - key: companyRootCA.crt
                path: companyRootCA.crt
        - name: vault-consul-config
          configMap:
            name: "{{ .Release.Name }}-vault-configmap"
            items:
              - key: vault_agent.hcl
                path: vault_agent.hcl
              - key: consul_template_config.hcl
                path: consul_template_config.hcl
              - key: config.tmpl
                path: config.tmpl
      containers:
        - name: vault-agent-auth
          image: vault
          volumeMounts:
            - name: company-config
              mountPath: /etc/pki/ca-trust/source/anchors/companyRootCA.crt
              subPath: companyRootCA.crt
            - name: vault-consul-config
              mountPath: /etc/vault/vault_agent.hcl
              subPath: vault_agent.hcl
            - name: vault-token
              mountPath: /home/vault/
          env:
            - name: VAULT_ADDR
              value: "{{ .Values.vault.endpoint }}"
            - name: VAULT_NAMESPACE
              value: "company/devops/tarchon/{{ .Values.environmentName }}"
          args:
            [
              "agent",
              "-config=/etc/vault/vault_agent.hcl",
              "-log-level=debug"
            ]
        - name: consul-template
          image: hashicorp/consul-template:alpine
          imagePullPolicy: Always
          volumeMounts:
            - name: company-config
              mountPath: /etc/pki/ca-trust/source/anchors/companyRootCA.crt
              subPath: companyRootCA.crt
            - name: vault-consul-config
              mountPath: /etc/consul-template/consul_template_config.hcl
              subPath: consul_template_config.hcl
            - name: vault-token
              mountPath: /home/vault
            - name: vault-consul-config
              mountPath: /etc/templates/config.tmpl
              subPath: config.tmpl
            - name: shared-data
              mountPath: /etc/secrets
          env:
            - name: HOME
              value: /home/vault
            - name: VAULT_ADDR
              value: "{{ .Values.vault.endpoint }}"
            - name: VAULT_NAMESPACE
              value: "company/devops/tarchon/{{ .Values.environmentName }}"
          args:
            [
              "-config=/etc/consul-template/consul_template_config.hcl",
              "-log-level=trace",
            ]
        - name: "{{ .Values.web.service.name }}"
          image: "{{ .Values.image.registry }}:{{ .Values.image.tag }}"
          imagePullPolicy: "{{ .Values.image.imagePullPolicy }}"
          args: [
            "bash",
            "-c",
            "python manage.py collectstatic --noinput && gunicorn --bind :8000 --workers 3 ecops_cross_team_platform_backend.wsgi:application"
          ]
          volumeMounts:
            - name: shared-data
              mountPath: /usr/src/app/config.json
              subPath: config.json
          {{- if $.Values.environmentVariables }}
          env:
            {{- range $key, $value := $.Values.environmentVariables }}
            - name: {{ $key }}
              valueFrom:
                configMapKeyRef:
                  name: "{{ $.Release.Name }}-config"
                  key: {{ $key | quote }}
            {{- end }}
          {{- end }}
          ports:
            - containerPort: {{ .Values.web.service.port }}
          resources: {}
      restartPolicy: Always
status: {}
</code>```

consul-template generates a file /etc/secrets/config.json with credentials that come from HashiCorp Vault in the shared volume shared-data.

In my application container I bind the file in a different directory (/usr/src/app/config.json) (because the application wants the file to be in different directory compared to where consul-template generates the file).

The problem is that whenever the file config.json is updated in the volume that is mounted in the consul-template container, the modification is not propagated to the other containers, so I end up having the application container with stale non-working data.

At the beginning, I initially thought it was a problem caused by the readOnly volumeMount option, however the problem was still present after removing it.

答:
As anmol said in the comments, it was indeed the fact of binding a single file using subPath in the directory.

The solution was to remove the subPath and bind the shared-data volume into a single-scoped folder (ie. /usr/src/app/credentials) so that it won't go wrong with other things.

Solution:

```<code>volumeMounts:
  - name: shared-data
    mountPath: /usr/src/app/credentials
</code>```

Instead of:

```<code>volumeMounts:
  - name: shared-data
    mountPath: /usr/src/app/config.json
    subPath: config.json
</code>```

Body:
My Kubernetes Deployment is composed like this:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: "{{ .Release.Name }}-{{ .Values.web.service.name }}"
  namespace: "{{ .Values.namespace }}"
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      name: "{{ .Values.web.deployment.selector }}"
  template:
    metadata:
      labels:
        name: "{{ .Values.web.deployment.selector }}"
    spec:
      {{- if $.Values.vault.serviceAccount }}
      serviceAccountName: "{{ $.Release.Name }}-vault-auth"
      automountServiceAccountToken: true
      {{- end }}
      volumes:
        - name: shared-data
          emptyDir: {}
        - name: vault-token
          emptyDir:
            medium: Memory
        - name: company-config
          configMap:
            name: "{{ .Release.Name }}-config"
            items:
              - key: companyRootCA.crt
                path: companyRootCA.crt
        - name: vault-consul-config
          configMap:
            name: "{{ .Release.Name }}-vault-configmap"
            items:
              - key: vault_agent.hcl
                path: vault_agent.hcl
              - key: consul_template_config.hcl
                path: consul_template_config.hcl
              - key: config.tmpl
                path: config.tmpl
      containers:
        - name: vault-agent-auth
          image: vault
          volumeMounts:
            - name: company-config
              mountPath: /etc/pki/ca-trust/source/anchors/companyRootCA.crt
              subPath: companyRootCA.crt
            - name: vault-consul-config
              mountPath: /etc/vault/vault_agent.hcl
              subPath: vault_agent.hcl
            - name: vault-token
              mountPath: /home/vault/
          env:
            - name: VAULT_ADDR
              value: "{{ .Values.vault.endpoint }}"
            - name: VAULT_NAMESPACE
              value: "company/devops/tarchon/{{ .Values.environmentName }}"
          args:
            [
              "agent",
              "-config=/etc/vault/vault_agent.hcl",
              "-log-level=debug"
            ]
        - name: consul-template
          image: hashicorp/consul-template:alpine
          imagePullPolicy: Always
          volumeMounts:
            - name: company-config
              mountPath: /etc/pki/ca-trust/source/anchors/companyRootCA.crt
              subPath: companyRootCA.crt
            - name: vault-consul-config
              mountPath: /etc/consul-template/consul_template_config.hcl
              subPath: consul_template_config.hcl
            - name: vault-token
              mountPath: /home/vault
            - name: vault-consul-config
              mountPath: /etc/templates/config.tmpl
              subPath: config.tmpl
            - name: shared-data
              mountPath: /etc/secrets
          env:
            - name: HOME
              value: /home/vault
            - name: VAULT_ADDR
              value: "{{ .Values.vault.endpoint }}"
            - name: VAULT_NAMESPACE
              value: "company/devops/tarchon/{{ .Values.environmentName }}"
          args:
            [
              "-config=/etc/consul-template/consul_template_config.hcl",
              "-log-level=trace",
            ]
        - name: "{{ .Values.web.service.name }}"
          image: "{{ .Values.image.registry }}:{{ .Values.image.tag }}"
          imagePullPolicy: "{{ .Values.image.imagePullPolicy }}"
          args: [
            "bash",
            "-c",
            "python manage.py collectstatic --noinput && gunicorn --bind :8000 --workers 3 ecops_cross_team_platform_backend.wsgi:application"
          ]
          volumeMounts:
            - name: shared-data
              mountPath: /usr/src/app/config.json
              subPath: config.json
          {{- if $.Values.environmentVariables }}
          env:
            {{- range $key, $value := $.Values.environmentVariables }}
            - name: {{ $key }}
              valueFrom:
                configMapKeyRef:
                  name: "{{ $.Release.Name }}-config"
                  key: {{ $key | quote }}
            {{- end }}
          {{- end }}
          ports:
            - containerPort: {{ .Values.web.service.port }}
          resources: {}
      restartPolicy: Always
status: {}

consul-template generates a file /etc/secrets/config.json with credentials that come from HashiCorp Vault in the shared volume shared-data.

In my application container I bind the file in a different directory (/usr/src/app/config.json) (because the application wants the file to be in different directory compared to where consul-template generates the file).

The problem is that whenever the file config.json is updated in the volume that is mounted in the consul-template container, the modification is not propagated to the other containers, so I end up having the application container with stale non-working data.

At the beginning, I initially thought it was a problem caused by the readOnly volumeMount option, however the problem was still present after removing it.

Body:
As anmol said in the comments, it was indeed the fact of binding a single file using subPath in the directory.

The solution was to remove the subPath and bind the shared-data volume into a single-scoped folder (ie. /usr/src/app/credentials) so that it won't go wrong with other things.

Solution:

volumeMounts:
  - name: shared-data
    mountPath: /usr/src/app/credentials

Instead of:

volumeMounts:
  - name: shared-data
    mountPath: /usr/src/app/config.json
    subPath: config.json


问:
Naming items in Value clause for readability
Is there a better way to achieve mapping items in the values to column names. I always do this using comments:

```<code>insert into Table1 (Col1, Col2, ..., Coln)
values ('One' /* Col1 */, 'Two' /* Col2 */, ..., 'ValN' /* Coln */);
</code>```

It becomes especially important when there are many columns involved and the values clause has queries in it. I always have to count and see which item in the values clause is for which column. Therefore, I just use comments as shown above. I will state the obvious that sometimes depending on the query, I may keep them on separate lines.

Any other way?

答:
Yours is a good way. I usually use one line for each column. It can get really long but I find it more readable. Something like this:

```<code>insert into Table1 (
 Col1
,Col2
,...
,Coln
)
values (
 One  /* Col1 */
,Two  /* Col2 */
,...
,ValN /* Coln */
);
</code>```

In some cases, using a JSON string could be useful. In other cases it maybe an overkill. Here's a simple example:

Let's say we have a table called "test" with two columns: "Number" (INT) and "Word" (VARCHAR(40))

We can insert records in that table using the following construction:

```<code>INSERT INTO test (Number, Word)
  SELECT source.Number, source.Word
  FROM
  (
  SELECT  Number, Word
      FROM
      OpenJson('[{
    "number": 01,  "word": "This"
  }, {
    "number": 02,  "word": "Is"
  }, {
    "number": 03,  "word": "Just"
  }, {
    "number": 04,  "word": "a"
  }, {
    "number": 05,  "word": "Test"
  }] '
  ) WITH (Number INT '$.number', Word VARCHAR(40) '$.word')

  ) AS source
</code>```

As we can see:

The data to insert is stored inside the JSON string. We then name the each property in the JSON string using the same column names in the table.

When doing the actual insert, the names of the values to insert are variables that have the same name than their columns, making it very readable. (source.Number, source.Word).

In some cases, using the JSON string can help out not only with the mapping of the data and their columns but also debugging the data and finding wrong values.

Body:
Is there a better way to achieve mapping items in the values to column names. I always do this using comments:

insert into Table1 (Col1, Col2, ..., Coln)
values ('One' /* Col1 */, 'Two' /* Col2 */, ..., 'ValN' /* Coln */);

It becomes especially important when there are many columns involved and the values clause has queries in it. I always have to count and see which item in the values clause is for which column. Therefore, I just use comments as shown above. I will state the obvious that sometimes depending on the query, I may keep them on separate lines.

Any other way?

Body:
Yours is a good way. I usually use one line for each column. It can get really long but I find it more readable. Something like this:

insert into Table1 (
 Col1
,Col2
,...
,Coln
)
values (
 One  /* Col1 */
,Two  /* Col2 */
,...
,ValN /* Coln */
);

In some cases, using a JSON string could be useful. In other cases it maybe an overkill. Here's a simple example:

Let's say we have a table called "test" with two columns: "Number" (INT) and "Word" (VARCHAR(40))

We can insert records in that table using the following construction:

INSERT INTO test (Number, Word)
  SELECT source.Number, source.Word
  FROM
  (
  SELECT  Number, Word
      FROM
      OpenJson('[{
    "number": 01,  "word": "This"
  }, {
    "number": 02,  "word": "Is"
  }, {
    "number": 03,  "word": "Just"
  }, {
    "number": 04,  "word": "a"
  }, {
    "number": 05,  "word": "Test"
  }] '
  ) WITH (Number INT '$.number', Word VARCHAR(40) '$.word')

  ) AS source

As we can see:

The data to insert is stored inside the JSON string. We then name the each property in the JSON string using the same column names in the table.

When doing the actual insert, the names of the values to insert are variables that have the same name than their columns, making it very readable. (source.Number, source.Word).

In some cases, using the JSON string can help out not only with the mapping of the data and their columns but also debugging the data and finding wrong values.


问:
How to show only root in JTree?
I have a JTree like this:

```<code>private TreeNode createNodes() {

        DefaultMutableTreeNode root;
        DefaultMutableTreeNode grandparent;
        DefaultMutableTreeNode parent;

        root = new DefaultMutableTreeNode("San Francisco");

        grandparent = new DefaultMutableTreeNode("Potrero Hill");
        root.add(grandparent);

        parent = new DefaultMutableTreeNode("Restaurants");
        grandparent.add(parent);

        dummyParent = root;

        return root;
    }
</code>```

I want to show only the root "San Francisco" in the screen not by default. Then the tree only expands when I click to the extended icon. How can I do that? I had tried to use some methods:

```<code>         tree.setRootVisible(true);
         tree.setShowsRootHandles(false);
</code>```

答:
I want to show only the root "San Francisco" in the screen

After you have created the data and added the model to the tree you can use:

```<code>tree.collapseRow(0);
</code>```

Title: How to show only root in JTree?

Body:
I have a JTree like this:

private TreeNode createNodes() {

        DefaultMutableTreeNode root;
        DefaultMutableTreeNode grandparent;
        DefaultMutableTreeNode parent;

        root = new DefaultMutableTreeNode("San Francisco");

        grandparent = new DefaultMutableTreeNode("Potrero Hill");
        root.add(grandparent);

        parent = new DefaultMutableTreeNode("Restaurants");
        grandparent.add(parent);

        dummyParent = root;

        return root;
    }

I want to show only the root "San Francisco" in the screen not by default. Then the tree only expands when I click to the extended icon. How can I do that? I had tried to use some methods:

         tree.setRootVisible(true);
         tree.setShowsRootHandles(false);

Body:
I want to show only the root "San Francisco" in the screen

After you have created the data and added the model to the tree you can use:

tree.collapseRow(0);


问:
Shorthand for creating a Python dictionary with key as variable name
In javascript, you can create an object in this way:

const a = 5;
const b = 10;

const c = {a, b};
// This will make c = {a: 5, b: 10}
```

<p>Is there a "shorthand" like this in Python?</p>

<p>So far, I have to do:</p>

<pre class="lang-py prettyprint-override"><code>a = 5
b = 10

c = {'a': a, 'b': b}
</code>```

答:
The answer in this specific case is "no", because a and b in your examples are labels for int objects within __main__ or another module. a doesn't have anything resembling an attribute "a".

However, something closer to what you might want is possible, although it certainly is bordering on a dirty hack, depending on exactly what you are doing. For example, if running from main:

```<code>a = 5
b = 10
c = {i : eval(i) for i in dir() if "_" not in i}
</code>```

This works because "a" and "b" (the names/labels, that is) do exist within a higher object, namely __main__ or your module. You need the filter to exclude other hidden attributes. This example is extremely hacky for many reasons, starting with the use of dir(), but the principle would work in more appropriate cases such as when a and b are attributes of a lower object. However, in those cases, I can't imagine why you'd want to do this, as you'd essentially already have exactly that dictionary.

So really the reason that this is quite difficult in python is because there just isn't any need to do it.

Body:
In javascript, you can create an object in this way:

const a = 5;
const b = 10;

const c = {a, b};
// This will make c = {a: 5, b: 10}

Is there a "shorthand" like this in Python?

So far, I have to do:

a = 5
b = 10

c = {'a': a, 'b': b}

Body:
The answer in this specific case is "no", because a and b in your examples are labels for int objects within __main__ or another module. a doesn't have anything resembling an attribute "a".

However, something closer to what you might want is possible, although it certainly is bordering on a dirty hack, depending on exactly what you are doing. For example, if running from main:

a = 5
b = 10
c = {i : eval(i) for i in dir() if "_" not in i}

This works because "a" and "b" (the names/labels, that is) do exist within a higher object, namely __main__ or your module. You need the filter to exclude other hidden attributes. This example is extremely hacky for many reasons, starting with the use of dir(), but the principle would work in more appropriate cases such as when a and b are attributes of a lower object. However, in those cases, I can't imagine why you'd want to do this, as you'd essentially already have exactly that dictionary.

So really the reason that this is quite difficult in python is because there just isn't any need to do it.


问:
protobuf embedded message best practice
I have a protobuf message that contains another repeating message. It looks like this:

```<code>message AddGroupsRequest
{
    message GroupProperties
    {
        string name = 1;
        int32 some_property_1 = 2;
        int32 some_property_2 = 3;
    }

    repeated GroupProperties group_properties = 1;
}
</code>```

My question is whether that's the best way to encode the messages, or should they be separated like this:

```<code>message GroupProperties
{
    string name = 1;
    int32 some_property_1 = 2;
    int32 some_property_2 = 3;
}

message AddGroupsRequest
{
    repeated GroupProperties group_properties = 1;
}
</code>```

Are there implications for defining the message one way or another?

Thanks

答:
The underlying encoding of the two specifications will be identical when using the binary output.

```<code>$> echo 'group_properties { name: "Bob", some_property_1: 6 }' \
      | protoc nested.proto --encode='AddGroupsRequest'        \
      | xxd

00000000: 0a07 0a03 426f 6210 06                   ....Bob..
</code>```

```<code>$> echo 'group_properties { name: "Bob", some_property_1: 6 }' \
      | protoc sibling.proto --encode='AddGroupsRequest'       \
      | xxd

00000000: 0a07 0a03 426f 6210 06                   ....Bob..
</code>```

The only decision point is if you want the generated C++ class name to be AddGroupsRequest_GroupProperties (in nested form) or if you want an independent GroupProperties type, which is largely a preference thing. Note that you can change this later without breaking the already-encoded messages.

Title: protobuf embedded message best practice

Body:
I have a protobuf message that contains another repeating message. It looks like this:

message AddGroupsRequest
{
    message GroupProperties
    {
        string name = 1;
        int32 some_property_1 = 2;
        int32 some_property_2 = 3;
    }

    repeated GroupProperties group_properties = 1;
}

My question is whether that's the best way to encode the messages, or should they be separated like this:

message GroupProperties
{
    string name = 1;
    int32 some_property_1 = 2;
    int32 some_property_2 = 3;
}

message AddGroupsRequest
{
    repeated GroupProperties group_properties = 1;
}

Are there implications for defining the message one way or another?

Thanks

Body:
The underlying encoding of the two specifications will be identical when using the binary output.

$> echo 'group_properties { name: "Bob", some_property_1: 6 }' \
      | protoc nested.proto --encode='AddGroupsRequest'        \
      | xxd

00000000: 0a07 0a03 426f 6210 06                   ....Bob..

$> echo 'group_properties { name: "Bob", some_property_1: 6 }' \
      | protoc sibling.proto --encode='AddGroupsRequest'       \
      | xxd

00000000: 0a07 0a03 426f 6210 06                   ....Bob..

The only decision point is if you want the generated C++ class name to be AddGroupsRequest_GroupProperties (in nested form) or if you want an independent GroupProperties type, which is largely a preference thing. Note that you can change this later without breaking the already-encoded messages.


问:
How to return specific rows first and then randomize the rest in MySQL?
I have this table where I have about 250 rows. What I want is to return all the rows, but first I want to display the six rows where the field spazio = 'auditorium' and then display all the remaining rows in a random order.
I've tried something like

```<code>SELECT * FROM table ORDER BY case when spazio = 'auditorium' then case spazio != 'auditorium' RAND()
</code>```

But it's not returning what I want.

答:
I would recommend two order by keys:

```<code>SELECT *
FROM table
ORDER BY (spazio = 'auditorium') desc, RAND()
</code>```

The first condition is a boolean.  Because true > false, you want a descending sort to get the auditoria first in the result set.

Body:
I have this table where I have about 250 rows. What I want is to return all the rows, but first I want to display the six rows where the field spazio = 'auditorium' and then display all the remaining rows in a random order.
I've tried something like

SELECT * FROM table ORDER BY case when spazio = 'auditorium' then case spazio != 'auditorium' RAND()

But it's not returning what I want.

Body:
I would recommend two order by keys:

SELECT *
FROM table
ORDER BY (spazio = 'auditorium') desc, RAND()

The first condition is a boolean.  Because true > false, you want a descending sort to get the auditoria first in the result set.


问:
How do I make Google Cloud Functions accept POST requests larger than 10KB?
I have created a small Python program accepting HTTP triggers and uploaded it to Google Cloud Functions.  It works fine when I make a POST request whose body is less than 10KB.

However, when I exceed this value, the function fails to work and sends error code 413 (request entity too large) in its response.  Is there something I might be missing?  When I read the quotas doc page, it says that Google Cloud Functions should allow requests of up to 10MB, which is clearly much more than what I am sending.

Thanks.

Edit:

The Python code parsing the POST data is as follows:

def html_switcher_test(request):

    request_args = request.args

    if request_args:

        report_html = BeautifulSoup(request.args['data'], 'lxml')
```

A Postman request screenshot showing the error is provided below:

答: This public issue tracker has been filed for this issue with an internal bug linked to it. Further feedback will be provided through there.</p>

Body:
I have created a small Python program accepting HTTP triggers and uploaded it to Google Cloud Functions.  It works fine when I make a POST request whose body is less than 10KB.

However, when I exceed this value, the function fails to work and sends error code 413 (request entity too large) in its response.  Is there something I might be missing?  When I read the quotas doc page, it says that Google Cloud Functions should allow requests of up to 10MB, which is clearly much more than what I am sending.

Thanks.

Edit:

The Python code parsing the POST data is as follows:

def html_switcher_test(request):

    request_args = request.args

    if request_args:

        report_html = BeautifulSoup(request.args['data'], 'lxml')

A Postman request screenshot showing the error is provided below:


问:
How to give label for null values with previous value
I have a table "person_visits" table have data like as below

The expected output should be like as below, the nulls should be replaced with the previous not null visited_location

Please suggest on this

Thanks

答:
Below i s for BigQuery Standard SQL    </p>

```<code>#standardSQL
SELECT * EXCEPT(fixed_location) REPLACE(fixed_location AS visited_location) FROM (
  SELECT *,
    LAST_VALUE(visited_location IGNORE NULLS)
    OVER(PARTITION BY person_id ORDER BY calendar_date
      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) fixed_location
  FROM `project.dataset.person_visits`
)
</code>```

<p>if to apply to sample data in your question - result is    </p>

```<code>Row person_id   calendar_date   visited_location    holiday_flag
1   1001        2020-02-03      New Jersey          N
2   1001        2020-02-04      New Jersey          N
3   1001        2020-02-05      New Jersey          N
4   1001        2020-02-06      New Jersey          N
5   1001        2020-02-07      New Jersey          N
6   1001        2020-02-08      New Jersey          Y
7   1001        2020-02-09      New Jersey          Y
8   1001        2020-02-10      New York            N
9   1001        2020-02-11      New York            N
10  1001        2020-02-12      New York            N
11  1001        2020-02-13      New York            N
12  1001        2020-02-14      New York            N
13  1001        2020-02-15      New York            Y
14  1001        2020-02-16      New York            Y
15  1001        2020-02-17      New York            Y
16  1001        2020-02-18      Los Angeles         N
17  1001        2020-02-19      Los Angeles         N
</code>```

Body:
Below i s for BigQuery Standard SQL

#standardSQL
SELECT * EXCEPT(fixed_location) REPLACE(fixed_location AS visited_location) FROM (
  SELECT *,
    LAST_VALUE(visited_location IGNORE NULLS)
    OVER(PARTITION BY person_id ORDER BY calendar_date
      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) fixed_location
  FROM `project.dataset.person_visits`
)

if to apply to sample data in your question - result is

Row person_id   calendar_date   visited_location    holiday_flag
1   1001        2020-02-03      New Jersey          N
2   1001        2020-02-04      New Jersey          N
3   1001        2020-02-05      New Jersey          N
4   1001        2020-02-06      New Jersey          N
5   1001        2020-02-07      New Jersey          N
6   1001        2020-02-08      New Jersey          Y
7   1001        2020-02-09      New Jersey          Y
8   1001        2020-02-10      New York            N
9   1001        2020-02-11      New York            N
10  1001        2020-02-12      New York            N
11  1001        2020-02-13      New York            N
12  1001        2020-02-14      New York            N
13  1001        2020-02-15      New York            Y
14  1001        2020-02-16      New York            Y
15  1001        2020-02-17      New York            Y
16  1001        2020-02-18      Los Angeles         N
17  1001        2020-02-19      Los Angeles         N


问:
Left Function Compile Error: Argument not optional (VBA)
I am trying to do a few things with this subroutine.
First i need to insert a row after every 18th row
Then i need to insert a string in column A based on the string in the above row (i.e. 17th row in the first iteration).
Finally i need to insert a string in column B of the ith row again based on the previously established string.

So in Layman's terms, row 17 will say 120F_CASH
i want to find "_ " and take the characters in the string from the left of the "_ ", then in row 18 i want to put 120F & "_MULTI_STRAT" in column A
in column B of row 18, i want to insert "SSELECT PERF.IMST.INDEX WITH ENTITY = " & "120F" & "AND WITH CATEGORY1 = ""01"""

here's my code:

```<code>Option Explicit

Sub InsertRowEveryXrows()
Dim r As Long, lr As Long
Dim code As String

lr = Range("A" & Rows.Count).End(xlUp).Row
    For r = 18 To lr Step 18
        Rows(r).Insert Shift:=xlDown
        Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1))
        Cells(r, "A") = code & "_MULTI_STRAT"
        Cells(r, "B") = "SSELECT PERF.IMST.INDEX WITH ENTITY = " & code & "AND WITH CATEGORY1 = ""01"""
    Next r
End Sub
</code>```

i am getting a compile error: Wrong number of arguments or invalid property assignments on this line:

Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A"))
  - 1))

the string's location is in row 17 (r-1) in column A & the number of characters is found by looking for "_"

What am i missing?
*fyi i had to add a space after the underscore for it to show up properly here, however, there SHOULD NOT be a space after the underscore.

答:
```<code>Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1))
</code>```

The Left function wants a string and an integer, but you haven't provided the integer. Here's the same expression, without the outer Left function call:

```<code>Set code = Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1)
</code>```

Notice anything? The result of InStr is being passed as the 2nd argument to the (unqualified) Range property, and that isn't what you intended.

In fact, you don't need that Range call at all. This should be closer to your intent:

```<code>Set code = Left(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1)
</code>```

Note that there is quite a bit of implicit code going on here; made explicit, reads like this:

```<code>Set code = Left(ActiveSheet.Cells(r - 1, "A").Value, InStr(1, "_", ActiveSheet.Cells(r, "A").Value) - 1)
</code>```

Do you really intend to be working of just whatever worksheet happens to be active? Most likely not, but if so, consider explicitly qualifying these Cells calls with ActiveSheet. If you mean to be working with a specific sheet, use that sheet object as a qualifier instead.

Now, you're using Set for this assignment, but code is not an object reference, and that is another problem.

Strings are not objects in VBA, they're assigned with the regular value assignment syntax. That is, without a Set keyword (you could have the legacy Let keyword there if you wanted, but it's not needed):

```<code>code = Left(ActiveSheet.Cells(r - 1, "A").Value, InStr(1, "_", ActiveSheet.Cells(r, "A").Value) - 1)
</code>```

Now, Range.Value (explicit here, implicit in your code) will be a Variant, not a String. In most cases, it won't matter.

Until one cell has a Variant/Error subtype (think #N/A, or #VALUE! worksheet errors); then everything blows up with a type mismatch error. To avoid this, you can use the Text of the cell instead of its Value, or you can pull that value into its own local Variant variable, and only proceed to treat it like a string when IsError returns False for it.

Body:
I am trying to do a few things with this subroutine.
First i need to insert a row after every 18th row
Then i need to insert a string in column A based on the string in the above row (i.e. 17th row in the first iteration).
Finally i need to insert a string in column B of the ith row again based on the previously established string.

So in Layman's terms, row 17 will say 120F_CASH
i want to find "_ " and take the characters in the string from the left of the "_ ", then in row 18 i want to put 120F & "_MULTI_STRAT" in column A
in column B of row 18, i want to insert "SSELECT PERF.IMST.INDEX WITH ENTITY = " & "120F" & "AND WITH CATEGORY1 = ""01"""

here's my code:

Option Explicit

Sub InsertRowEveryXrows()
Dim r As Long, lr As Long
Dim code As String

lr = Range("A" & Rows.Count).End(xlUp).Row
    For r = 18 To lr Step 18
        Rows(r).Insert Shift:=xlDown
        Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1))
        Cells(r, "A") = code & "_MULTI_STRAT"
        Cells(r, "B") = "SSELECT PERF.IMST.INDEX WITH ENTITY = " & code & "AND WITH CATEGORY1 = ""01"""
    Next r
End Sub

i am getting a compile error: Wrong number of arguments or invalid property assignments on this line:

Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A"))
  - 1))

the string's location is in row 17 (r-1) in column A & the number of characters is found by looking for "_"

What am i missing?
*fyi i had to add a space after the underscore for it to show up properly here, however, there SHOULD NOT be a space after the underscore.

Body:
Set code = Left(Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1))

The Left function wants a string and an integer, but you haven't provided the integer. Here's the same expression, without the outer Left function call:

Set code = Range(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1)

Notice anything? The result of InStr is being passed as the 2nd argument to the (unqualified) Range property, and that isn't what you intended.

In fact, you don't need that Range call at all. This should be closer to your intent:

Set code = Left(Cells(r - 1, "A"), InStr(1, "_", Cells(r, "A")) - 1)

Note that there is quite a bit of implicit code going on here; made explicit, reads like this:

Set code = Left(ActiveSheet.Cells(r - 1, "A").Value, InStr(1, "_", ActiveSheet.Cells(r, "A").Value) - 1)

Do you really intend to be working of just whatever worksheet happens to be active? Most likely not, but if so, consider explicitly qualifying these Cells calls with ActiveSheet. If you mean to be working with a specific sheet, use that sheet object as a qualifier instead.

Now, you're using Set for this assignment, but code is not an object reference, and that is another problem.

Strings are not objects in VBA, they're assigned with the regular value assignment syntax. That is, without a Set keyword (you could have the legacy Let keyword there if you wanted, but it's not needed):

code = Left(ActiveSheet.Cells(r - 1, "A").Value, InStr(1, "_", ActiveSheet.Cells(r, "A").Value) - 1)

Now, Range.Value (explicit here, implicit in your code) will be a Variant, not a String. In most cases, it won't matter.

Until one cell has a Variant/Error subtype (think #N/A, or #VALUE! worksheet errors); then everything blows up with a type mismatch error. To avoid this, you can use the Text of the cell instead of its Value, or you can pull that value into its own local Variant variable, and only proceed to treat it like a string when IsError returns False for it.


问:
Unicode std::string class replacement
I'm looking for suggestions regarding unicode aware std::string library replacements. I have a bunch of code that uses std::string, its iterators etc, and would like to now support unicode strings (free or open source implementations preferred, regex capabilities would be great!).

I'm not sure at this point if I require a complete rewrite or if I can get away with dropping in a new string library that supports all of the std::string interfaces. The unicode world seems very complex and I'm just wanting to enable it in my applications not have to learn every single aspect of it.

btw how does the index operator work when it has to pass back a reference to either a 1, 2,3 or 4 structure which could in theory change to either a 1,2,3 or 4 byte structure.  if a larger or smaller sized value is passed, does the shifting back and forth of the internal data representation occur insitu?

答:
Asking for "a type like std::string, but for Unicode" is like asking for "a type like unsigned, but for primes." std::string is perfectly capable of storing Unicode, in many encodings - the most generally useful being UTF-8.

What you need to replace is your iterators, not your storage type. The iterators should iterate over the codepoints of the string rather than the bytes. That is, ++i should advance one codepoint, and *i should return a codepoint (via uint32_t) rather than a char.

Title: Unicode std::string class replacement


问:
Convert a number column into a time format in Power BI
I'm looking for a way to convert a decimal number into a valid HH:mm:ss format.

I'm importing data from an SQL database.

One of the columns in my database is labelled Actual Start Time.

The values in my database are stored in the following decimal format:

```<code>73758    // which translates to 07:27:58
114436   // which translates to 11:44:36
</code>```

I cannot simply convert this Actual Start Time column into a Time format in my Power BI import as it returns errors for some values, saying it doesn't recognise 73758 as a valid 'time'. It needs to have a leading zero for cases such as 73758.

To combat this, I created a new Text column with the following code to append a leading zero:

```<code>Column = FORMAT([Actual Start Time], "000000")
</code>```

This returns the following results:

```<code>073758
114436
</code>```

-- which is perfect. Exactly what I needed.

I now want to convert these values into a Time.

Simply changing the data type field to Time doesn't do anything, returning:

Cannot convert value '073758' of type Text to type Date.

So I created another column with the following code:

```<code>Column 2 = FORMAT(TIME(LEFT([Column], 2), MID([Column], 3, 2), RIGHT([Column], 2)), "HH:mm:ss")
</code>```

To pass the values 07, 37 and 58 into a TIME format.

This returns the following:

```<code> _______________________________________
| Actual Start Date | Column | Column 2 |
|_______________________________________|
|       73758       | 073758 | 07:37:58 |
|       114436      | 114436 | 11:44:36 |

</code>```

Which is what I wanted but is there any other way of doing this? I want to ideally do it in one step without creating additional columns.

答:
I, on purpose show you the concept of variables so you can use this in future with more complex queries.</p>

```<code>TimeC =
var timeStr = FORMAT([Actual Start Time], "000000")
return FORMAT(TIME(LEFT([timeStr], 2), MID([timeStr], 3, 2), RIGHT([timeStr], 2)), "HH:mm:ss")
</code>```

Body:
I'm looking for a way to convert a decimal number into a valid HH:mm:ss format.

I'm importing data from an SQL database.

One of the columns in my database is labelled Actual Start Time.

The values in my database are stored in the following decimal format:

73758    // which translates to 07:27:58
114436   // which translates to 11:44:36

I cannot simply convert this Actual Start Time column into a Time format in my Power BI import as it returns errors for some values, saying it doesn't recognise 73758 as a valid 'time'. It needs to have a leading zero for cases such as 73758.

To combat this, I created a new Text column with the following code to append a leading zero:

Column = FORMAT([Actual Start Time], "000000")

This returns the following results:

073758
114436

-- which is perfect. Exactly what I needed.

I now want to convert these values into a Time.

Simply changing the data type field to Time doesn't do anything, returning:

Cannot convert value '073758' of type Text to type Date.

So I created another column with the following code:

Column 2 = FORMAT(TIME(LEFT([Column], 2), MID([Column], 3, 2), RIGHT([Column], 2)), "HH:mm:ss")

To pass the values 07, 37 and 58 into a TIME format.

This returns the following:

 _______________________________________
| Actual Start Date | Column | Column 2 |
|_______________________________________|
|       73758       | 073758 | 07:37:58 |
|       114436      | 114436 | 11:44:36 |

Which is what I wanted but is there any other way of doing this? I want to ideally do it in one step without creating additional columns.

Body:
I, on purpose show you the concept of variables so you can use this in future with more complex queries.

TimeC =
var timeStr = FORMAT([Actual Start Time], "000000")
return FORMAT(TIME(LEFT([timeStr], 2), MID([timeStr], 3, 2), RIGHT([timeStr], 2)), "HH:mm:ss")


问:
Okta 'request body was not well-formed' during very simple property update
I am calling the okta API from my .Net back-end. It works fine when creating the user (the first part of the snippet below), so I know the token is correct etc. and I can confirm the new user exists.

I also, subsequently, update a property I've added to the user called 'Site'. When attempting to assign this property a value it throws an exception on the 'UpdateAsync' line that the request body was not well formed

```<code>            var user = await _oktaClient.Users.CreateUserAsync(new CreateUserWithPasswordOptions
            {
                Profile = new UserProfile
                {
                    FirstName = value.FirstName,
                    LastName = value.Surname,
                    Email = value.Email,
                    Login = value.Email,
                },
                Password = value.Password,
                Activate = true,
            });

            var newUser = await _oktaClient.Users.GetUserAsync(user.Id);

            newUser["site"] = Site;
            await newUser.UpdateAsync(); // This line throws!
</code>```

Note: I wasn't always doing it this way, I was previously assigning to the user object and then calling UpdateAsync() once I'd updated 'site' on the user object. This is an alternative approach as I'm trying different things (i.e. getting the user from the API again). Neither approach works.

What's very strange is that this has been working, I am 100% certain of that. I'm looking through my okta users directory 'as we speak', and there are a load of users, all with their site property populated. There has been no problem previously. I believe something must've been updated okta's end that now doesn't like my request for some reason but in either case I need a work-around ideally.

I can confirm Site is neither null or empty, it's simply a string.

UPDATE

I just discovered a SetProperty extension on okta's IResource, calling this before attempting to update the user causes the same issue.

Any help on this greatly appreciated.

答: Looks like custom attributes can't be assigned to the User object itself anymore, but need to be in the users profile: newUser.Profile["site"] = Site;

Body:
I am calling the okta API from my .Net back-end. It works fine when creating the user (the first part of the snippet below), so I know the token is correct etc. and I can confirm the new user exists.

I also, subsequently, update a property I've added to the user called 'Site'. When attempting to assign this property a value it throws an exception on the 'UpdateAsync' line that the request body was not well formed

            var user = await _oktaClient.Users.CreateUserAsync(new CreateUserWithPasswordOptions
            {
                Profile = new UserProfile
                {
                    FirstName = value.FirstName,
                    LastName = value.Surname,
                    Email = value.Email,
                    Login = value.Email,
                },
                Password = value.Password,
                Activate = true,
            });

            var newUser = await _oktaClient.Users.GetUserAsync(user.Id);

            newUser["site"] = Site;
            await newUser.UpdateAsync(); // This line throws!

Note: I wasn't always doing it this way, I was previously assigning to the user object and then calling UpdateAsync() once I'd updated 'site' on the user object. This is an alternative approach as I'm trying different things (i.e. getting the user from the API again). Neither approach works.

What's very strange is that this has been working, I am 100% certain of that. I'm looking through my okta users directory 'as we speak', and there are a load of users, all with their site property populated. There has been no problem previously. I believe something must've been updated okta's end that now doesn't like my request for some reason but in either case I need a work-around ideally.

I can confirm Site is neither null or empty, it's simply a string.

UPDATE

I just discovered a SetProperty extension on okta's IResource, calling this before attempting to update the user causes the same issue.

Any help on this greatly appreciated.


问:
Spotify keyboard shortcuts - MacOS & Microsoft Sculpt keyboard
I recently got an ergonomic Sculpt keyboard that I use with my Macbook. I managed to configure some handy keyboard shortcuts for e.g. moving between screens but I'm failing miserably at configuring "Next" and "Previous" buttons to use with Spotify.

I tried first Karabiner but it's apparently missing both options. So I started digging in keyboard settings. In Keyboard -> Shortcuts -> App Shortcuts I'm able to add manually a new shortcut for moving to the next song. And it works but only when I'm on the screen with Spotify. But the whole point of this shortcut is to switch between songs while doing something else, without even looking at Spotify app. And that I cannot configure somehow.

Has anyone done something like this before and can recommend a solution? Thanks in advance.

答:
Karabiner can easily do this though. Make a complex modification rule

bind some keybind to keybind fastfoward to skip next song and rewind to go to previous track. play_or_pause for obviously playing or pausing.

in fact i made a simple test to see if this works or not

```<code>    {
      "description": "Spotify next and prev button map",
      "manipulators": [
        {
          "type": "basic",
          "from": {
            "key_code": "n"
          },
          "to": [ {
            "key_code": "fastforward"
          } ]
        }
      ]
    },
</code>```

I make the letter n here to be fastfoward you can edit as you like

Body:
Karabiner can easily do this though. Make a complex modification rule

bind some keybind to keybind fastfoward to skip next song and rewind to go to previous track. play_or_pause for obviously playing or pausing.

in fact i made a simple test to see if this works or not

    {
      "description": "Spotify next and prev button map",
      "manipulators": [
        {
          "type": "basic",
          "from": {
            "key_code": "n"
          },
          "to": [ {
            "key_code": "fastforward"
          } ]
        }
      ]
    },

I make the letter n here to be fastfoward you can edit as you like


问:
routerLinkActive does not update Hyperlink, when route.params id is changed
That is my plunkr:

https://plnkr.co/edit/C9W0pHvy27J83m25YUOJ?p=preview

These are the steps to retrace the problem:

Open project 'neverending'

the url shows /projects/1/tests then

The 'Tests link' is orange highlighted

change the route in the url bar to /projects/2/tests

the formerly highlighted 'Tests link' is now NOT orange anymore.

Why is the active class removed by angular?

答:
I faced this issue. Actually my route needs to change from projects/1/test to projects/2/test, where 1 and 2 are params in the url that may change. so I resolved it by following technique:

```<code><a routerLink="/projects/:id/test" routerLinkActive="on"
   [routerLinkActiveOptions]="{ exact: false, __change_detection_hack__: id }">
   Link
</a>
</code>```

where __change_detection_hack__ detects changes in the url and id is your url param name.

Note: if you are setting routerLink with some variable then you should do something like this:

```<code><a [routerLink]="myStringVar" routerLinkActive="on"
   [routerLinkActiveOptions]="{ exact: false, __change_detection_hack__: someVariable }">
   Link
</a>
</code>```

for detailed discussion, please visit here

Body:
I faced this issue. Actually my route needs to change from projects/1/test to projects/2/test, where 1 and 2 are params in the url that may change. so I resolved it by following technique:

<a routerLink="/projects/:id/test" routerLinkActive="on"
   [routerLinkActiveOptions]="{ exact: false, __change_detection_hack__: id }">
   Link
</a>

where __change_detection_hack__ detects changes in the url and id is your url param name.

Note: if you are setting routerLink with some variable then you should do something like this:

<a [routerLink]="myStringVar" routerLinkActive="on"
   [routerLinkActiveOptions]="{ exact: false, __change_detection_hack__: someVariable }">
   Link
</a>

for detailed discussion, please visit here


问:
font looks pixalated in IE8
I build that site with dynamic portfolio, now i looked at it in IE8 and for some reason font with sub navigation on the right hand side is getting distorted and have this unwanted white background it looks fine in all the other browsers only IE8 gives me that problem have a look at site and please help.

http://teddington-kitchens.fsdegrees.com/portfolio/

答:
It's to do with setting opacity on an element - IE has a long-standing bug with font-rendering using opacity values. I believe it's actually part of the underlying operating system's "ClearType" anti-aliasing. I'm afraid the only way I've gotten around it in the past is to sniff for IE and not use opacity, but then again I'm pretty lazy like that... :)

Here's a workaround you could try - it uses IE's proprietary filters attribute if possible, which seems to get around the auto-disabling of ClearType mode.

Title: font looks pixalated in IE8


问:
make a vertical scroll view with horizontal rows react native
I'm new to programming and react-native and I'm trying to make a Scrollview and get values from a JSON file and show 2 boxes in each row but when I use flexDirection : 'row' they all merge into each other.

Thank you I appreciate every help.
The section below is my code:

```<code>export default class Creative extends Component {

    constructor(props) {
        super(props);
        this.state = { isLoading: true, refreshing: false, }
    }

    _fetchData = () => {
        const key = 'D0BEFCE031A955294DE1DD87C14B13EA77CBF8A86F293FD30E9B8D57F3C401F9';
        var type = 'creative';
        const lal = `imapp=${key}&type=${type}`;
        fetch('https://facebook.github.io/react-native/movies.json', {
            method: 'get',
            headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
            }),
        }).then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.list,
                    refreshing: false,
                });

            })
            .catch((error) => {
                console.error(error);
            });
    }

    componentDidMount() {
        this._fetchData();
    }

    _onRefresh = () => {
        () => this.setState({ refreshing: true, });
        status = '1';
        this._fetchData();
    }

    render() {
        return (
            <SafeAreaView>
                <View style={{ backgroundColor: '#323232' }}>
                    <View style={{ flex: 1, paddingTop: 20 }}>
                        <View style={{ flex: 1, paddingTop: 20 }}>
                            <FlatList
                                data={this.state.dataSource}
                                renderItem={({ item }) => <Text>{item.title}, {item.releaseYear}</Text>}
                                keyExtractor={({ id }, index) => id}
                            />
                        </View>
                    </View>
                </View>
            </SafeAreaView>
        );
    }
}
</code>```

答:
Use numColumns in ReactNative Flatlist to render multiple columns & Change your Flatlist as below

```<code><FlatList
    data={this.state.dataSource}
    renderItem={({ item }) => (
        <View style={{ width: '40%', justifyContent: 'space-between', backgroundColor: 'red', margin: 5 }}>
            <Text>{item.title}, {item.releaseYear}</Text>
        </View>
    )}
    keyExtractor={item => item.id}
    numColumns={2}
/>
</code>```

Change this according to your requirements.

Hope this helps you. Feel free for doubts.

Body:
I'm new to programming and react-native and I'm trying to make a Scrollview and get values from a JSON file and show 2 boxes in each row but when I use flexDirection : 'row' they all merge into each other.

Thank you I appreciate every help.
The section below is my code:

export default class Creative extends Component {

    constructor(props) {
        super(props);
        this.state = { isLoading: true, refreshing: false, }
    }

    _fetchData = () => {
        const key = 'D0BEFCE031A955294DE1DD87C14B13EA77CBF8A86F293FD30E9B8D57F3C401F9';
        var type = 'creative';
        const lal = `imapp=${key}&type=${type}`;
        fetch('https://facebook.github.io/react-native/movies.json', {
            method: 'get',
            headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
            }),
        }).then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.list,
                    refreshing: false,
                });

            })
            .catch((error) => {
                console.error(error);
            });
    }

    componentDidMount() {
        this._fetchData();
    }

    _onRefresh = () => {
        () => this.setState({ refreshing: true, });
        status = '1';
        this._fetchData();
    }

    render() {
        return (
            <SafeAreaView>
                <View style={{ backgroundColor: '#323232' }}>
                    <View style={{ flex: 1, paddingTop: 20 }}>
                        <View style={{ flex: 1, paddingTop: 20 }}>
                            <FlatList
                                data={this.state.dataSource}
                                renderItem={({ item }) => <Text>{item.title}, {item.releaseYear}</Text>}
                                keyExtractor={({ id }, index) => id}
                            />
                        </View>
                    </View>
                </View>
            </SafeAreaView>
        );
    }
}

Body:
Use numColumns in ReactNative Flatlist to render multiple columns & Change your Flatlist as below

<FlatList
    data={this.state.dataSource}
    renderItem={({ item }) => (
        <View style={{ width: '40%', justifyContent: 'space-between', backgroundColor: 'red', margin: 5 }}>
            <Text>{item.title}, {item.releaseYear}</Text>
        </View>
    )}
    keyExtractor={item => item.id}
    numColumns={2}
/>

Change this according to your requirements.

Hope this helps you. Feel free for doubts.


问:
GPy and GPflow mathematical background - references
Does GPy and GPflow share a common mathematical background? I'm asking this because I'm using GPy but I cannot see the references. However, GPflow provides references in its examples.

Is it Ok using keep using GPy or would you suggest the use GPflow inmediately for gaussian processes purposes?

答:
GPy and GPflow definitely share a common mathematical background: Gaussian processes Rasmussen and Williams, and many of the concepts are very similar in both frameworks: kernels, likelihoods, mean-functions, inducing points, etc. For me, the biggest difference between GPy and GPflow is the computational backend: AFAIK GPy uses plain Python and numpy to perform all its computations, whereas GPflow relies on TensorFlow. This gives GPflow multiple nice features for free: GPU acceleration, automatic gradients, compatibility with TF eco-system, etc. Depending on your use-case, these features can be crucial or simply nice-to-have.

Here is more information on the technical details between the two frameworks:
https://gpflow.readthedocs.io/en/master/intro.html#what-s-the-difference-between-gpy-and-gpflow


问:
Access multiple request params in flow
I have an action state in a Spring Web Flow that take in parameters from a submitted form:

<action-state id="newToken">
    <set name="requestScope.timestamp" value="requestParameters.timestamp" type="java.lang.String"/>
    <set name="requestScope.origin" value="requestParameters.origin" type="java.lang.String"/>
    <set name="requestScope.tokenHmacToValidate" value="requestParameters.tokenHmacToValidate" type="java.lang.String"/>
    <transition to="validateToken"/>
</action-state>
```

<p>However, only the first <code>requestParameters</code> value gets set (i.e. if <code>timestamp</code> is first, then only it gets set. If <code>origin</code> is first, then only it gets set). When I access the second and third values, they have a value of <code>null</code> instead of the value that is passed into it. Here is an example of form data that is passed on form submission:</p>

```_eventId=tokenValidationEvent
origin=https%3A%2F%2Flocalhost%3A8443
timestamp=20200218171041
tokenHmacToValidate=**REDACTED**
```

All the information is getting passed when the form is submitted, but only the first <set> tag is actually setting data. Am I receiveing the request wrong? Is there something I need to register somewhere that I'm not doing

答:
This is the way <action-state> works. Only the first expression is evaluated.

If you want all three to be evaluated, you could use <on-entry> to evaluate the other 2:

    <action-state id="newToken">
        <on-entry>
            <set name="requestScope.timestamp" value="requestParameters.timestamp" type="java.lang.String"/>
            <set name="requestScope.origin" value="requestParameters.origin" type="java.lang.String"/>
        </on-entry>
        <set name="requestScope.tokenHmacToValidate" value="requestParameters.tokenHmacToValidate" type="java.lang.String"/>
        <transition to="validateToken"/>
    </action-state>
```

From https://docs.spring.io/spring-webflow/docs/current/reference/html/actions.html#action-state

After the execution of each action, the action-state checks the result to see if matches a declared transition to another state. That means if more than one action is configured they are executed in an ordered chain until one returns a result event that matches a state transition out of the action-state while the rest are ignored. This is a form of the Chain of Responsibility (CoR) pattern.

The result of an action's execution is typically the criteria for a transition out of this state. Additional information in the current RequestContext may also be tested as part of custom transitional criteria allowing for sophisticated transition expressions that reason on contextual state.

Note also that an action-state just like any other state can have one more on-entry actions that are executed as a list from start to end.

Title: Access multiple request params in flow

Body:
I have an action state in a Spring Web Flow that take in parameters from a submitted form:

<action-state id="newToken">
    <set name="requestScope.timestamp" value="requestParameters.timestamp" type="java.lang.String"/>
    <set name="requestScope.origin" value="requestParameters.origin" type="java.lang.String"/>
    <set name="requestScope.tokenHmacToValidate" value="requestParameters.tokenHmacToValidate" type="java.lang.String"/>
    <transition to="validateToken"/>
</action-state>

However, only the first requestParameters value gets set (i.e. if timestamp is first, then only it gets set. If origin is first, then only it gets set). When I access the second and third values, they have a value of null instead of the value that is passed into it. Here is an example of form data that is passed on form submission:

_eventId=tokenValidationEvent
origin=https%3A%2F%2Flocalhost%3A8443
timestamp=20200218171041
tokenHmacToValidate=**REDACTED**

All the information is getting passed when the form is submitted, but only the first <set> tag is actually setting data. Am I receiveing the request wrong? Is there something I need to register somewhere that I'm not doing

Body:
This is the way <action-state> works. Only the first expression is evaluated.

If you want all three to be evaluated, you could use <on-entry> to evaluate the other 2:

    <action-state id="newToken">
        <on-entry>
            <set name="requestScope.timestamp" value="requestParameters.timestamp" type="java.lang.String"/>
            <set name="requestScope.origin" value="requestParameters.origin" type="java.lang.String"/>
        </on-entry>
        <set name="requestScope.tokenHmacToValidate" value="requestParameters.tokenHmacToValidate" type="java.lang.String"/>
        <transition to="validateToken"/>
    </action-state>

From https://docs.spring.io/spring-webflow/docs/current/reference/html/actions.html#action-state

After the execution of each action, the action-state checks the result to see if matches a declared transition to another state. That means if more than one action is configured they are executed in an ordered chain until one returns a result event that matches a state transition out of the action-state while the rest are ignored. This is a form of the Chain of Responsibility (CoR) pattern.

The result of an action's execution is typically the criteria for a transition out of this state. Additional information in the current RequestContext may also be tested as part of custom transitional criteria allowing for sophisticated transition expressions that reason on contextual state.

Note also that an action-state just like any other state can have one more on-entry actions that are executed as a list from start to end.


问:
Put a slider right under a subplot in matplotlib
I'm trying to put a slider right under the x-axis of a subplot in matplotlib, so that both start and end at the same value. Is there an easy way to do that, meaning that I don't have to find the right coordinates and put them myself when I create the plt.axe containing the slider?</p>

答:
You could use ax.get_position() to get x0, y0, width and height of the axis and use this to define the positions for the axes of the slider.

I adapted the matplotlib example to show a use case:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.3)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
delta_f = 5.0
s = a0 * np.sin(2 * np.pi * f0 * t)
l, = plt.plot(t, s, lw=2)
ax.margins(x=0)

axcolor = 'lightgoldenrodyellow'

def xaligned_axes(ax, y_distance, width, **kwargs):
    return plt.axes([ax.get_position().x0,
                     ax.get_position().y0-y_distance,
                     ax.get_position().width, width],
                    **kwargs)

axfreq = xaligned_axes(ax=ax, y_distance=0.1, width=0.03, facecolor=axcolor)
axamp = xaligned_axes(ax=ax, y_distance=0.15, width=0.03, facecolor=axcolor)

sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0, valstep=delta_f)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)

def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp*np.sin(2*np.pi*freq*t))
    fig.canvas.draw_idle()

sfreq.on_changed(update)
samp.on_changed(update)
```

But as you have to use plt.subplots_adjust(bottom=0.3) to have enough space below the plot and you need to define the width and the distance to the axis in y direction I guess you do not win that much.

Body:
You could use ax.get_position() to get x0, y0, width and height of the axis and use this to define the positions for the axes of the slider.

I adapted the matplotlib example to show a use case:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.3)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
delta_f = 5.0
s = a0 * np.sin(2 * np.pi * f0 * t)
l, = plt.plot(t, s, lw=2)
ax.margins(x=0)

axcolor = 'lightgoldenrodyellow'

def xaligned_axes(ax, y_distance, width, **kwargs):
    return plt.axes([ax.get_position().x0,
                     ax.get_position().y0-y_distance,
                     ax.get_position().width, width],
                    **kwargs)

axfreq = xaligned_axes(ax=ax, y_distance=0.1, width=0.03, facecolor=axcolor)
axamp = xaligned_axes(ax=ax, y_distance=0.15, width=0.03, facecolor=axcolor)

sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0, valstep=delta_f)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)

def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp*np.sin(2*np.pi*freq*t))
    fig.canvas.draw_idle()

sfreq.on_changed(update)
samp.on_changed(update)

But as you have to use plt.subplots_adjust(bottom=0.3) to have enough space below the plot and you need to define the width and the distance to the axis in y direction I guess you do not win that much.


问:
Laravel 5.2 artisan error: Parse error: syntax error, unexpected ':'
Error

i am using Laravel 5.2 and PHP 7.3.12. and everything was working fine but today whenever i write any artisan command in laravel it gives this error:

[Symfony\Component\Debug\Exception\FatalThrowableError]   Parse error: syntax error, unexpected ':'

i don't understand why its giving this error because last night it was working fine.

答:
There must be No extra space " " between : and list

```<code>php artisan route:list
</code>```

Body:
There must be No extra space " " between : and list

php artisan route:list


问:
how can I treat different apostrophe formats the same way in a js regex?
I need the ability to evaluate the following strings as equal even though the apostrophe format is different between the strings:

Hickman’s

Hickman's

Can you recommend a good way for me to do this in js?

答:
Try this:

const
  first = 'Hickman’s',
  second = "Hickman's",
  isEquals = !first.localeCompare(second, 'en', { ignorePunctuation: true });

console.log(isEquals);```