问:
Spark SQL join based on priority match
I am stuck on a problem where I have to produce a resulting dataset by joining a source dataset against a bunch of transformation rules. Now for a given entity, a number of rules can match but only the first rule that matches needs be selected for this match.
Here's an example of my source dataset

```<code>Id,Group,Person,Item,Count
1000000,Finance,Scott,Fan,100
1000000,HR,Taylor,Light,200
1000000,Finance,Troy,Table,100
1000000,Legal,Willian,Chair,100
</code>```

The other data set to join has a bunch of transformations that look like the following,

```<code>Field,Source,Targets
Person,Scott,[Taylor, William]
Item,Light,[Table, Chair]
GroupHR,Finance;[Legal]
</code>```

The following is the processing order for which I'm stuck in building the SQL Join query

```<code>Row1 -> Matches tansform1, Scott -100, Taylor +50, William +50
Row2 -> Matches tansform2,tansform3. Pick tansform2 only, Light -200, Table +100, Chair +100
Row3 -> Doesn't match any policy.
Row4 -> Doesn't match any policy.
</code>```

Any ideas on how this can be achieved in Spark SQL ? As a C# primary developer I could do this with a foreach on the row but is that the ideal way to do this computation ?

答:
Ok, here you are

```<code>val jdata = """[
{"id": 1, "group": "finance", "person": "scott", "item": "fan", "count": 100},
{"id": 2, "group": "hr", "person": "taylor", "item": "light", "count": 200},
{"id": 3, "group": "finance", "person": "troy", "item": "table", "count": 300},
{"id": 4, "group": "legal", "person": "willian", "item": "chair", "count": 400}
]"""

val data = spark.read.json(Seq(jdata).toDS)
data.registerTempTable("data")

val jtrans = """[
{"field": "person", "source": "scott", "targets": "taylor,willian"},
{"field": "item", "source": "light", "targets": "table,chair"},
{"field": "group", "source": "hr", "targets": "legal"}
]"""

val trans = spark.read.json(Seq(jtrans).toDS)
trans.registerTempTable("trans")
</code>```

Let's check

```<code>scala> spark.sql("SELECT * FROM data").show
+-----+-------+---+-----+-------+
|count|  group| id| item| person|
+-----+-------+---+-----+-------+
|  100|finance|  1|  fan|  scott|
|  200|     hr|  2|light| taylor|
|  300|finance|  3|table|   troy|
|  400|  legal|  4|chair|willian|
+-----+-------+---+-----+-------+

scala> spark.sql("SELECT * FROM trans").show
+------+------+--------------+
| field|source|       targets|
+------+------+--------------+
|person| scott|taylor,willian|
|  item| light|   table,chair|
| group|    hr|         legal|
+------+------+--------------+
</code>```

And the SQL

```<code>spark.sql("""
WITH
datac AS (
SELECT CONCAT('item_', item) itemc, CONCAT('person_', person) personc, count
FROM data
),
trans_person AS (
SELECT count, personc, itemc, source as source_person, targets as targets_person
FROM datac LEFT JOIN trans ON CONCAT(field, '_', source) = personc
),
trans_item AS (
SELECT count, personc, itemc, source_person, targets_person, source as source_item, targets as targets_item
FROM trans_person LEFT JOIN trans t2 ON CONCAT(t2.field, '_', t2.source) = itemc
),
trans_concat AS (
SELECT CASE WHEN source_person IS NOT NULL THEN 'person' WHEN source_item IS NOT NULL THEN 'item' END AS field,
CONCAT(COALESCE(source_person, ''), COALESCE(source_item, '')) as source,
CONCAT(COALESCE(targets_person, ''), COALESCE(targets_item, '')) AS targets,
count
FROM trans_item
),
trans_source AS (
SELECT field, source, count as cnt
FROM trans_concat
WHERE field IS NOT NULL
),
trans_target AS (
SELECT field, EXPLODE(SPLIT(targets, ',')) as target, count / SIZE(SPLIT(targets, ',')) as cnt
FROM trans_concat
WHERE field IS NOT NULL
)
SELECT count + COALESCE(t1.cnt, 0) + COALESCE(t2.cnt, 0) - COALESCE(t3.cnt, 0) - COALESCE(t4.cnt, 0) AS count,
group, id, item, person
FROM data
LEFT JOIN trans_target t1 ON  CONCAT('person_', person) = CONCAT(t1.field, '_', t1.target)
LEFT JOIN trans_target t2 ON  CONCAT('item_', item) = CONCAT(t2.field, '_', t2.target)
LEFT JOIN trans_source t3 ON  CONCAT('person_', person) = CONCAT(t3.field, '_', t3.source)
LEFT JOIN trans_source t4 ON  CONCAT('item_', item) = CONCAT(t4.field, '_', t4.source)
""").show()
</code>```

The result

```<code>+-----+-------+---+-----+-------+
|count|  group| id| item| person|
+-----+-------+---+-----+-------+
| 50.0|     hr|  2|light| taylor|
|550.0|  legal|  4|chair|willian|
|400.0|finance|  3|table|   troy|
|  0.0|finance|  1|  fan|  scott|
+-----+-------+---+-----+-------+
</code>```

For simplicity I did it only for 'item' and 'person', but you can easily extend it for 'id' and 'group'.

Also if you want to apply only the first rule you have to use window function which I also omitted for simplicity.

The answer is tested in spark Scala shell, but the main code is in plain SQL and it should work in pyspark.

Title: Spark SQL join based on priority match

Body:
I am stuck on a problem where I have to produce a resulting dataset by joining a source dataset against a bunch of transformation rules. Now for a given entity, a number of rules can match but only the first rule that matches needs be selected for this match.
Here's an example of my source dataset

Id,Group,Person,Item,Count
1000000,Finance,Scott,Fan,100
1000000,HR,Taylor,Light,200
1000000,Finance,Troy,Table,100
1000000,Legal,Willian,Chair,100

The other data set to join has a bunch of transformations that look like the following,

Field,Source,Targets
Person,Scott,[Taylor, William]
Item,Light,[Table, Chair]
GroupHR,Finance;[Legal]

The following is the processing order for which I'm stuck in building the SQL Join query

Row1 -> Matches tansform1, Scott -100, Taylor +50, William +50
Row2 -> Matches tansform2,tansform3. Pick tansform2 only, Light -200, Table +100, Chair +100
Row3 -> Doesn't match any policy.
Row4 -> Doesn't match any policy.

Any ideas on how this can be achieved in Spark SQL ? As a C# primary developer I could do this with a foreach on the row but is that the ideal way to do this computation ?

Body:
Ok, here you are

val jdata = """[
{"id": 1, "group": "finance", "person": "scott", "item": "fan", "count": 100},
{"id": 2, "group": "hr", "person": "taylor", "item": "light", "count": 200},
{"id": 3, "group": "finance", "person": "troy", "item": "table", "count": 300},
{"id": 4, "group": "legal", "person": "willian", "item": "chair", "count": 400}
]"""

val data = spark.read.json(Seq(jdata).toDS)
data.registerTempTable("data")

val jtrans = """[
{"field": "person", "source": "scott", "targets": "taylor,willian"},
{"field": "item", "source": "light", "targets": "table,chair"},
{"field": "group", "source": "hr", "targets": "legal"}
]"""

val trans = spark.read.json(Seq(jtrans).toDS)
trans.registerTempTable("trans")

Let's check

scala> spark.sql("SELECT * FROM data").show
+-----+-------+---+-----+-------+
|count|  group| id| item| person|
+-----+-------+---+-----+-------+
|  100|finance|  1|  fan|  scott|
|  200|     hr|  2|light| taylor|
|  300|finance|  3|table|   troy|
|  400|  legal|  4|chair|willian|
+-----+-------+---+-----+-------+

scala> spark.sql("SELECT * FROM trans").show
+------+------+--------------+
| field|source|       targets|
+------+------+--------------+
|person| scott|taylor,willian|
|  item| light|   table,chair|
| group|    hr|         legal|
+------+------+--------------+

And the SQL

spark.sql("""
WITH
datac AS (
SELECT CONCAT('item_', item) itemc, CONCAT('person_', person) personc, count
FROM data
),
trans_person AS (
SELECT count, personc, itemc, source as source_person, targets as targets_person
FROM datac LEFT JOIN trans ON CONCAT(field, '_', source) = personc
),
trans_item AS (
SELECT count, personc, itemc, source_person, targets_person, source as source_item, targets as targets_item
FROM trans_person LEFT JOIN trans t2 ON CONCAT(t2.field, '_', t2.source) = itemc
),
trans_concat AS (
SELECT CASE WHEN source_person IS NOT NULL THEN 'person' WHEN source_item IS NOT NULL THEN 'item' END AS field,
CONCAT(COALESCE(source_person, ''), COALESCE(source_item, '')) as source,
CONCAT(COALESCE(targets_person, ''), COALESCE(targets_item, '')) AS targets,
count
FROM trans_item
),
trans_source AS (
SELECT field, source, count as cnt
FROM trans_concat
WHERE field IS NOT NULL
),
trans_target AS (
SELECT field, EXPLODE(SPLIT(targets, ',')) as target, count / SIZE(SPLIT(targets, ',')) as cnt
FROM trans_concat
WHERE field IS NOT NULL
)
SELECT count + COALESCE(t1.cnt, 0) + COALESCE(t2.cnt, 0) - COALESCE(t3.cnt, 0) - COALESCE(t4.cnt, 0) AS count,
group, id, item, person
FROM data
LEFT JOIN trans_target t1 ON  CONCAT('person_', person) = CONCAT(t1.field, '_', t1.target)
LEFT JOIN trans_target t2 ON  CONCAT('item_', item) = CONCAT(t2.field, '_', t2.target)
LEFT JOIN trans_source t3 ON  CONCAT('person_', person) = CONCAT(t3.field, '_', t3.source)
LEFT JOIN trans_source t4 ON  CONCAT('item_', item) = CONCAT(t4.field, '_', t4.source)
""").show()

The result

+-----+-------+---+-----+-------+
|count|  group| id| item| person|
+-----+-------+---+-----+-------+
| 50.0|     hr|  2|light| taylor|
|550.0|  legal|  4|chair|willian|
|400.0|finance|  3|table|   troy|
|  0.0|finance|  1|  fan|  scott|
+-----+-------+---+-----+-------+

For simplicity I did it only for 'item' and 'person', but you can easily extend it for 'id' and 'group'.

Also if you want to apply only the first rule you have to use window function which I also omitted for simplicity.

The answer is tested in spark Scala shell, but the main code is in plain SQL and it should work in pyspark.


来源: stackexchange

问:
Is it possible to use AWS Route 53 as a DNS provider for a bare-metal K8s cluster?
I would like to use Route 53 as the DNS provider of a bare-metal k8s cluster. I've found a few guides on the internet, but they are all for cloud k8s clusters. </p>

<p>Have anyone done this before? </p>

答:
I've managed to set this up on my on-prem K8s cluster. I used "external-dns" - running locally (https://github.com/kubernetes-sigs/external-dns), and this is what I've done from the AWS side:

On AWS

Create the following resources:

```<code>IAM user k8s-r53-user
IAM policy assume-role-policy (attached to the k8s-r53-user)
IAM policy allow-k8s-r53-connection
IAM role k8s-r53-role (allow-k8s-r53-connection policy attached to this role)
</code>```

1 - Create IAM resource:

```<code>     $ aws iam create-user --user-name k8s-r53-user
</code>```

2 - Create policy (pretty generic):

policy-document1.json

        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "iam:ListRoles",
                        "sts:AssumeRole"
                    ],
                    "Resource": "*"
                }
            ]
        }
```
<p>run:</p>
<pre class="lang-sh prettyprint-override"><code>$ aws iam create-policy --policy-name assume-role-policy --policy-document policy-document1.json
</code>```

3 - attach the policy to k8s-r53-user:

$ aws iam attach-user-policy --user-name k8s-r53-user --policy-arn "arn:aws:iam::${account_id}:policy/assume-role-policy"
```
<p>check:</p>
<pre class="lang-sh prettyprint-override"><code>$ aws iam list-attached-user-policies --user-name k8s-r53-user
</code>```

4 - create an IAM policy which will be attached to the role.

policy-document2.json:

        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "route53:ChangeResourceRecordSets"
                    ],
                    "Resource": "arn:aws:route53:::hostedzone/*"
                },
            {
              "Effect": "Allow",
              "Action": [
                "route53:ListHostedZones",
                "route53:ListResourceRecordSets"
              ],
              "Resource": [
                "*"
              ]
            }

            ]
        }
```
<p>run:</p>
<pre class="lang-sh prettyprint-override"><code>$ aws iam create-policy --policy-name allow-k8s-r53-connection --policy-document policy-document2.json
</code>```

5 - Create IAM role:

application-role-trust-policy.json:

        {
            "Version": "2012-10-17",
            "Statement": {
                "Effect": "Allow",
                "Principal": { "AWS": "arn:aws:iam::<account_id>:root" },
                "Action": "sts:AssumeRole"
            }
        }
```
<p>run:</p>
<pre class="lang-sh prettyprint-override"><code>$ aws iam create-role --role-name k8s-r53-role --assume-role-policy-document application-role-trust-policy.json
</code>```

6 - Configure k8s-r53-user on on-premise server

Create access keys for the k8s-r53-user:

$ aws iam create-access-key --user-name k8s-r53-user
```
<ul>
<li>Use the values from the last command output and run:</li>
</ul>
<pre class="lang-sh prettyprint-override"><code>$ aws configure
    AWS Access Key ID []: xxx
    AWS Secret Access Key []: xxx
    Default region name []:
    Default output format [None]:
</code>```

K8s side

Follow the guide on the External-Dns page, section "Running locally", the only part that changes is the end:

run:

$ builds/external-dns --registry txt --provider=aws --aws-assume-'role=arn:aws:iam::${account_id}:role/k8s-r53-role --source service --once --dry-run'
```
<p><strong>instead of:</strong></p>
<pre class="lang-sh prettyprint-override"><code>$ external-dns --registry txt --txt-owner-id my-cluster-id --provider google --google-project example-project --source service --once --dry-run
</code>```

References

https://medium.com/@lvthillo/connect-on-premise-python-application-with-aws-services-using-roles-8b24ab4872e6

External DNS official repo

ContentLicense: CC BY-SA 4.0

Body:
I would like to use Route 53 as the DNS provider of a bare-metal k8s cluster. I've found a few guides on the internet, but they are all for cloud k8s clusters.

Have anyone done this before?

Body:
I've managed to set this up on my on-prem K8s cluster. I used "external-dns" - running locally (https://github.com/kubernetes-sigs/external-dns), and this is what I've done from the AWS side:

On AWS

Create the following resources:

IAM user k8s-r53-user
IAM policy assume-role-policy (attached to the k8s-r53-user)
IAM policy allow-k8s-r53-connection
IAM role k8s-r53-role (allow-k8s-r53-connection policy attached to this role)

1 - Create IAM resource:

     $ aws iam create-user --user-name k8s-r53-user

2 - Create policy (pretty generic):

policy-document1.json

        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "iam:ListRoles",
                        "sts:AssumeRole"
                    ],
                    "Resource": "*"
                }
            ]
        }

run:

$ aws iam create-policy --policy-name assume-role-policy --policy-document policy-document1.json

3 - attach the policy to k8s-r53-user:

$ aws iam attach-user-policy --user-name k8s-r53-user --policy-arn "arn:aws:iam::${account_id}:policy/assume-role-policy"

check:

$ aws iam list-attached-user-policies --user-name k8s-r53-user

4 - create an IAM policy which will be attached to the role.

policy-document2.json:

        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "route53:ChangeResourceRecordSets"
                    ],
                    "Resource": "arn:aws:route53:::hostedzone/*"
                },
            {
              "Effect": "Allow",
              "Action": [
                "route53:ListHostedZones",
                "route53:ListResourceRecordSets"
              ],
              "Resource": [
                "*"
              ]
            }

            ]
        }

run:

$ aws iam create-policy --policy-name allow-k8s-r53-connection --policy-document policy-document2.json

5 - Create IAM role:

application-role-trust-policy.json:

        {
            "Version": "2012-10-17",
            "Statement": {
                "Effect": "Allow",
                "Principal": { "AWS": "arn:aws:iam::<account_id>:root" },
                "Action": "sts:AssumeRole"
            }
        }

run:

$ aws iam create-role --role-name k8s-r53-role --assume-role-policy-document application-role-trust-policy.json

6 - Configure k8s-r53-user on on-premise server

Create access keys for the k8s-r53-user:

$ aws iam create-access-key --user-name k8s-r53-user

Use the values from the last command output and run:

$ aws configure
    AWS Access Key ID []: xxx
    AWS Secret Access Key []: xxx
    Default region name []:
    Default output format [None]:

K8s side

Follow the guide on the External-Dns page, section "Running locally", the only part that changes is the end:

run:

$ builds/external-dns --registry txt --provider=aws --aws-assume-'role=arn:aws:iam::${account_id}:role/k8s-r53-role --source service --once --dry-run'

instead of:

$ external-dns --registry txt --txt-owner-id my-cluster-id --provider google --google-project example-project --source service --once --dry-run

References

https://medium.com/@lvthillo/connect-on-premise-python-application-with-aws-services-using-roles-8b24ab4872e6

External DNS official repo


问:
Error: Action has more than one parameter bound from request body
I wrote a new method into my Controller of my ASP.Net MVC project and getting error below. I think InvalidOperationException coming from with Swagger. I marked it as "ignored Api" hoping it will skip the method but error still there:

```<code>[ApiExplorerSettings(IgnoreApi = true)]
public decimal CalculatePriceWithCampaign(
       BeverageCapacityCampaign campaign,
       BeverageCapacity capacity,
       int count = 1)
{
    switch (campaign.DiscountType)
    {
        case DiscountType.Fixed:
            return (capacity.CapacityPrice - campaign.DiscountValue) * count;
        case DiscountType.Percentage:
            return (capacity.CapacityPrice * count) * campaign.DiscountValue;
        default:
            return capacity.CapacityPrice;
    }
}
</code>```

But when running I am getting this error:

An unhandled exception occurred while processing the request.

InvalidOperationException: Action 'Gorilla.WebApi.Source.Controller.Campaigns.BeverageCapacityCampaignController.CalculatePriceWithCampaign (Gorilla.WebApi)' has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be bound from body. Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to specify bound from route, and 'FromBodyAttribute' for parameters to be bound from body:

    BeverageCapacityCampaign campaign

    BeverageCapacity capacity

Information I could find suggested to check nugets, but all my Nugets are up-to-date.

答: My controller has some refactored code whose methods are marked public.  Looks like either moving them out of the controller or marking private corrects this problem.  Or attributing the pesky methods with [NonAction] might also be a choice as asked at asp.net Core mvc hide and exclude Web Api Controller Method

Body:
I wrote a new method into my Controller of my ASP.Net MVC project and getting error below. I think InvalidOperationException coming from with Swagger. I marked it as "ignored Api" hoping it will skip the method but error still there:

[ApiExplorerSettings(IgnoreApi = true)]
public decimal CalculatePriceWithCampaign(
       BeverageCapacityCampaign campaign,
       BeverageCapacity capacity,
       int count = 1)
{
    switch (campaign.DiscountType)
    {
        case DiscountType.Fixed:
            return (capacity.CapacityPrice - campaign.DiscountValue) * count;
        case DiscountType.Percentage:
            return (capacity.CapacityPrice * count) * campaign.DiscountValue;
        default:
            return capacity.CapacityPrice;
    }
}

But when running I am getting this error:

An unhandled exception occurred while processing the request.

InvalidOperationException: Action 'Gorilla.WebApi.Source.Controller.Campaigns.BeverageCapacityCampaignController.CalculatePriceWithCampaign (Gorilla.WebApi)' has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be bound from body. Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to specify bound from route, and 'FromBodyAttribute' for parameters to be bound from body:

    BeverageCapacityCampaign campaign

    BeverageCapacity capacity

Information I could find suggested to check nugets, but all my Nugets are up-to-date.


问:
Nested IF ELSE in a derived column
I have the following logic to store the date in BI_StartDate as below:

If UpdatedDate is not null then BI_StartDate=UpddatedDate

ELSE BI_StartDate takes EntryDate value , if the EntryDate is null
then BI_StartDate=CreatedDate

If the CreatedDate IS NULL then BI_StartDate=GetDATE()

I am using a derived column as seen below:

```<code>ISNULL(UpdatedDateODS)  ? EntryDateODS : (ISNULL(EntryDateODS) ? CreatedDateODS :
(ISNULL(CreatedDateODS) ? GETDATE()  ))
</code>```

I am getting this error:

The expression "ISNULL(UpdatedDateODS)  ? EntryDateODS :
  (ISNULL(EntryDateODS) ? CreatedDateODS :(ISNULL(CreatedDateODS) ?
  GETDATE()  ))" on "Derived Column.Outputs[Derived Column
  Output].Columns[Derived Column 1]" is not valid.

答:
You are looking the first non-null which is a coalesce which doesn't exist in SSIS Data Flow (derived Column).

I'd suggest a very simple script component:

```<code>Row.BIStartDate = Row.UpdateDate ?? Row.EntryDate ?? Row.CreatedDate ?? DateTime.Now;
</code>```

This is the Input Columns Screen:

This is the Inputs and Outputs:

And then you add the above code to Row Processing section:

```<code>public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        /*
         * Add your code here
         */

        Row.BIStartDate = Row.UpdateDate ?? Row.EntryDate ?? Row.CreatedDate ?? DateTime.Now;
}
</code>```

Title: Nested IF ELSE in a derived column

Body:
I have the following logic to store the date in BI_StartDate as below:

If UpdatedDate is not null then BI_StartDate=UpddatedDate

ELSE BI_StartDate takes EntryDate value , if the EntryDate is null
then BI_StartDate=CreatedDate

If the CreatedDate IS NULL then BI_StartDate=GetDATE()

I am using a derived column as seen below:

ISNULL(UpdatedDateODS)  ? EntryDateODS : (ISNULL(EntryDateODS) ? CreatedDateODS :
(ISNULL(CreatedDateODS) ? GETDATE()  ))

I am getting this error:

The expression "ISNULL(UpdatedDateODS)  ? EntryDateODS :
  (ISNULL(EntryDateODS) ? CreatedDateODS :(ISNULL(CreatedDateODS) ?
  GETDATE()  ))" on "Derived Column.Outputs[Derived Column
  Output].Columns[Derived Column 1]" is not valid.

Body:
You are looking the first non-null which is a coalesce which doesn't exist in SSIS Data Flow (derived Column).

I'd suggest a very simple script component:

Row.BIStartDate = Row.UpdateDate ?? Row.EntryDate ?? Row.CreatedDate ?? DateTime.Now;

This is the Input Columns Screen:

This is the Inputs and Outputs:

And then you add the above code to Row Processing section:

public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        /*
         * Add your code here
         */

        Row.BIStartDate = Row.UpdateDate ?? Row.EntryDate ?? Row.CreatedDate ?? DateTime.Now;
}


问:
assign output of execution of PHP script to a variable?
I made a website, I probably didn't do it like I should have, but I was new to PHP at the time. So in order to save me lots of frustration of trying to re-write a script to display photos on my site, I need to run a *.php file, and make the output if it go into a var called "$html". I know it might sound strange, but that's what I need.

From inside index.php, I include photos.php; In photos.php, I need to declare $html with the output of a script called photos_page.php;

For example:
$html = parse_my_script("../photos_page.php");

Thank you

答:
You could also do this if $path returns a value:

```<code>$path = '/path/to/your/script.php';
$html = return include $path;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You could also do this if $path returns a value:

$path = '/path/to/your/script.php';
$html = return include $path;


问:
How to add listener to ul li list?
How to add listener to ul li list, that is in component template?

```<code><ul #list>
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

I have tried:

```<code>@ViewChild("list", { static: false }) list: ElementRef;

ngOnInit() {
   list.addEventListener('keydown', this.onKeyDown);
}

 onKeyDown = (e) => { console.log(e); // event keydown}
</code>```

But it does not work for me.

答:
the angular way of handling events is attaching handlers in the template, like this:</p>

```<code>handleUlClick(e) {console.log(e)}
...
<ul (click)="handleUlClick($event)">
//whatever
</ul>
</code>```

Title: How to add listener to ul li list?

Body:
How to add listener to ul li list, that is in component template?

1

2

3

I have tried:

@ViewChild("list", { static: false }) list: ElementRef;

ngOnInit() {
   list.addEventListener('keydown', this.onKeyDown);
}

 onKeyDown = (e) => { console.log(e); // event keydown}

But it does not work for me.

Body:
the angular way of handling events is attaching handlers in the template, like this:

handleUlClick(e) {console.log(e)}
...
<ul (click)="handleUlClick($event)">
//whatever
</ul>


问:
Laravel: cannot use php artisan migrate with Amazon RDS
I followed every tutorial from Amazon to set up the RDS Database then to set up the VPC, the subnet, and the Security Groups but I still can't connect to the Database using Laravel command.

However, I can connect to the Database using MySQLWorkbench...

This is the error I got when I use the command "php artisan migrate"

Every help will be more than appreciate, thank you Guys.

答:
I'm taking these settings right out of my RDS instance and the Laravel application that uses it.

The first thing you have to do after setting up your RDS database is to allow the database instance to be accessed publicly. This can be done from your AWS console by going to RDS > DB Instances > your database instance > Modify (top left corner). Then scroll down to the Network and Security section and select 'Yes' for public accessibility.

 Public accessibility">

Also double check your Security groups to make sure there is a rule allowing incoming connections to port 3306.

In your Laravel application's .env file and update the database values.
DB_HOST should contain the endpoint specified on the Connectivity and security section of the RDS dashboard. DB_PORT should remain at 3306. Then specify the  database name in DB_DATABASE and the database credentials in DB_USERNAME and DB_PASSWORD.

These are the settings I'm using to connect my Laravel application to an RDS MySQL database.

Body:
I'm taking these settings right out of my RDS instance and the Laravel application that uses it.

The first thing you have to do after setting up your RDS database is to allow the database instance to be accessed publicly. This can be done from your AWS console by going to RDS > DB Instances > your database instance > Modify (top left corner). Then scroll down to the Network and Security section and select 'Yes' for public accessibility.

Also double check your Security groups to make sure there is a rule allowing incoming connections to port 3306.

In your Laravel application's .env file and update the database values.
DB_HOST should contain the endpoint specified on the Connectivity and security section of the RDS dashboard. DB_PORT should remain at 3306. Then specify the  database name in DB_DATABASE and the database credentials in DB_USERNAME and DB_PASSWORD.

These are the settings I'm using to connect my Laravel application to an RDS MySQL database.


问:
How to fix ASP.NET error "The file 'nnn.aspx' has not been pre-compiled, and cannot be requested."?
I have a VS 2005 web site that I publish using "Publish Web Site", and I clear all the three checkboxes. I also have a deployment project that picks up the published files and creates an MSI. I then install the package on a separate test server.

In other words, the whole site is pre-compiled. However, when I go to any .aspx file in a specific subfolder named "Services", I get an HttpException:

System.Web.HttpException: The file '/myapp/Services/mypage.aspx' has not been pre-compiled, and cannot be requested.

If I go to an .aspx file in an other folder, be it the root or other subfolder, it works properly.

The contents of mypage.aspx itself is: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="mypage.aspx.cs" Inherits="Services_mypage" %>"

In the /myapp/bin folder I can see a mypage.aspx.989dc2fb.compiled file. The content of this seems to point to a certain assembly that is also present in the bin folder.

Why is this error occurring? The .compiled file is there, and the assembly is there, and the type in question is present in that assembly (I can see it in Object Browser). Is it something about the name or the content of the .compiled file? Do I have the wrong version somehow? What does the seemingly random number in the .compiled filename mean and is it important?

I also want to mention that this issue appeared suddenly, and I'm not sure what changes there can have been done since it worked properly a few days ago (but to the best of my knowledge, none).

答: It turned out to be a missing (non-web) DLL in the MSI, which I assume was used by the pages giving the error. A quite misleading error message I'd say, as the page was certainly precompiled, but had a missing reference to that DLL.</p>

OwnerDisplayName: jbaekken

ContentLicense: CC BY-SA 2.5


问:
Does the Levenshtein (Edit Distance) algorithm perform faster than O(n*m) in a native graph database?
Would the Levenshtein (Edit Distance) have better time complexity in a native graph database such as Neo4j than the current limit of O(n*m)? If so, why?</p>

答:
Since the implementations of apoc.text.levenshteinDistance and apoc.text.levenshteinSimilarity simply rely on org.apache.commons.text.similarity.LevenshteinDistance to do the calculation, the APOC library does not introduce any complexity improvements.

In any case, such a calculation should just compare 2 strings of text and should not in any way rely on the graphical nature of the DB.

And finally, it has been proven that the complexity cannot be improved (unless the Strong Exponential Time Hypothesis is wrong).


问:
How to calculate the Average size of the last 5 candlesticks in Pine Script
I'm new, and trying to figure this out.

I am trying to write a script to calculate the average size of the last 5 bars (High-Low) for the last five candlesticks of a stock.

I know how to write the logic, but I am still finding my way around Pine Script.

```<code>Calculate Last 5 Bar Sizes
Bar3Range = Bar 3 (High - Low)
Bar4Range = Bar 4 (High - Low)
Bar5Range = Bar 5 (High - Low)
Bar6Range = Bar 6 (High - Low)
Bar7Range = Bar 7 (High - Low)

//  Calculate Average Bar Size
Last5BarAverage = (Bar3Range + Bar4Range + Bar5Range + Bar6Range + Bar7Range) / 5
If Bar 2 is >= 2 * Bar1Range then True
</code>```

答:
```<code>//@version=4
study("")
plot(sma(high - low, 5))
</code>```

Body:
I'm new, and trying to figure this out.

I am trying to write a script to calculate the average size of the last 5 bars (High-Low) for the last five candlesticks of a stock.

I know how to write the logic, but I am still finding my way around Pine Script.

Calculate Last 5 Bar Sizes
Bar3Range = Bar 3 (High - Low)
Bar4Range = Bar 4 (High - Low)
Bar5Range = Bar 5 (High - Low)
Bar6Range = Bar 6 (High - Low)
Bar7Range = Bar 7 (High - Low)

//  Calculate Average Bar Size
Last5BarAverage = (Bar3Range + Bar4Range + Bar5Range + Bar6Range + Bar7Range) / 5
If Bar 2 is >= 2 * Bar1Range then True


问:
Importing model classes from other apps without causing circular reference in Django
I have 3 apps products, sales, purchases. each app has a correspondingly named Model class, Product, Sale, and Purchase.

```<code>products/models.py
class Product(models.Model):
    Name = models.CharField(max_length=32)

sales/models.py
class Sale(models.Model):
    Product = models.ForeignKey('products.Product', on_delete=models.CASCADE)

purchases/models.py
class Purchase(models.Model):
    Product = models.ForeignKey('products.Product', on_delete=models.CASCADE)
</code>```

And I decided to make custom managers for the Model classes so that I can keep all the logic in the model files (by overriding objects attr for each class) when I'm writing the methods in the custom manager I imported Sale model In products.models and Product model in sales.models which creates a circular reference, I was able to get away with it by performing the imports in the methods themselves but I remember reading online that circular imports are sign of bad code writing.

So my question is how can I avoid circular imports in this case and have access to the Product Model in sales.models and Sale in products.models.

答:
You can import a model by name to avoid circular imports. When you need to use the model, import it like this:

from django.apps import apps

ModelName = apps.get_model(app_label='app_name', model_name='ModelName')
```

Body:
I have 3 apps products, sales, purchases. each app has a correspondingly named Model class, Product, Sale, and Purchase.

products/models.py
class Product(models.Model):
    Name = models.CharField(max_length=32)

sales/models.py
class Sale(models.Model):
    Product = models.ForeignKey('products.Product', on_delete=models.CASCADE)

purchases/models.py
class Purchase(models.Model):
    Product = models.ForeignKey('products.Product', on_delete=models.CASCADE)

And I decided to make custom managers for the Model classes so that I can keep all the logic in the model files (by overriding objects attr for each class) when I'm writing the methods in the custom manager I imported Sale model In products.models and Product model in sales.models which creates a circular reference, I was able to get away with it by performing the imports in the methods themselves but I remember reading online that circular imports are sign of bad code writing.

So my question is how can I avoid circular imports in this case and have access to the Product Model in sales.models and Sale in products.models.


问:
How to check if a list is inside another list in python?
How would you check if the inside of the list is also a list?

For example:

[[2,3]]

This is a list inside of a list. For my code, I need to check if the list1 index is a list, if it is, add it to a new list as individual indexes instead of a list.

```<code>list1 = [1, [[2, 3]], [4], 5]
list2 = []
for i in range(0, len(list1)):
    if (isinstance(list1[i],list)):
        list2.extend(list1[i])
    else:
        list2.append(list1[i])

print(list2)
</code>```

This prints out [1, [2,3], 4, 5]

This shows that it does add the 4, since 4 was originally as a list.
But it doesn't add the 2,3 to the list.

This is what I want it to print out:

[1,2,3,4,5]

This is what I've tried to check if there is a list inside a list but it doesn't work:

```<code>elif(isinstance(list1[i],list) and isinstance(list1[i][0],list)):
        list2.extend(list1[i][0])
</code>```

答:
Use a recursive function to flatten the list:</p>

```<code>def flatten(lst):
    assert isinstance(lst, list)
    result = []
    for i in lst:
        if isinstance(i, list):
            result.extend(flatten(i))
        else:
            result.append(i)
    return result
</code>```

Body:
How would you check if the inside of the list is also a list?

For example:

[[2,3]]

This is a list inside of a list. For my code, I need to check if the list1 index is a list, if it is, add it to a new list as individual indexes instead of a list.

list1 = [1, [[2, 3]], [4], 5]
list2 = []
for i in range(0, len(list1)):
    if (isinstance(list1[i],list)):
        list2.extend(list1[i])
    else:
        list2.append(list1[i])

print(list2)

This prints out [1, [2,3], 4, 5]

This shows that it does add the 4, since 4 was originally as a list.
But it doesn't add the 2,3 to the list.

This is what I want it to print out:

[1,2,3,4,5]

This is what I've tried to check if there is a list inside a list but it doesn't work:

elif(isinstance(list1[i],list) and isinstance(list1[i][0],list)):
        list2.extend(list1[i][0])

Body:
Use a recursive function to flatten the list:

def flatten(lst):
    assert isinstance(lst, list)
    result = []
    for i in lst:
        if isinstance(i, list):
            result.extend(flatten(i))
        else:
            result.append(i)
    return result


问:
Align the green button at the end of each div in css
I have this "buy" (comprar) button that I'd like to put in the end of div so they would be align with each other "buy" button.

eg:

```<code>button button button
</code>```

not:

```<code>button            button
       button
</code>```

#content01{
 min-height:500px;
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
}

.produto{
  display: inline-block;
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 2px solid #F6F6F6;
  width: 246px;
  text-align: center;
  vertical-align: top;
  padding-bottom:10px;
}

.comprar_button {
  background: green;
  padding:10px;
  color: #fff;
  text-align:center;
  font-weight:bold;
  vertical-align:bottom;
  align-self: flex-end;
}

.comprar_button a{
  color: #fff!important;
}

.comprar_button img{
  width: 15px;
  height: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content01">

  <div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text text some text some text some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text Some text Some text Some text Some text Some text Some text Some text Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

</div></code>```

https://jsfiddle.net/j72u8Lx5/

how can I align the "comprar" button?

答:
Is this what you want? It used position absolute.

https://jsfiddle.net/usv7jLhm/

```<code>.produto{
    position: relative;
    display: inline-block;
    margin-top: 20px;
    margin-right: 20px;
    margin-bottom: 20px;
    border: 2px solid #F6F6F6;
    width: 246px;
    text-align: center;
    vertical-align: top;
    padding-bottom:10px;
}

.comprar_button {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translate(-50%, -50%);
    background: green;
    padding:10px;
    color: #fff;
    text-align:center;
    font-weight:bold;
    vertical-align:bottom;
    align-self: flex-end;
}
</code>```

Body:
I have this "buy" (comprar) button that I'd like to put in the end of div so they would be align with each other "buy" button.

eg:

button button button

not:

button            button
       button

#content01{
 min-height:500px;
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
}

.produto{
  display: inline-block;
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 2px solid #F6F6F6;
  width: 246px;
  text-align: center;
  vertical-align: top;
  padding-bottom:10px;
}

.comprar_button {
  background: green;
  padding:10px;
  color: #fff;
  text-align:center;
  font-weight:bold;
  vertical-align:bottom;
  align-self: flex-end;
}

.comprar_button a{
  color: #fff!important;
}

.comprar_button img{
  width: 15px;
  height: 15px;
}

Some text

$ 20.00

COMPRAR

Some text text some text some text some text

$ 20.00

COMPRAR

Some text

$ 20.00

COMPRAR

Some text Some text Some text Some text Some text Some text Some text Some text Some text

$ 20.00

COMPRAR

https://jsfiddle.net/j72u8Lx5/

how can I align the "comprar" button?

Body:
Is this what you want? It used position absolute.

https://jsfiddle.net/usv7jLhm/

.produto{
    position: relative;
    display: inline-block;
    margin-top: 20px;
    margin-right: 20px;
    margin-bottom: 20px;
    border: 2px solid #F6F6F6;
    width: 246px;
    text-align: center;
    vertical-align: top;
    padding-bottom:10px;
}

.comprar_button {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translate(-50%, -50%);
    background: green;
    padding:10px;
    color: #fff;
    text-align:center;
    font-weight:bold;
    vertical-align:bottom;
    align-self: flex-end;
}


问:
escaping special character in groovy
I want to run my command in background.And I am trying this in jenkins pipeline
This is my command

sh "./node_modules/.bin/selenium-standalone start  \&"

But when I run this command & gets single quote because of which the command fails.
OUTPUT :  ./node_modules/.bin/selenium-standalone start '&'

Can anyone suggest how I should escape the & in groovy so I just get & without single quote.

答: & is no special character to Groovy.  It is for the shell.  So if you dont want to start this command in the background but want to pass & as an argument to your script there, you have to use \\& inside "-strings. And if you want to start the script in the background, then just use &.

Title: escaping special character in groovy


问:
Setting LinearLayout Background Resource scale type programmatically
I have a linear layout that when i want programmatically to enter a TileXY background image to it i can do it that way:

```<code>ImageButton.SetImageBitmap(BitmapFactory.DecodeFile(Button1ImageURI));
Bitmap temp = BitmapFactory.DecodeFile(Button1ImageURI);
BitmapDrawable bitmapDrawable = new BitmapDrawable(Resources, temp);
bitmapDrawable.SetTileModeXY(Shader.TileMode.Repeat, Shader.TileMode.Repeat);
MainLinearLayout.Background = bitmapDrawable;
</code>```

I'm not sure how i can do the same but this time i want the bitmapDrawable to ScaleType.FitCenter in the LinearLayout.

I'm not sure how i can do that, if i don't put a SetTileModeXY in the BitmapDrawable, Background in MainLinearLayout is scaled with FitXY,
but i want to be scaled in FitCenter

答: Why you want to set image as background on the LinearLayout, when you can create ImageView as a child of the LinearLayout with width and height that match the parent(LinearLayout), and use the benefits of the ImageView. Setting the image as source and use the ScaleType?

Body:
I have a linear layout that when i want programmatically to enter a TileXY background image to it i can do it that way:

ImageButton.SetImageBitmap(BitmapFactory.DecodeFile(Button1ImageURI));
Bitmap temp = BitmapFactory.DecodeFile(Button1ImageURI);
BitmapDrawable bitmapDrawable = new BitmapDrawable(Resources, temp);
bitmapDrawable.SetTileModeXY(Shader.TileMode.Repeat, Shader.TileMode.Repeat);
MainLinearLayout.Background = bitmapDrawable;

I'm not sure how i can do the same but this time i want the bitmapDrawable to ScaleType.FitCenter in the LinearLayout.

I'm not sure how i can do that, if i don't put a SetTileModeXY in the BitmapDrawable, Background in MainLinearLayout is scaled with FitXY,
but i want to be scaled in FitCenter


问:
Intellij "java: package org.junit does not exist"
When i try to run my test i get the following Errors:
I looked up on google and found somthing on google but this didn't help.

```<code>Error:(3, 24) java: package org.junit does not exist
Error:(3, 1) java: static import only from classes and interfaces
Error:(5, 17) java: package org.junit does not exist
Error:(6, 17) java: package org.junit does not exist
Error:(12, 10) java: cannot find symbol
    symbol:   class Before
    location: class edu.kit.ipd.swt1.SimpleEditMeTest
Error:(17, 10) java: cannot find symbol
    symbol:   class Test
    location: class edu.kit.ipd.swt1.SimpleEditMeTest
[...]
</code>```

My test code:

```<code>package edu.kit.ipd.swt1;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;

public class SimpleEditMeTest {
private EditMe editMe;
@Before
public void setUp() throws Exception {
    editMe = new EditMe();
}
@Test
public void test() {
    assertNotNull(editMe.getFoo());
}
}
</code>```

Screenshot of the whole project

Run configurations

Dependencies i.stack.imgur. com/OiQWU.png (Can't post more than 2 links)

答:
The solution to this is to add junit library as dependency to the project. This can be done by adding junit to global library and then hovering over the error(junit word) and right clicking to add junit to class path.
alt+shift+ctrl+s to get project settings in the same either add junit to global library or to project section as mentioned by rob in his answer.

Body:
When i try to run my test i get the following Errors:
I looked up on google and found somthing on google but this didn't help.

Error:(3, 24) java: package org.junit does not exist
Error:(3, 1) java: static import only from classes and interfaces
Error:(5, 17) java: package org.junit does not exist
Error:(6, 17) java: package org.junit does not exist
Error:(12, 10) java: cannot find symbol
    symbol:   class Before
    location: class edu.kit.ipd.swt1.SimpleEditMeTest
Error:(17, 10) java: cannot find symbol
    symbol:   class Test
    location: class edu.kit.ipd.swt1.SimpleEditMeTest
[...]

My test code:

package edu.kit.ipd.swt1;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;

public class SimpleEditMeTest {
private EditMe editMe;
@Before
public void setUp() throws Exception {
    editMe = new EditMe();
}
@Test
public void test() {
    assertNotNull(editMe.getFoo());
}
}

Screenshot of the whole project

Run configurations

Dependencies i.stack.imgur. com/OiQWU.png (Can't post more than 2 links)


问:
XDMP-FORESTERR: Error in checkpoint of forest App-Services: SVC-FILWRT
When trying to open query console getting the below error as seen in the images below:

答:
It reads No space left on device. Make room, and restart affected cluster, hosts, or forests to recover.

HTH!


问:
iterate an array of object and separe comparing dates in es6
I need to make a function to iterate an array of x objects then compare the date inside the objects and separate in different arrays so I can show separately in the HTML, this is my object:

[{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141},{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]
```

<p>I want something like this:</p>

```obj1 = [{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141}]

obj2 = [{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]
```

<p>my code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// global variables
json = [{
  "id": 1,
  "date": "2020-02-06",
  "value": 131
}, {
  "id": 2,
  "date": "2020-02-06",
  "value": 135
}, {
  "id": 3,
  "date": "2020-02-06",
  "value": 141
}, {
  "id": 4,
  "date": "2020-02-05",
  "value": 151
}, {
  "id": 6,
  "date": "2020-02-05",
  "value": 155
}];
obj1 = [];
obj2 = [];

for (const x of json) {
  if (x.date != x.date) {
    obj1.push(x)
  } else {
    obj2.push(x)
  }
}

console.log(obj1);
console.log(obj2);</code>```

in result always the items push into the obj1..

any help is welcome.

答:
You can use reduce to build an object that maps each unique date to its respective data items, having, basically, a group by date:

const data = [{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141},{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}];

const groupedData = data.reduce((acc, curr) => ({
  ...acc,
  [curr.date]: [...(acc[curr.date] || []), curr]
}), {});

console.log(groupedData);```

We also use above the spread syntax and computed property names to make the code shorter.

Body:
I need to make a function to iterate an array of x objects then compare the date inside the objects and separate in different arrays so I can show separately in the HTML, this is my object:

[{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141},{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]

I want something like this:

obj1 = [{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141}]

obj2 = [{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]

my code:

// global variables
json = [{
  "id": 1,
  "date": "2020-02-06",
  "value": 131
}, {
  "id": 2,
  "date": "2020-02-06",
  "value": 135
}, {
  "id": 3,
  "date": "2020-02-06",
  "value": 141
}, {
  "id": 4,
  "date": "2020-02-05",
  "value": 151
}, {
  "id": 6,
  "date": "2020-02-05",
  "value": 155
}];
obj1 = [];
obj2 = [];

for (const x of json) {
  if (x.date != x.date) {
    obj1.push(x)
  } else {
    obj2.push(x)
  }
}

console.log(obj1);
console.log(obj2);

in result always the items push into the obj1..

any help is welcome.

Body:
You can use reduce to build an object that maps each unique date to its respective data items, having, basically, a group by date:

const data = [{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141},{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}];

const groupedData = data.reduce((acc, curr) => ({
  ...acc,
  [curr.date]: [...(acc[curr.date] || []), curr]
}), {});

console.log(groupedData);

We also use above the spread syntax and computed property names to make the code shorter.


问:
Unable to find image 'jmeter:latest' locally when the image is already available
I am trying to run JMeter in a docker container. To achieve this I initially pulled this JMeter image from the docker hub. Then when I do

docker image ls

It shows the pulled image

But when I execute the below command and try to run the container It gives me the below error:

```<code>export volume_path=/Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_resource && export jmeter_path=/jmeter && docker run --rm --name jmeterContainer --memory="512m" --cpus=2 --volume ${volume_path}:${jmeter_path} -e JAVA_OPTS="-Xms512 -Xmx512" jmeter -t ${jmeter_path}/factorial.jmx -l ${jmeter_path}/jmeter_results.jtl -q ${jmeter_path}/user.properties  egaillardon/jmeter:latest
</code>```

Unable to find image 'jmeter:latest' locally docker: Error response
  from daemon: pull access denied for jmeter, repository does not exist
  or may require 'docker login': denied: requested access to the
  resource is denied. See 'docker run --help'.

What am I doing wrong?

答:
What @Marc mentioned was the problem but since a solution was not mentioned I'm posting how I solved it for future reference. My problem was that I have put the image tag in the wrong place. The working command is as shown below:</p>

```<code>export volume_path=/Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_resource && export jmeter_path=/jmeter && docker run --rm --name jmeterContainer --memory='512m' --cpus=2 -e JAVA_OPTS="-Xms512 -Xmx512" --volume ${volume_path}:${jmeter_path} egaillardon/jmeter --nongui -t factorial.jmx -l jmeter_results.jtl -q user.properties
</code>```

Body:
I am trying to run JMeter in a docker container. To achieve this I initially pulled this JMeter image from the docker hub. Then when I do

docker image ls

It shows the pulled image

But when I execute the below command and try to run the container It gives me the below error:

export volume_path=/Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_resource && export jmeter_path=/jmeter && docker run --rm --name jmeterContainer --memory="512m" --cpus=2 --volume ${volume_path}:${jmeter_path} -e JAVA_OPTS="-Xms512 -Xmx512" jmeter -t ${jmeter_path}/factorial.jmx -l ${jmeter_path}/jmeter_results.jtl -q ${jmeter_path}/user.properties  egaillardon/jmeter:latest

Unable to find image 'jmeter:latest' locally docker: Error response
  from daemon: pull access denied for jmeter, repository does not exist
  or may require 'docker login': denied: requested access to the
  resource is denied. See 'docker run --help'.

What am I doing wrong?

Body:
What @Marc mentioned was the problem but since a solution was not mentioned I'm posting how I solved it for future reference. My problem was that I have put the image tag in the wrong place. The working command is as shown below:

export volume_path=/Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_resource && export jmeter_path=/jmeter && docker run --rm --name jmeterContainer --memory='512m' --cpus=2 -e JAVA_OPTS="-Xms512 -Xmx512" --volume ${volume_path}:${jmeter_path} egaillardon/jmeter --nongui -t factorial.jmx -l jmeter_results.jtl -q user.properties


问:
Setting the minimumValue (earliest date) in asp.net causes The MaximumValue cannot be less than the MinimumValue
I am attempting to use the range validator to set a minimum date using minimumValue as I do not need a maximum value and the error comes up saying System.Web.HttpException: The MaximumValue  cannot be less than the MinimumValue 2002/09/15 of . Does anyone have any ideas on how I can remove this error?</p>

```<code>Starting date
<asp:TextBox  ID = "textbox1" runat="server"></asp:TextBox>
<asp:RangeValidator runat="server"  MinimumValue ="2002/09/15" ControlToValidate = "textbox1"  ErrorMessage="after 14 September 2002"></asp:RangeValidator>
</code>```

答: Specify type="date" in your range validator

Body:
I am attempting to use the range validator to set a minimum date using minimumValue as I do not need a maximum value and the error comes up saying System.Web.HttpException: The MaximumValue  cannot be less than the MinimumValue 2002/09/15 of . Does anyone have any ideas on how I can remove this error?

Starting date
<asp:TextBox  ID = "textbox1" runat="server"></asp:TextBox>
<asp:RangeValidator runat="server"  MinimumValue ="2002/09/15" ControlToValidate = "textbox1"  ErrorMessage="after 14 September 2002"></asp:RangeValidator>


问:
tabulator .tabulator-row-even overridden but .tabulator-row-odd is not
i'm trying to set ".tabulator-row-even" and ".tabulator-row-odd" colors on a tabulator table.

".tabulator-row-even" is being overridden by tabulator.scss

".tabulator-row-odd" is not overridden, I can change this color.

my style.css has these lines:

```<code>.tabulator-row-odd {
    background-color: #553333;
}
.tabulator-row-even {
    background-color: #335533;
}
</code>```

computed properties on Safari:

```<code>#553333.tabulator-row-odd   style.css:23
#fff.tabulator-row  tabulator.scss:1001
#fff.tabulator .…lator-table    tabulator.scss:1001

#efefef.tabulator-r…or-row-even tabulator.scss:1001
#335533.tabulator-row-even  style.css:26
#fff.tabulator-row  tabulator.scss:1001
</code>```

答:
Did you try ?</p>

```<code>.tabulator-row-odd {
    background-color: #553333 !important;
}
.tabulator-row-even {
    background-color: #335533 !important;
}
</code>```

Body:
i'm trying to set ".tabulator-row-even" and ".tabulator-row-odd" colors on a tabulator table.

".tabulator-row-even" is being overridden by tabulator.scss

".tabulator-row-odd" is not overridden, I can change this color.

my style.css has these lines:

.tabulator-row-odd {
    background-color: #553333;
}
.tabulator-row-even {
    background-color: #335533;
}

computed properties on Safari:

#553333.tabulator-row-odd   style.css:23
#fff.tabulator-row  tabulator.scss:1001
#fff.tabulator .…lator-table    tabulator.scss:1001

#efefef.tabulator-r…or-row-even tabulator.scss:1001
#335533.tabulator-row-even  style.css:26
#fff.tabulator-row  tabulator.scss:1001

Body:
Did you try ?

.tabulator-row-odd {
    background-color: #553333 !important;
}
.tabulator-row-even {
    background-color: #335533 !important;
}


问:
Analyze Table Optimization in Databricks for Views
After doing Analyze Table Compute Statistics performance of my joins got better in Databricks Delta table.
As in Spark sql Analyze view is not supported. I would like to know if the query Optimizer will optimize the query if I have a view created on the same table on which I have used Analyze table compute statistics. </p>

答:
There is no Analyze View that I know of.

From the manuals: Define a logical view on one or more tables or
  views.

It is logical. But the View will be expanded, merged, compiled, materialized and the sum total of the SQL statements will be subject to optimization. E.g. a JOIN of a View with another View or Table will lead to optimization of the base level components - the Tables along with the operations e.g. a JOIN, sub-select.

So, the Table stats are important, but also the intended set of operations for the Optimizer.

So, the answer to your question is Yes.


问:
Permission denied when saving an image in android
I can't save an image file, even after I request the permission.
I added the permission to the manifest file like this:

```<code>permission.WRITE_EXTERNAL_STORAGE
</code>```

But I keep seeing this error:

Permission denied

Here is the relevant code:

```<code>@SuppressLint("MissingPermission")
private void saveImage() {
    if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        showLoading("Saving...");
        File file = new File(Environment.getExternalStorageDirectory()
                + File.separator + ""
                + System.currentTimeMillis() + ".png");
        try {
            file.createNewFile();

            SaveSettings saveSettings = new SaveSettings.Builder()
                    .setClearViewsEnabled(true)
                    .setTransparencyEnabled(true)
                    .build();

            mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
                @Override
                public void onSuccess(@NonNull String imagePath) {
                    hideLoading();
                    showSnackbar("Image Saved Successfully");
                    mSaveImageUri = Uri.fromFile(new File(imagePath));
                    mPhotoEditorView.getSource().setImageURI(mSaveImageUri);
                }

                @Override
                public void onFailure(@NonNull Exception exception) {
                    hideLoading();
                    showSnackbar("Failed to save Image");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            hideLoading();
            showSnackbar(e.getMessage());
        }
    }
}
</code>```

And here is the error log:

```<code>D/ViewRootImpl@faa5b66[EditImageActivity]: setView = com.android.internal.policy.DecorView@63d69b7 TM=true MM=false
W/System.err: java.io.IOException: Permission denied
W/System.err:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
</code>```

答:
Check if it is consecuence of how the permissions in Android Q has changed:

https://developer.android.com/training/data-storage/files/external-scoped

Body:
I can't save an image file, even after I request the permission.
I added the permission to the manifest file like this:

permission.WRITE_EXTERNAL_STORAGE

But I keep seeing this error:

Permission denied

Here is the relevant code:

@SuppressLint("MissingPermission")
private void saveImage() {
    if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        showLoading("Saving...");
        File file = new File(Environment.getExternalStorageDirectory()
                + File.separator + ""
                + System.currentTimeMillis() + ".png");
        try {
            file.createNewFile();

            SaveSettings saveSettings = new SaveSettings.Builder()
                    .setClearViewsEnabled(true)
                    .setTransparencyEnabled(true)
                    .build();

            mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
                @Override
                public void onSuccess(@NonNull String imagePath) {
                    hideLoading();
                    showSnackbar("Image Saved Successfully");
                    mSaveImageUri = Uri.fromFile(new File(imagePath));
                    mPhotoEditorView.getSource().setImageURI(mSaveImageUri);
                }

                @Override
                public void onFailure(@NonNull Exception exception) {
                    hideLoading();
                    showSnackbar("Failed to save Image");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            hideLoading();
            showSnackbar(e.getMessage());
        }
    }
}

And here is the error log:

D/ViewRootImpl@faa5b66[EditImageActivity]: setView = com.android.internal.policy.DecorView@63d69b7 TM=true MM=false
W/System.err: java.io.IOException: Permission denied
W/System.err:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)


问:
Compromising Mongoose with REST API
I need to ask - I've got a /users endpoint and I want to add tasks to user, just like that: /users/:username/tasks. Should I create another model and route? I don't know how to add an ID to an array in Mongoose model and add a slug with mongoose-url-slugs.

I want it to be RESTful as much as I can. So this: /users/:username/tasks or /tasks/:username? If first, I need to know how to add ID to tasks in that model:

import mongoose from 'mongoose'

const User = mongoose.Schema({
    username: String,
    email: String,
    password: String,
    tasks: Array
}, {
    timestamps: true
})

export default mongoose.model('User', User)
```

答:
In my opinion, I believe you should create a new model tasks.

You can use a reference to tasks model like that:

```<code>tasks: [{ type: Schema.Types.ObjectId, ref: 'tasks' }]
</code>```

https://mongoosejs.com/docs/populate.html

This route's better because you're adding a task to the user and not a user to the task
/users/:username/tasks

And to link then you can use mongoose's virtual: https://mongoosejs.com/docs/tutorials/virtuals.html

Ex: https://github.com/Automattic/mongoose/issues/6608

```<code>UserSchema.virtual('tasks', {
  lookup: (doc) => {
    return {
      from: 'tasks',
      let: { userId: '$_id' },
      pipeline: [{
        $match: {
          $expr: {
            $and: [{
              $eq: ['$refId', '$$userId']
            }]
          }
        }
      }, {
        $project: { name: 1, createdAt: 1 }
      }
      ],
      as: 'tasks',
    }
  }
});
</code>```

```<code>userModel.find().populate('tasks').lean(true);
</code>```

Title: Compromising Mongoose with REST API

Body:
In my opinion, I believe you should create a new model tasks.

You can use a reference to tasks model like that:

tasks: [{ type: Schema.Types.ObjectId, ref: 'tasks' }]

https://mongoosejs.com/docs/populate.html

This route's better because you're adding a task to the user and not a user to the task
/users/:username/tasks

And to link then you can use mongoose's virtual: https://mongoosejs.com/docs/tutorials/virtuals.html

Ex: https://github.com/Automattic/mongoose/issues/6608

UserSchema.virtual('tasks', {
  lookup: (doc) => {
    return {
      from: 'tasks',
      let: { userId: '$_id' },
      pipeline: [{
        $match: {
          $expr: {
            $and: [{
              $eq: ['$refId', '$$userId']
            }]
          }
        }
      }, {
        $project: { name: 1, createdAt: 1 }
      }
      ],
      as: 'tasks',
    }
  }
});

userModel.find().populate('tasks').lean(true);


问:
Setting a random number of characters to an array
I want to make an array of 16 characters with the next conditions:
Between 1 to 3 characters must be a W.
2 characters must be X
And the rest need to be O.
How can I do it?</p>

答:
I think you are looking for a array which can be randomly initialized based on the conditions you mentioned. The random number generator which is present in the java.util.Random package is quite useful in such cases. Below is the code which can be used.

```<code>    Random ran = new Random();
    int countW = ran.nextInt(3);
    int insertCountW = 0;
    int insertCountX = 0;
    char[] c = new char[16];
    while(insertCountW != countW){
        int pos = ran.nextInt(16);
        c[pos] = 'W';
        insertCountW++;
    }
    while(insertCountX != 2){
        int pos = ran.nextInt(16);
       if(c[pos] == 0){
           c[pos] = 'X';
           insertCountX++;
       }

    }
    for (int i = 0; i < 16; i++) {
        if(c[i] == 0){
            c[i] = 'O';
        }
    }
</code>```

The following document from the Oracle document might be useful https://docs.oracle.com/javase/8/docs/api/java/util/Random.html to know more about the package. Hope this helps.

Body:
I think you are looking for a array which can be randomly initialized based on the conditions you mentioned. The random number generator which is present in the java.util.Random package is quite useful in such cases. Below is the code which can be used.

    Random ran = new Random();
    int countW = ran.nextInt(3);
    int insertCountW = 0;
    int insertCountX = 0;
    char[] c = new char[16];
    while(insertCountW != countW){
        int pos = ran.nextInt(16);
        c[pos] = 'W';
        insertCountW++;
    }
    while(insertCountX != 2){
        int pos = ran.nextInt(16);
       if(c[pos] == 0){
           c[pos] = 'X';
           insertCountX++;
       }

    }
    for (int i = 0; i < 16; i++) {
        if(c[i] == 0){
            c[i] = 'O';
        }
    }

The following document from the Oracle document might be useful https://docs.oracle.com/javase/8/docs/api/java/util/Random.html to know more about the package. Hope this helps.


问:
Implement Tree with checkboxes and drag drop
Im trying to implement Tree view in Vue with checkboxes and also with drag & drop. But I do not know where to start.

I implemented checkboxes but I do not know how to add support when parent is selected to select all children, and also when select all children to select parent ?

Also Im having issue with Drag and Drop, I tried ussing vue-draggable but I do not know how to implement it

Im trying to implement, something like this:

https://ej2.syncfusion.com/vue/documentation/treeview/check-box/

Here is my sandbox, what I have managed to implement:

https://codesandbox.io/s/immutable-cookies-8lxxf

答:
I had a go at doing this with Vue using a recursive component which can be found below. It shows how you can select all the children from the parent and how you could use vue-draggable (though you can only drag on the same tier). It should be a decent starting point, it needs a few tweaks.

EDIT:

To accommodate for drag and drop on multiple levels, I've edited the code so that the draggables are in the same group. I've tested it quickly and the concept works but it still needs some tweaks. Support for nested vue-draggable can be found here, I also made a fork of the JSFiddle on GitHub that works so you can see how they implemented nesting

let tree = {
  draggableOptions: {group: 'share'},
  label: 'root',
  selected: false,
  nodes: [
    {
      label: 'item1',
      selected: false,
      nodes: [
        {
          label: 'item1.1',
          selected: false
        },
        {
          label: 'item1.2',
          selected: false,
          nodes: [
            {
              label: 'item1.2.1',
              selected: false
            }
          ]
        }
      ]
    },
    {
      label: 'item2',
      selected: false
    }
  ]
}

Vue.component('tree-menu', {
  template: '#tree-menu',
  props: [ 'nodes', 'label', 'depth', 'selected' ],
  data() {
     return {
       showChildren: false
     }
  },
  computed: {
    iconClasses() {
      return {
        'fa-plus-square-o': !this.showChildren,
        'fa-minus-square-o': this.showChildren
      }
    },
    labelClasses() {
      return { 'has-children': this.nodes }
    },
    indent() {
      return { transform: `translate(${this.depth * 50}px)` }
    }
  },
  methods: {
    toggleChildren() {
       this.showChildren = !this.showChildren;

    },
    tickChildren(ev) {
      this.selected = !this.selected;
      this.tickRecursive(this);
    },
    tickRecursive(node) {
       if(node.nodes && node.nodes.length)
          node.nodes.forEach(x => {
            x.selected = this.selected;
            this.tickRecursive(x);
          });
    }
  }
});

new Vue({
  el: '#app',
  data: {
    tree
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: "Open Sans", sans-serif;
  font-size: 18px;
  font-weight: 300;
  line-height: 1em;
}

.container {
  padding-left: 5rem;
  padding-right: 5rem;
  margin: 0 auto;
}

.tree-menu {
  .label-wrapper {
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid #ccc;
    .has-children {
      cursor: pointer;
    }
  }
}</code>```

Implement Tree with checkboxes and drag drop
(Using Vue, Recursive Component, Vue Draggable)
For StackOverflow Question

  <tree-menu
             :nodes="tree.nodes"
             :depth="0"
             :label="tree.label"
             :selected="tree.selected"
             ></tree-menu>

```

Body:
I had a go at doing this with Vue using a recursive component which can be found below. It shows how you can select all the children from the parent and how you could use vue-draggable (though you can only drag on the same tier). It should be a decent starting point, it needs a few tweaks.

EDIT:

To accommodate for drag and drop on multiple levels, I've edited the code so that the draggables are in the same group. I've tested it quickly and the concept works but it still needs some tweaks. Support for nested vue-draggable can be found here, I also made a fork of the JSFiddle on GitHub that works so you can see how they implemented nesting

let tree = {
  draggableOptions: {group: 'share'},
  label: 'root',
  selected: false,
  nodes: [
    {
      label: 'item1',
      selected: false,
      nodes: [
        {
          label: 'item1.1',
          selected: false
        },
        {
          label: 'item1.2',
          selected: false,
          nodes: [
            {
              label: 'item1.2.1',
              selected: false
            }
          ]
        }
      ]
    },
    {
      label: 'item2',
      selected: false
    }
  ]
}

Vue.component('tree-menu', {
  template: '#tree-menu',
  props: [ 'nodes', 'label', 'depth', 'selected' ],
  data() {
     return {
       showChildren: false
     }
  },
  computed: {
    iconClasses() {
      return {
        'fa-plus-square-o': !this.showChildren,
        'fa-minus-square-o': this.showChildren
      }
    },
    labelClasses() {
      return { 'has-children': this.nodes }
    },
    indent() {
      return { transform: `translate(${this.depth * 50}px)` }
    }
  },
  methods: {
    toggleChildren() {
       this.showChildren = !this.showChildren;

    },
    tickChildren(ev) {
      this.selected = !this.selected;
      this.tickRecursive(this);
    },
    tickRecursive(node) {
       if(node.nodes && node.nodes.length)
          node.nodes.forEach(x => {
            x.selected = this.selected;
            this.tickRecursive(x);
          });
    }
  }
});

new Vue({
  el: '#app',
  data: {
    tree
  }
})

body {
  font-family: "Open Sans", sans-serif;
  font-size: 18px;
  font-weight: 300;
  line-height: 1em;
}

.container {
  padding-left: 5rem;
  padding-right: 5rem;
  margin: 0 auto;
}

.tree-menu {
  .label-wrapper {
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid #ccc;
    .has-children {
      cursor: pointer;
    }
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js">
</script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.7.0/Sortable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.16.0/vuedraggable.min.js"></script>

<div class="container">
  <h4>Implement Tree with checkboxes and drag drop<br/><small>(Using Vue, Recursive Component, Vue Draggable)</small><br /><small><a href="https://stackoverflow.com/questions/60260675/implement-tree-with-checkboxes-and-drag-drop" target="_blank">For StackOverflow Question</a></small></h4>
  <div id="app">

  <tree-menu
             :nodes="tree.nodes"
             :depth="0"
             :label="tree.label"
             :selected="tree.selected"
             ></tree-menu>

  </div>

</div>

<script type="text/x-template" id="tree-menu">

  <div class="tree-menu">
    <div class="label-wrapper">
      <div :style="indent" :class="labelClasses" @click.stop="toggleChildren">
        <i v-if="nodes" class="fa" :class="iconClasses"></i>
        <input type="checkbox" :checked="selected" @input="tickChildren" @click.stop />
        {{label}}
      </div>
    </div>

        <draggable v-model="nodes" :options="{group:{ name:'g1'}}">
    <tree-menu
      v-if="showChildren"
      v-for="node in nodes"
      :nodes="node.nodes"
      :label="node.label"
      :depth="depth + 1"
      :selected="node.selected"
      :key="node"
    >
    </tree-menu>
            </draggable>

  </div>

</script>


问:
How to manage response data of steps implemented in Gherkin using QAF API?
Looking for ways to carry over data from previous step to subsequent using QAF. Is there an option for such behavior?</p>

答:
In qaf your step can return a value. If you step is returning a value and you want to use it in another step you can use store into 'var-name' step after step that returning value. For example

```<code>When create new user using "{'name':'user1','password':'user123'}"
And store into 'newUser'
Then system should have user '${newUser}'
</code>```

Your step may look like below:

```<code>@QAFTestStep(description="create new user using {userInfo}")
public User createUser(User user){
    //steps to createUser
    long id = userDao.createUser(user);
    user.setId(id);
    return user;
}
@QAFTestStep(description="system should have user {userInfo}")
public void createUser(User user){
    //steps to createUser
    User user = userDao.getUser(user.getId);
    Validator.assertThat("get user from system",user, Matchers.notNull());
}
</code>```

Below is example of web services test:

```<code>Given user requests 'myservice.getuser.reqcall'
And say 'userID' is value at jsonpath '$.id'
Then ...
</code>```

Body:
In qaf your step can return a value. If you step is returning a value and you want to use it in another step you can use store into 'var-name' step after step that returning value. For example

When create new user using "{'name':'user1','password':'user123'}"
And store into 'newUser'
Then system should have user '${newUser}'

Your step may look like below:

@QAFTestStep(description="create new user using {userInfo}")
public User createUser(User user){
    //steps to createUser
    long id = userDao.createUser(user);
    user.setId(id);
    return user;
}
@QAFTestStep(description="system should have user {userInfo}")
public void createUser(User user){
    //steps to createUser
    User user = userDao.getUser(user.getId);
    Validator.assertThat("get user from system",user, Matchers.notNull());
}

Below is example of web services test:

Given user requests 'myservice.getuser.reqcall'
And say 'userID' is value at jsonpath '$.id'
Then ...


问:
Why would the output of "last" show history less than the time I've had my laptop?
If I execute "last" in Terminal I see the following output:

```<code>Yonda     ttys000                   Wed Feb 19 18:03   still logged in
Yonda     console                   Tue Feb 18 23:21   still logged in
reboot    ~                         Tue Feb 18 23:21
shutdown  ~                         Tue Feb 18 23:18
Yonda     console                   Sun Feb 16 16:26 - 23:18 (2+06:52)
reboot    ~                         Sun Feb 16 16:26
shutdown  ~                         Sun Feb 16 16:25
root      console                   Sun Feb 16 16:24 - shutdown  (00:01)
Yonda     console                   Sun Feb 16 16:13 - 16:24  (00:10)
reboot    ~                         Sun Feb 16 16:13
shutdown  ~                         Sun Feb 16 16:12
Yonda     ttys001                   Sun Feb  9 16:09 - 16:09  (00:00)
Yonda     ttys001                   Sun Feb  9 15:56 - 15:56  (00:00)
Yonda     ttys001                   Thu Feb  6 11:01 - 11:01  (00:00)
Yonda     console                   Sat Feb  1 17:59 - 16:12 (14+22:13)
reboot    ~                         Sat Feb  1 17:58
</code>```

It seems strange that this only goes back to Feb 1, when I've been using the laptop daily since well before Christmas.

I did recently update this laptop to High Sierra, potentially around that time.

My main concern is: is this an indication my laptop has been compromised?

答:
Long story short, no it is not an indication.

The "last" command much like other history commands essentially print out the history that is written to a log file that is stored somewhere. For instance, if I use the history command in zsh, it will print out the contents of .zsh_history and if I delete that and attempt the command again after starting a new terminal, I will no longer get that history.

What likely happened here, is that the OS upgrade cleared that log file, and the history started saving again after that. That is why you are not able to see those commands from before. There is little worry that your laptop has been compromised just because of this. Unless, someone took your computer, looked at your history and then deleted that log file. But why would they do that, you know.

Body:
If I execute "last" in Terminal I see the following output:

Yonda     ttys000                   Wed Feb 19 18:03   still logged in
Yonda     console                   Tue Feb 18 23:21   still logged in
reboot    ~                         Tue Feb 18 23:21
shutdown  ~                         Tue Feb 18 23:18
Yonda     console                   Sun Feb 16 16:26 - 23:18 (2+06:52)
reboot    ~                         Sun Feb 16 16:26
shutdown  ~                         Sun Feb 16 16:25
root      console                   Sun Feb 16 16:24 - shutdown  (00:01)
Yonda     console                   Sun Feb 16 16:13 - 16:24  (00:10)
reboot    ~                         Sun Feb 16 16:13
shutdown  ~                         Sun Feb 16 16:12
Yonda     ttys001                   Sun Feb  9 16:09 - 16:09  (00:00)
Yonda     ttys001                   Sun Feb  9 15:56 - 15:56  (00:00)
Yonda     ttys001                   Thu Feb  6 11:01 - 11:01  (00:00)
Yonda     console                   Sat Feb  1 17:59 - 16:12 (14+22:13)
reboot    ~                         Sat Feb  1 17:58

It seems strange that this only goes back to Feb 1, when I've been using the laptop daily since well before Christmas.

I did recently update this laptop to High Sierra, potentially around that time.

My main concern is: is this an indication my laptop has been compromised?


问:
JWT - asymmetric encryption
I have three servers:
- authorization server
- api server
- frontend server

Authorization server returns JWT self-contained access token (+refresh token). JWTs aren't stored anywhere in Authorization Server.
I want to secure JWT with asymmetric encryption and i am not sure if i my idea is correct.
Let me describe flow:

After login from Fronted Server, Authorization server gets user credentials, then generates JWT token and encode it with public key.

Fronted Server receives encrypted JWT token and client (web browser) saves it as HTTP-Only cookie.

Client sends request to secured resource, so FrontEnd based on obtained encoded JWT token, requests for secured data API Server.

API Server based on secured JWT and private key decrypt value and checks if user has enough access to perform operation.

If JWT token expires, front end sends request to Authorization Server with refresh token to get new JWT token.

In this case Authorization Server and API Server would need to store private key for decryption.
Is this solution secure enough? Is it OK to store the same private key in two servers?
Do you know if flow is correct? Or maybe data flow should be different?

答:
I want to secure JWT with asymmetric encryption and i am not sure if i my idea is correct.

In general, data encryption is a good idea. Especially if you transport sensitive data.

Let me describe flow
[…]
In this case Authorization Server and API Server would need to store private key for decryption. Is this solution secure enough? Is it OK to store the same private key in two servers? Do you know if flow is correct? Or maybe data flow should be different?

If I understand correctly your flow, the token is encrypted on AS (Authorization Server) side and decrypted on API server side. Therefore you want to prevent the client from reading its content.

This flow is absolutely fine. Both the AS and the API server will have the shared secret so that they will be able to encrypt or decrypt the token.

I suggest you to read more about JWE (encrypted JWT) and the associated RFC7516. This specification describes a standard way to encrypt tokens.
Depending on the programming language you use, you may found libraries that support JWE. https://jwt.io/ lists lot of libraries and some of these support more than signed tokens (JWS). For example com.nimbusds/nimbus-jose-jwt (Java) or web-token/jwt-framework (PHP).

A possible flow could be as follow. Please not that it will undoubtedly create complexity in your AS and API server code. So before you implement it, you should make sure it is necessary to encrypt your tokens! (e.g. you transport sensitive data)

The AS sign the token with its private key (e.g. algorithm RSxxx, PSxxx or ESxxx) => JWS

The JWS is encrypted as per the RFC7516 with an asymmetric encryption algorithm (e.g. AxxxKW or AxxxGCMKW) and the shared key => Nested token (a JWS in a JWE)

The Nested token is sent to the client

The client cannot read the content, but the token can be sent to the API server as usual

The API server decrypts the JWE with the shared key to get the JWS

The API server verifies the JWS with the AS public key

Title: JWT - asymmetric encryption


问:
Command to remove all npm modules globally
Is there a command to remove all global npm modules? If not, what do you suggest?</p>

答:
For yarn global

nano ~/.config/yarn/global/package.json
<Manually remove all packages from package.json>
yarn global add
```

<p>Or, if you don't care about what is actually inside <code>package.json</code></p>

<pre class="lang-sh prettyprint-override"><code>echo {} >  ~/.config/yarn/global/package.json && yarn global add
</code>```

This should apply to NPM too, but I am not exactly sure where NPM global is stored.

Body:
For yarn global

nano ~/.config/yarn/global/package.json
<Manually remove all packages from package.json>
yarn global add

Or, if you don't care about what is actually inside package.json

echo {} >  ~/.config/yarn/global/package.json && yarn global add

This should apply to NPM too, but I am not exactly sure where NPM global is stored.


问:
How to get integer list from a string but not integer list?
I want to create an integer list from the string list called a. The list I want to create is shown in the integer list called b.

```<code>a = ["ab","ac","ad","ae","af","ab","ab"]
b = [1,2,3,4,5,1,1]

</code>```

I've tried that solution but it takes long time for thousands of data.

```<code>a = ["ab","ac","ad","ae","af","ab","ab"]
b = list(set(a))
for i in range(0,len(a)):
    if a[i] in b:
        a[i] = b.index(a[i])+1
print(a)
</code>```

Thanks

答:
```<code>a = ["ab","ac","ad","ae","af","ab","ab"]
from itertools import count
counter = count(1)
a_dict = dict()
b = []
for elem in a:
    a_dict[elem] = a_dict.get(elem, next(counter))
    b.append(a_dict[elem])

print(b)
</code>```

Outputs:
[1, 2, 3, 4, 5, 1, 1]

Just keeping track of which ones have been seen, and their respective numbers.  If not seen, it grabs the next number on the counter.

Body:
I want to create an integer list from the string list called a. The list I want to create is shown in the integer list called b.

a = ["ab","ac","ad","ae","af","ab","ab"]
b = [1,2,3,4,5,1,1]

I've tried that solution but it takes long time for thousands of data.

a = ["ab","ac","ad","ae","af","ab","ab"]
b = list(set(a))
for i in range(0,len(a)):
    if a[i] in b:
        a[i] = b.index(a[i])+1
print(a)

Thanks

Body:
a = ["ab","ac","ad","ae","af","ab","ab"]
from itertools import count
counter = count(1)
a_dict = dict()
b = []
for elem in a:
    a_dict[elem] = a_dict.get(elem, next(counter))
    b.append(a_dict[elem])

print(b)

Outputs:
[1, 2, 3, 4, 5, 1, 1]

Just keeping track of which ones have been seen, and their respective numbers.  If not seen, it grabs the next number on the counter.


问:
How Pod status becomes MatchNodeSelector
In our staging environment, there is a defect reported. After kubernetes updated, some Pods status become 'MatchNodeSelector'.

But I have no idea why and how some Pods become 'MatchNodeSelector'. So I do some research 'if a Pod have a field 'nodeSelector' and doesn't have any node have this label. These Pods will become 'MatchNodeSelector'.

But I cannot reproduce it. The Pods status always becomes 'Pending', not 'MatchNodeSelector'.
So my question is that how can I make a Pod status become 'MatchNodeSelector'?

答:
I have been able to reproduce this by:

For any running pod with no node affinity provided, export its yaml or json with kubectl get po -o json --export. Do note the node on which it is running

Delete the pod.

Explicitly provide the node affinity to a node which is not the same as the previous node on which it was running. Add it in spec with something like this:

```<code> "spec": {
     "affinity": {
        "nodeAffinity": {
          "requiredDuringSchedulingIgnoredDuringExecution": {
            "nodeSelectorTerms": [
              {
                "matchExpressions": [
                  {
                    "key": "kubernetes.io/hostname",
                    "operator": "In",
                    "values": [
                      "new node name"
                    ]
                  }
                ]
              }
            ]
          }
        }
      }
    }
</code>```

Create the pod with kubectl create -f pod.json

Pod status is now MatchNodeSelector.

This is because there is a node option in the same spec as well, which also needs to be changed. It is not removed by the --export option and would still have the older node name in that field.

I am guessing if it conflicts with whatever node name you gave in affinity, it will result in this status.

These are the versions:
`Client Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.3", GitCommit:"2bba0127d85d5a46ab4b778548be28623b32d0b0", GitTreeState:"clean", BuildDate:"2018-05-21T09:17:39Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"darwin/amd64"}

Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.1", GitCommit:"eec55b9ba98609a46fee712359c7b5b365bdd920", GitTreeState:"clean", BuildDate:"2018-12-13T10:31:33Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"linux/amd64"}`

Body:
I have been able to reproduce this by:

For any running pod with no node affinity provided, export its yaml or json with kubectl get po -o json --export. Do note the node on which it is running

Delete the pod.

Explicitly provide the node affinity to a node which is not the same as the previous node on which it was running. Add it in spec with something like this:

 "spec": {
     "affinity": {
        "nodeAffinity": {
          "requiredDuringSchedulingIgnoredDuringExecution": {
            "nodeSelectorTerms": [
              {
                "matchExpressions": [
                  {
                    "key": "kubernetes.io/hostname",
                    "operator": "In",
                    "values": [
                      "new node name"
                    ]
                  }
                ]
              }
            ]
          }
        }
      }
    }

Create the pod with kubectl create -f pod.json

Pod status is now MatchNodeSelector.

This is because there is a node option in the same spec as well, which also needs to be changed. It is not removed by the --export option and would still have the older node name in that field.

I am guessing if it conflicts with whatever node name you gave in affinity, it will result in this status.

These are the versions:
`Client Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.3", GitCommit:"2bba0127d85d5a46ab4b778548be28623b32d0b0", GitTreeState:"clean", BuildDate:"2018-05-21T09:17:39Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"darwin/amd64"}

Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.1", GitCommit:"eec55b9ba98609a46fee712359c7b5b365bdd920", GitTreeState:"clean", BuildDate:"2018-12-13T10:31:33Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"linux/amd64"}`


问:
Using RelativeLayout dynamically and setting margins in px, dp, inch, mm
My application is just a modified ImageViewer with the options of zooming and dragging.
Containing that modified Imageviewer there is a RelativeLayout (that I want to use as an AbsoluteLayout).

Then, new elements can be added to the layout to situate them in certain points of the image. The position (x, y) in pixels of the elements is in a database so I guess there is no other way that adding them programmatically, and not with XML.

Then the position of those elements is updated every time that a dragging or zooming action is performed.

The problem is that somehow the pixels of the image are not matching with the pixels in the RelativeLayout! So the items are "more or less" situated but not in the proper place (the further from (0,0) the bigger is the error).

Things I've tried already:

Try different conversions because maybe the problem is related to the difference of densities between the Bitmap and the Layout:

```<code>Resources r = getResources();
float x = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, r.getDisplayMetrics());
</code>```

Try to use different methods in the layout to set the margins:

```<code>RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin = (int) newPosition.x;
params.topMargin = (int) newPosition.y;
element.setLayoutParams(params);
</code>```

I also wanted to use the options available for the RelativeLayout in XML but I really cant find it programmatically but I can find the way to specify the dimension, I mean:

```<code>android:layout_marginLeft ="50px" // or "50mm", or dp, or inches...
</code>```

答:
I've found the answer, the problem was in fact with the density, so I made:

```<code>    DisplayMetrics metrics = getResources().getDisplayMetrics();
    float density = metrics.density;
    //And then I add a new element like: realX*density, realY*density
</code>```

I don't understand so much what it is doing but it works... Actually what I don't understand the value metrics.density
Any explanation is welcome.

Body:
My application is just a modified ImageViewer with the options of zooming and dragging.
Containing that modified Imageviewer there is a RelativeLayout (that I want to use as an AbsoluteLayout).

Then, new elements can be added to the layout to situate them in certain points of the image. The position (x, y) in pixels of the elements is in a database so I guess there is no other way that adding them programmatically, and not with XML.

Then the position of those elements is updated every time that a dragging or zooming action is performed.

The problem is that somehow the pixels of the image are not matching with the pixels in the RelativeLayout! So the items are "more or less" situated but not in the proper place (the further from (0,0) the bigger is the error).

Things I've tried already:

Try different conversions because maybe the problem is related to the difference of densities between the Bitmap and the Layout:

Resources r = getResources();
float x = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, r.getDisplayMetrics());

Try to use different methods in the layout to set the margins:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin = (int) newPosition.x;
params.topMargin = (int) newPosition.y;
element.setLayoutParams(params);

I also wanted to use the options available for the RelativeLayout in XML but I really cant find it programmatically but I can find the way to specify the dimension, I mean:

android:layout_marginLeft ="50px" // or "50mm", or dp, or inches...

Body:
I've found the answer, the problem was in fact with the density, so I made:

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    float density = metrics.density;
    //And then I add a new element like: realX*density, realY*density

I don't understand so much what it is doing but it works... Actually what I don't understand the value metrics.density
Any explanation is welcome.


问:
How to add listener to ul li list?
How to add listener to ul li list, that is in component template?

```<code><ul #list>
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

I have tried:

```<code>@ViewChild("list", { static: false }) list: ElementRef;

ngOnInit() {
   list.addEventListener('keydown', this.onKeyDown);
}

 onKeyDown = (e) => { console.log(e); // event keydown}
</code>```

But it does not work for me.

答:
You don't need ViewChild to do that. simply use the keydown event.
Make sure you add tabindex to be able to focus the element.

https://stackblitz.com/edit/angular-umck67

HTML

```<code><ul tabindex=-1 (keydown)="onKeyDown($event)">
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

Component:

```<code>onKeyDown = (e) => { console.log(e);  }
</code>```

Title: How to add listener to ul li list?

Body:
How to add listener to ul li list, that is in component template?

1

2

3

I have tried:

@ViewChild("list", { static: false }) list: ElementRef;

ngOnInit() {
   list.addEventListener('keydown', this.onKeyDown);
}

 onKeyDown = (e) => { console.log(e); // event keydown}

But it does not work for me.

Body:
You don't need ViewChild to do that. simply use the keydown event.
Make sure you add tabindex to be able to focus the element.

https://stackblitz.com/edit/angular-umck67

HTML

<ul tabindex=-1 (keydown)="onKeyDown($event)">
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>

Component:

onKeyDown = (e) => { console.log(e);  }