问:
Can't make
 text aligned to top in grid layout
I've created a simple CSS grid layout of two columns and h2 elements are aligned properly at the top, but P elements are aligned vertically to the middle.

I've tried adding vertical-align: top and vertical-align: text-top, nothing changed.

#prosolcolumns {
  padding: 40px !important;
  display: grid !important;
  grid-gap: 40px !important;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)) !important;
  grid-template-rows: auto !important;
  background: #ffffff !important;
  max-width: 90% !important;
  min-width: 50% !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
  margin-left: auto !important;
  margin-right: auto !important;
}

#prosolcolumns>div,
#prosolcolumns>noindex>div {
  display: grid;
  vertical-align: top !important;
  width: auto !important;
  padding: 40px !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
}

#prosolcolumns p {
  padding: 0px 0px 0px 0px !important;
  margin-left: 0px !important;
  text-align: justify;
}

#prosolcolumns h2 {
  margin-left: 0px !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="prosolcolumns">
  <div>
    <h2>Problem</h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices. Phasellus in sollicitudin justo. Cras faucibus et diam quis facilisis. Nam ac lectus sem. Duis sit amet est nec felis malesuada semper quis pretium arcu. Sed laoreet mattis nisl, non
      tempor quam porttitor et. Nulla non ante sit amet ex blandit tincidunt nec sit amet lorem. Nam vitae lacus pretium, porta leo id, maximus enim. Vestibulum vehicula nunc vel enim euismod, ac convallis sem iaculis. Lorem ipsum dolor sit amet, consectetur
      adipiscing elit. Phasellus sit amet sem sapien. Sed vel turpis eget nunc facilisis maximus fermentum vel tellus.
    </p>
  </div>
  <div>
    <h2>Solution</h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices.
    </p>
  </div>
</div></code>```

答:
The row size would be auto by default - you can change this by using grid-template-rows or grid-auto-rows property. I am using grid-auto-rows: min-content in the demo below:

#prosolcolumns {
  padding: 40px !important;
  display: grid !important;
  grid-gap: 40px !important;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)) !important;
  grid-template-rows: auto !important;
  background: #ffffff !important;
  max-width: 90% !important;
  min-width: 50% !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
  margin-left: auto !important;
  margin-right: auto !important;
}

#prosolcolumns>div,
#prosolcolumns>noindex>div {
  display: grid;
  grid-auto-rows: min-content; /* added */
  vertical-align: top !important;
  width: auto !important;
  padding: 40px !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
}

#prosolcolumns p {
  padding: 0px 0px 0px 0px !important;
  margin-left: 0px !important;
  text-align: justify;
}

#prosolcolumns h2 {
  margin-left: 0px !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="prosolcolumns">
  <div>
    <h2>Problem</h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices. Phasellus in sollicitudin justo. Cras faucibus et diam quis facilisis. Nam ac lectus sem. Duis sit amet est nec felis malesuada semper quis pretium arcu. Sed laoreet mattis nisl, non
      tempor quam porttitor et. Nulla non ante sit amet ex blandit tincidunt nec sit amet lorem. Nam vitae lacus pretium, porta leo id, maximus enim. Vestibulum vehicula nunc vel enim euismod, ac convallis sem iaculis. Lorem ipsum dolor sit amet, consectetur
      adipiscing elit. Phasellus sit amet sem sapien. Sed vel turpis eget nunc facilisis maximus fermentum vel tellus.
    </p>
  </div>
  <div>
    <h2>Solution</h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices.

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

Please note that this is not a complete solution - because what you are trying to do is match grid items in adjacent grid containers and this would come under the preview of the new subgrid module. It'd have been easier to match the inner grids if subgrid module was supported in browsers (only in Firefox Nightly versions at the moment). See some of the discussions too if interested:

Alignment of content vertically in adjacent flexbox containers

Wrap CSS grid with auto placement

Title: Can't make <p> text aligned to top in grid layout

Body:
I've created a simple CSS grid layout of two columns and h2 elements are aligned properly at the top, but P elements are aligned vertically to the middle.

I've tried adding vertical-align: top and vertical-align: text-top, nothing changed.

#prosolcolumns {
  padding: 40px !important;
  display: grid !important;
  grid-gap: 40px !important;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)) !important;
  grid-template-rows: auto !important;
  background: #ffffff !important;
  max-width: 90% !important;
  min-width: 50% !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
  margin-left: auto !important;
  margin-right: auto !important;
}

#prosolcolumns>div,
#prosolcolumns>noindex>div {
  display: grid;
  vertical-align: top !important;
  width: auto !important;
  padding: 40px !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
}

#prosolcolumns p {
  padding: 0px 0px 0px 0px !important;
  margin-left: 0px !important;
  text-align: justify;
}

#prosolcolumns h2 {
  margin-left: 0px !important;
}

Problem

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices. Phasellus in sollicitudin justo. Cras faucibus et diam quis facilisis. Nam ac lectus sem. Duis sit amet est nec felis malesuada semper quis pretium arcu. Sed laoreet mattis nisl, non
      tempor quam porttitor et. Nulla non ante sit amet ex blandit tincidunt nec sit amet lorem. Nam vitae lacus pretium, porta leo id, maximus enim. Vestibulum vehicula nunc vel enim euismod, ac convallis sem iaculis. Lorem ipsum dolor sit amet, consectetur
      adipiscing elit. Phasellus sit amet sem sapien. Sed vel turpis eget nunc facilisis maximus fermentum vel tellus.

Solution

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices.

Body:
The row size would be auto by default - you can change this by using grid-template-rows or grid-auto-rows property. I am using grid-auto-rows: min-content in the demo below:

#prosolcolumns {
  padding: 40px !important;
  display: grid !important;
  grid-gap: 40px !important;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)) !important;
  grid-template-rows: auto !important;
  background: #ffffff !important;
  max-width: 90% !important;
  min-width: 50% !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
  margin-left: auto !important;
  margin-right: auto !important;
}

#prosolcolumns>div,
#prosolcolumns>noindex>div {
  display: grid;
  grid-auto-rows: min-content; /* added */
  vertical-align: top !important;
  width: auto !important;
  padding: 40px !important;
  box-sizing: border-box;
  /* не поддерживается в CSS2 */
}

#prosolcolumns p {
  padding: 0px 0px 0px 0px !important;
  margin-left: 0px !important;
  text-align: justify;
}

#prosolcolumns h2 {
  margin-left: 0px !important;
}

<div id="prosolcolumns">
  <div>
    <h2>Problem</h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices. Phasellus in sollicitudin justo. Cras faucibus et diam quis facilisis. Nam ac lectus sem. Duis sit amet est nec felis malesuada semper quis pretium arcu. Sed laoreet mattis nisl, non
      tempor quam porttitor et. Nulla non ante sit amet ex blandit tincidunt nec sit amet lorem. Nam vitae lacus pretium, porta leo id, maximus enim. Vestibulum vehicula nunc vel enim euismod, ac convallis sem iaculis. Lorem ipsum dolor sit amet, consectetur
      adipiscing elit. Phasellus sit amet sem sapien. Sed vel turpis eget nunc facilisis maximus fermentum vel tellus.
    </p>
  </div>
  <div>
    <h2>Solution</h2>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat sodales quam, vitae auctor ligula consequat ut. Phasellus quis mollis lectus. Aenean aliquet enim in suscipit rutrum. Praesent quis pellentesque orci, vel auctor lorem. Sed tortor
      ligula, porttitor quis lorem vitae, vehicula consectetur metus. Phasellus accumsan lectus in turpis suscipit blandit. Aenean ornare, nulla id tempus semper, lectus augue lobortis nulla, aliquam gravida risus mauris at diam. Donec in maximus nisl.
      Nullam luctus metus ut lectus commodo, a tincidunt ex ultrices.

    </p>
  </div>
</div>

Please note that this is not a complete solution - because what you are trying to do is match grid items in adjacent grid containers and this would come under the preview of the new subgrid module. It'd have been easier to match the inner grids if subgrid module was supported in browsers (only in Firefox Nightly versions at the moment). See some of the discussions too if interested:

Alignment of content vertically in adjacent flexbox containers

Wrap CSS grid with auto placement


来源: stackexchange

问:
Create new Column in Power Bi with RegEx
I'm relatively new to Power BI and want to generate a new one based on a column. The contents of the new column should be based on the first value of another column. For example:

```<code>ColumnA NewColumn
1123 Argentinia
5644 Brazil
5555 Brazil
3334 Denmark
1124 Argentinia
</code>```

As you can see, the first value of the number decides which country will be added to the new column.
In SQL I know that I can use something like this:

```<code>`select * from table where column LIKE '%[2]`%'
</code>```

and so on but is this possible with Power BI? Thanks a lot.

Edit:

My additional list looks like this:

```<code>ID Country
1  Argentina
2  Swiss
3  Denmark
4  Norway
5  Brazil
</code>```

and so on...

I thougt I could use somethin like this:

```<code>NewColumn = IF('table'[ColumnA] = "%[1]`%"
THEN "Argentinia"
ELSE if IF('table'[ColumnA] = "%[2]`%
THEN Swiss
ELSE "No Country")
</code>```

答:
Okay, I've now also found a solution:

```<code>NewColumn = SWITCH(TRUE();

                 LEFT(table[ColumnA]; 1) in {"1"}; "Argentina";
                 LEFT(table[ColumnA]; 1) in {"2"}; "Swiss";
                 LEFT(table[ColumnA]; 1) in {"3"}; "Denmark";
                 LEFT(table[ColumnA]; 1) in {"4"}; "Norway";
                 LEFT(table[ColumnA]; 1) in {"5"}; "Brazil"
            )
</code>```

Works very well :)

ContentLicense: CC BY-SA 4.0

Body:
I'm relatively new to Power BI and want to generate a new one based on a column. The contents of the new column should be based on the first value of another column. For example:

ColumnA NewColumn
1123 Argentinia
5644 Brazil
5555 Brazil
3334 Denmark
1124 Argentinia

As you can see, the first value of the number decides which country will be added to the new column.
In SQL I know that I can use something like this:

`select * from table where column LIKE '%[2]`%'

and so on but is this possible with Power BI? Thanks a lot.

Edit:

My additional list looks like this:

ID Country
1  Argentina
2  Swiss
3  Denmark
4  Norway
5  Brazil

and so on...

I thougt I could use somethin like this:

NewColumn = IF('table'[ColumnA] = "%[1]`%"
THEN "Argentinia"
ELSE if IF('table'[ColumnA] = "%[2]`%
THEN Swiss
ELSE "No Country")

Body:
Okay, I've now also found a solution:

NewColumn = SWITCH(TRUE();

                 LEFT(table[ColumnA]; 1) in {"1"}; "Argentina";
                 LEFT(table[ColumnA]; 1) in {"2"}; "Swiss";
                 LEFT(table[ColumnA]; 1) in {"3"}; "Denmark";
                 LEFT(table[ColumnA]; 1) in {"4"}; "Norway";
                 LEFT(table[ColumnA]; 1) in {"5"}; "Brazil"
            )

Works very well :)


问:
Insert multiple rows from result of Average by date and id
I have a table with 1 result per day like this :

```<code>id |  item_id  | date       | amount
-------------------------------------
1       1        2019-01-01     1
2       1        2019-01-02     2
3       1        2019-01-03     3
4       1        2019-01-04     4
5       1        2019-01-05     5
6       2        2019-01-01     1
7       2        2019-01-01     2
8       2        2019-01-01     3
9       2        2019-01-01     4
10      2        2019-01-01     5
11      3        2019-01-01     1
12      3        2019-01-01     2
13      3        2019-01-01     3
14      3        2019-01-01     4
15      3        2019-01-01     5
</code>```

First I was trying to average the column amount for each day.

```<code>SELECT
    x.item_id AS id,avg(x.amount) AS result
FROM
    (SELECT
         il.item_id, il.amount,
         ROW_NUMBER() OVER (PARTITION BY il.item_id  ORDER BY il.date DESC) rn
     FROM
         item_prices il) x
WHERE
    x.rn BETWEEN 1 AND 50
GROUP BY
    x.item_id
</code>```

The result is going to be the following if calculated on 2019-01-05

```<code>item_id |  average
   1         3
   2         3
   3         3
</code>```

or, if calculated 2019-01-04

```<code>item_id |  average
   1         2.5
   2         2.5
   3         2.5
</code>```

My goal is to run the Average query , every day that would update the average automatically and insert it in 5th column "average" :

```<code>id |  item_id  | date       | amount | average
5       1        2019-01-05     5        3
10      2        2019-01-05     5        3
15      3        2019-01-05     5        3
</code>```

Issue is that every example i can find with Insert the Select they only update one row and they are over another table there is also the most recent date issue...

Can someone point me in the right direction?

答:
Perhaps you want to see  running average every day. Storing the value as a separate column is bound to cause problems especially when the rows are updated/deleted, the column also needs to be updated and hence will require complex triggers.

Simply create a View and run whenever you want to check the average directly from that View.

```<code>CREATE OR REPLACE VIEW v_item_prices AS
SELECT t.*,avg(t.amount) OVER ( PARTITION BY item_id order by date)
  AS average FROM item_prices t
  order by item_id,date
</code>```

DEMO

Body:
I have a table with 1 result per day like this :

id |  item_id  | date       | amount
-------------------------------------
1       1        2019-01-01     1
2       1        2019-01-02     2
3       1        2019-01-03     3
4       1        2019-01-04     4
5       1        2019-01-05     5
6       2        2019-01-01     1
7       2        2019-01-01     2
8       2        2019-01-01     3
9       2        2019-01-01     4
10      2        2019-01-01     5
11      3        2019-01-01     1
12      3        2019-01-01     2
13      3        2019-01-01     3
14      3        2019-01-01     4
15      3        2019-01-01     5

First I was trying to average the column amount for each day.

SELECT
    x.item_id AS id,avg(x.amount) AS result
FROM
    (SELECT
         il.item_id, il.amount,
         ROW_NUMBER() OVER (PARTITION BY il.item_id  ORDER BY il.date DESC) rn
     FROM
         item_prices il) x
WHERE
    x.rn BETWEEN 1 AND 50
GROUP BY
    x.item_id

The result is going to be the following if calculated on 2019-01-05

item_id |  average
   1         3
   2         3
   3         3

or, if calculated 2019-01-04

item_id |  average
   1         2.5
   2         2.5
   3         2.5

My goal is to run the Average query , every day that would update the average automatically and insert it in 5th column "average" :

id |  item_id  | date       | amount | average
5       1        2019-01-05     5        3
10      2        2019-01-05     5        3
15      3        2019-01-05     5        3

Issue is that every example i can find with Insert the Select they only update one row and they are over another table there is also the most recent date issue...

Can someone point me in the right direction?

Body:
Perhaps you want to see  running average every day. Storing the value as a separate column is bound to cause problems especially when the rows are updated/deleted, the column also needs to be updated and hence will require complex triggers.

Simply create a View and run whenever you want to check the average directly from that View.

CREATE OR REPLACE VIEW v_item_prices AS
SELECT t.*,avg(t.amount) OVER ( PARTITION BY item_id order by date)
  AS average FROM item_prices t
  order by item_id,date

DEMO


问:
Where to start with writing a small h.264 encoder
I need to write a very small, very simple h.264 encoder. I started with hello264 (the world's smallest h.264 encoder) and I'm starting to understand a few of the basics.  I'm also trying to wade through the h.264 spec, but I'm finding it difficult to understand without examples.  I've also got source code for x264 and ffmpeg, but that's a lot of code to wade through and I don't understand the principals of where to start. For example, I'm only looking to start with simple intra frame compression. Any advice on a good book, blog, article, document, etc. is appreciated.  </p>

答: The best answer seems to be the book "The H.264 Advance Video Compression Standard", by Iain E. Richardson.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Use NgClass with a custom Pipe
I'm trying to assign a custom class on a span based on a result given from a pipe trasform. Sadly, I'm not getting it to work.

Here's the scenario. I'm itering this object in a ngFor statement:

```<code>"documents": [
  {
    "document_ext": "pdf"
  } ,
  {
    "document_ext": "doc"
  }
]
</code>```

While itering I want to assign a custom class based on the document_ext. but this is causing me following error:

Error: Got interpolation ({{}}) where expression was expected at
  column 0 in [{{doc?.document_ext | documentaleType}}]

The html code:

```<code><ng-container *ngFor="let doc of documentList">
  <div class="row">
    <div class="doc-type">
      <span class="row-icon" [ngClass]="{{doc?.document_ext | documentaleType}}">
      </span>
     </div>
  </div>
</ng-container>
</code>```

And the simple pipe just return a standard value for now:

```<code>export class DocumentaleTypePipe {
    transform(ext: string): string {
        return "p3-018-dummy";
    }
}
</code>```

I don't want to call a function, that's why I've choose to use a pipe. What am I missing?

Any help is appreciated.

EDIT

Solved this way:

```<code><span class="row-icon" [ngClass]="[doc.document_ext ? (doc.document_ext | documentaleType) : 'p3-018-dummy']"></span>
</code>```

答:
PIPE

```<code>@Pipe({
  name: 'getClass'
})
export class GetClassPipe implements PipeTransform {
  transform(obj: any, args?: any): any {
    return obj['document_ext'];
  }
}
</code>```

COMPONENT

```<code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public documents = [
    {
      "document_ext": "pdf"
    },
    {
      "document_ext": "doc"
    }
  ]
}
</code>```

HTML

```<code><div *ngFor="let doc of documents" [ngClass]="doc | getClass">test</div>
</code>```

CSS

```<code>.pdf {
  color:red
}

.doc {
  color:green
}
</code>```

Here's a live demo https://stackblitz.com/edit/use-ngclass-with-a-custom-pipe

Title: Use NgClass with a custom Pipe

Body:
I'm trying to assign a custom class on a span based on a result given from a pipe trasform. Sadly, I'm not getting it to work.

Here's the scenario. I'm itering this object in a ngFor statement:

"documents": [
  {
    "document_ext": "pdf"
  } ,
  {
    "document_ext": "doc"
  }
]

While itering I want to assign a custom class based on the document_ext. but this is causing me following error:

Error: Got interpolation ({{}}) where expression was expected at
  column 0 in [{{doc?.document_ext | documentaleType}}]

The html code:

<ng-container *ngFor="let doc of documentList">

</ng-container>

And the simple pipe just return a standard value for now:

export class DocumentaleTypePipe {
    transform(ext: string): string {
        return "p3-018-dummy";
    }
}

I don't want to call a function, that's why I've choose to use a pipe. What am I missing?

Any help is appreciated.

EDIT

Solved this way:

Body:
PIPE

@Pipe({
  name: 'getClass'
})
export class GetClassPipe implements PipeTransform {
  transform(obj: any, args?: any): any {
    return obj['document_ext'];
  }
}

COMPONENT

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public documents = [
    {
      "document_ext": "pdf"
    },
    {
      "document_ext": "doc"
    }
  ]
}

HTML

<div *ngFor="let doc of documents" [ngClass]="doc | getClass">test</div>

CSS

.pdf {
  color:red
}

.doc {
  color:green
}

Here's a live demo https://stackblitz.com/edit/use-ngclass-with-a-custom-pipe


问:
setFetchMode() seems not to be working and not returning an object?
I'm currently working with one of my friends on making a portfolio for all of his projects and as strangely as it seems, I cannot manage to make setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Class Namespace') working on his code while it is working on my projects.

Here is the error returned by PHP :
!(https://cdn.discordapp.com/attachments/525023910698156034/583938068311179265/unknown.png)

Here is the class Entity which contains the __construct() function and the hydration() function :

<?php

namespace App\Entity;

class Entity {

    public function __construct(array $array) {
        $this->hydrate($array);
    }

    public function hydrate($array) {
        foreach ($array as $key => $value) {
            $setter = 'set' . ucfirst($key);
            if (method_exists($this, $setter)) {
                $this->$setter($value);
            }
        }
    }
}
```

<p>Then, here is the Project Class which implements the class Entity : </p>

<pre class="lang-php prettyprint-override"><code><?php

namespace App\Entity;

class Project extends Entity implements \JsonSerializable {

    private $_title;
    private $_description;
    private $_imagePath;
    private $_link;
    private $_repoLink;
    private $_creationDate;

    public function jsonSerialize() {
        return [
            'title' => $this->_title,
            'description' => $this->_description,
            'imagePath' => $this->_imagePath,
            'link' => $this->_link,
            'repoLink' => $this->_repoLink,
            'creationDate' => $this->_creationDate,
        ];
    }

    /
     * @return string
     */
    public function getTitle(): string {
        return $this->_title;
    }

    /
     * @param string $title
     */
    public function setTitle(string $title) {
        $this->_title = $title;
    }

    /
     * @return string
     */
    public function getDescription(): string {
        return $this->_description;
    }

    /
     * @param string $description
     */
    public function setDescription(string $description) {
        $this->_description = $description;
    }

    /
     * @return string
     */
    public function getImagePath(): string {
        return $this->_imagePath;
    }

    /
     * @param string $imagePath
     */
    public function setImagePath(string $imagePath) {
        $this->_imagePath = $imagePath;
    }

    /
     * @return string
     */
    public function getLink(): string {
        return $this->_link;
    }

    /
     * @param string $link
     */
    public function setLink(string $link) {
        $this->_link = $link;
    }
/
     * @return string
     */
    public function getRepoLink(): string {
        return $this->_repoLink;
    }

    /
     * @param string $repoLink
     */
    public function setRepoLink(string $repoLink) {
        $this->_repoLink = $repoLink;
    }

    /
     * @return \DateTime
     */
    public function getCreationDate(): \DateTime {
        return $this->_creationDate;
    }

    /
     * @param string $creationDate
     */
    public function setCreationDate(string $creationDate) {
        $this->_creationDate = new \DateTime($creationDate);
    }
}
</code>```

And finally, here is the SQL request :

<?php

namespace App\Model;

class ProjectManager extends Manager {

    /**
     * return a collection of Project objects
     * @return Project[]
     * @throws \Exception
     */
    public function getProjects() {
        $db = $this->getDb();
        $q = $db->query(
            'SELECT id,
                     title,
                     description,
                     image_path AS imagePath,
                     link,
                     repo_link AS repoLink,
                     creation_date AS creationDate
            FROM my_website_projects
            ORDER BY creationDate'
        );

        $q->setFetchMode(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, 'App\Entity\Project');
        $projects = $q->fetchAll();

        return $projects;
    }
}
```

The only thing that seems to work is to add PDO::FETCH_ASSOC in the fetchAll() but then it doesn't return an object but an array....

Your help would be much appreciated on this problem ! :)

答:
As far as I know, there is no solution to this problem. There is no fetch mode that creates an object passing the returned row as a constructor parameter.

So I would change the code to this a bit clumsy but working solution

```<code>public function getProjects() {
    $db = $this->getDb();
    $q = $db->query(
        'SELECT id,
                 title,
                 description,
                 image_path AS imagePath,
                 link,
                 repo_link AS repoLink,
                 creation_date AS creationDate
        FROM my_website_projects
        ORDER BY creationDate'
    );
    $projects = [];
    while($row = $q->fetch(PDO::FETCH_ASSOC)) {
        $projects[] = new App\Entity\Project($row);
    }
    return $projects;
}
</code>```

Your mistake is that you slightly confused the way PDO creates objects.

This way is rather blunt, PDO just takes an object and fills it properties, the process is not much different from filling an associative array.

So now you can tell how did your other code work:

first, the constructor parameter in your other class is optional, it means PHP won't complain for it.

second, in your other class properties are spelled equal to column names in the database, and PDO happily fills them as described above.

So, as another solution you can fix these 2 issues: make the constructor parameter optional and remove the underscore from the property names.

Some time ago I wrote an article on fetching obejects with PDO, you may find it useful.

Body:
I'm currently working with one of my friends on making a portfolio for all of his projects and as strangely as it seems, I cannot manage to make setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Class Namespace') working on his code while it is working on my projects.

Here is the error returned by PHP :
!(https://cdn.discordapp.com/attachments/525023910698156034/583938068311179265/unknown.png)

Here is the class Entity which contains the __construct() function and the hydration() function :

<?php

namespace App\Entity;

class Entity {

    public function __construct(array $array) {
        $this->hydrate($array);
    }

    public function hydrate($array) {
        foreach ($array as $key => $value) {
            $setter = 'set' . ucfirst($key);
            if (method_exists($this, $setter)) {
                $this->$setter($value);
            }
        }
    }
}

Then, here is the Project Class which implements the class Entity :

<?php

namespace App\Entity;

class Project extends Entity implements \JsonSerializable {

    private $_title;
    private $_description;
    private $_imagePath;
    private $_link;
    private $_repoLink;
    private $_creationDate;

    public function jsonSerialize() {
        return [
            'title' => $this->_title,
            'description' => $this->_description,
            'imagePath' => $this->_imagePath,
            'link' => $this->_link,
            'repoLink' => $this->_repoLink,
            'creationDate' => $this->_creationDate,
        ];
    }

    /
     * @return string
     */
    public function getTitle(): string {
        return $this->_title;
    }

    /
     * @param string $title
     */
    public function setTitle(string $title) {
        $this->_title = $title;
    }

    /
     * @return string
     */
    public function getDescription(): string {
        return $this->_description;
    }

    /
     * @param string $description
     */
    public function setDescription(string $description) {
        $this->_description = $description;
    }

    /
     * @return string
     */
    public function getImagePath(): string {
        return $this->_imagePath;
    }

    /
     * @param string $imagePath
     */
    public function setImagePath(string $imagePath) {
        $this->_imagePath = $imagePath;
    }

    /
     * @return string
     */
    public function getLink(): string {
        return $this->_link;
    }

    /
     * @param string $link
     */
    public function setLink(string $link) {
        $this->_link = $link;
    }
/
     * @return string
     */
    public function getRepoLink(): string {
        return $this->_repoLink;
    }

    /
     * @param string $repoLink
     */
    public function setRepoLink(string $repoLink) {
        $this->_repoLink = $repoLink;
    }

    /
     * @return \DateTime
     */
    public function getCreationDate(): \DateTime {
        return $this->_creationDate;
    }

    /
     * @param string $creationDate
     */
    public function setCreationDate(string $creationDate) {
        $this->_creationDate = new \DateTime($creationDate);
    }
}

And finally, here is the SQL request :

<?php

namespace App\Model;

class ProjectManager extends Manager {

    /**
     * return a collection of Project objects
     * @return Project[]
     * @throws \Exception
     */
    public function getProjects() {
        $db = $this->getDb();
        $q = $db->query(
            'SELECT id,
                     title,
                     description,
                     image_path AS imagePath,
                     link,
                     repo_link AS repoLink,
                     creation_date AS creationDate
            FROM my_website_projects
            ORDER BY creationDate'
        );

        $q->setFetchMode(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, 'App\Entity\Project');
        $projects = $q->fetchAll();

        return $projects;
    }
}

The only thing that seems to work is to add PDO::FETCH_ASSOC in the fetchAll() but then it doesn't return an object but an array....

Your help would be much appreciated on this problem ! :)

Body:
As far as I know, there is no solution to this problem. There is no fetch mode that creates an object passing the returned row as a constructor parameter.

So I would change the code to this a bit clumsy but working solution

public function getProjects() {
    $db = $this->getDb();
    $q = $db->query(
        'SELECT id,
                 title,
                 description,
                 image_path AS imagePath,
                 link,
                 repo_link AS repoLink,
                 creation_date AS creationDate
        FROM my_website_projects
        ORDER BY creationDate'
    );
    $projects = [];
    while($row = $q->fetch(PDO::FETCH_ASSOC)) {
        $projects[] = new App\Entity\Project($row);
    }
    return $projects;
}

Your mistake is that you slightly confused the way PDO creates objects.

This way is rather blunt, PDO just takes an object and fills it properties, the process is not much different from filling an associative array.

So now you can tell how did your other code work:

first, the constructor parameter in your other class is optional, it means PHP won't complain for it.

second, in your other class properties are spelled equal to column names in the database, and PDO happily fills them as described above.

So, as another solution you can fix these 2 issues: make the constructor parameter optional and remove the underscore from the property names.

Some time ago I wrote an article on fetching obejects with PDO, you may find it useful.


问:
Mockito verify fails in second unit test
I am using Mockito together to JUnit to implement unit tests for a class in an Android project.The problem is that I call Mockito.verify in two consequent tests where the tests are exactly same (to make sure that I am using Mockito correctly) but the interesting thing is that verify in second test always fails.I suspect that some operations need to be done before each test using @before annotation or so, that I have missed.Here are some code snippet about what I am doing.

I use Android Studio 3.4.1, Mockito 2.7.22 and JUnit 4.12.

```<code>@Test
public void test_onStart_do_nothing() throws Exception {
    ZConnectionService zConnectionService = new ZConnectionService();
    ZConnection mockedZConnection = mock(ZConnection.class);

    doNothing().when(mockedZConnection).connect();
    zConnectionService.initConnection(mockedZConnection);

    verify(mockedZConnection, times(1)).connect();
}

@Test
public void test_onStart_throw_IO_exceptioon() throws Exception {
    ZConnectionService zConnectionService = new ZConnectionService();
    ZConnection mockedZConnection = mock(ZConnection.class);

    doNothing().when(mockedZConnection).connect();
    zConnectionService.initConnection(mockedZConnection);
    // Line above is the line that error message points to!

    verify(mockedZConnection, times(1)).connect();
}
</code>```

Here comes the function under test

```<code>public void initConnection(ZConnection connection) {
    Log.d(TAG,"initConnection()");

    if (mConnection == null) {
        mConnection = connection;
    }

    if (!mActive) {
        mActive = true;

        if (mThread == null || !mThread.isAlive()) {
            mThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // The code here runs in a background thread.
                    Looper.prepare();
                    mTHandler = new Handler();

                    try {
                        mConnection.connect();
                    } catch (IOException e) {
                        Intent i = null;
                        i = new Intent(ZConnectionService.UI_NOTCONNECTED);
                        i.setPackage(getApplicationContext().getPackageName());
                        getApplicationContext().sendBroadcast(i);

                        e.printStackTrace();

                        // Stop the services all together.
                        stopSelf();
                    }

                    Looper.loop();
                }
            });

            mThread.start();
        }
    }
}
</code>```

I expect that both tests should pass without any problem. In fact, both tests are passed when I ran them individually, but they fail when I run the whole suite and the error is:

```<code>Wanted but not invoked:
mockedZinkConnection.connect();
-> at com.app.z.ZConnectionServiceUnitTest.test_onStart_throw_IO_exceptioon(ZConnectionServiceUnitTest.java:207)
Actually, there were zero interactions with this mock.
</code>```

答:
I think the issue is a multithreading one.
When you call initConnection, it calls mConnection.connect() in a Thread
The problem you are having is that this Thread takes some time to complete and you end up calling verify(mockedZConnection, times(1)).connect(); before the Thread actually reached the connect() call.
A way to make sure about it is to join the Thread after you start it, it will wait until the Thread has finished before continuing:

```<code>mThread.start();
try {
    mThread.join();
} catch (InterruptedException i) {
    i.printStackTrace();

}
</code>```

Now both tests should work.

This of course is not acceptable in the code, because it negated the use of a Thread. You will need an other way to test it.

A way I can think of would be to wait for the Thread to complete in your test before checking the mock:

```<code>@Test
public void test_onStart_throw_IO_exceptioon() throws Exception {
    ZConnectionService zConnectionService = new ZConnectionService();
    ZConnection mockedZConnection = mock(ZConnection.class);
    doNothing().when(mockedZConnection).connect();

    zConnectionService.initConnection(mockedZConnection);

    // Wait for the Thread to complete
    while(zConnectionService.mThread.isAlive()) {
        Thread.sleep(100);
    }
    verify(mockedZConnection, times(1)).connect();
}
</code>```

Tried and it works fine for me. Not sure it is a best practice though as you need to make public some internals of your class, which violates encapsulation

maybe having a package protected isThreadAlive() method on your ZConnectionService class could be acceptable

```<code>boolean isThreadAlive() {
    return mThread.isAlive();
}
</code>```

and the loop in the test

```<code>while(zConnectionService.isThreadAlive()) {
    Thread.sleep(100);
}
</code>```

Body:
I am using Mockito together to JUnit to implement unit tests for a class in an Android project.The problem is that I call Mockito.verify in two consequent tests where the tests are exactly same (to make sure that I am using Mockito correctly) but the interesting thing is that verify in second test always fails.I suspect that some operations need to be done before each test using @before annotation or so, that I have missed.Here are some code snippet about what I am doing.

I use Android Studio 3.4.1, Mockito 2.7.22 and JUnit 4.12.

@Test
public void test_onStart_do_nothing() throws Exception {
    ZConnectionService zConnectionService = new ZConnectionService();
    ZConnection mockedZConnection = mock(ZConnection.class);

    doNothing().when(mockedZConnection).connect();
    zConnectionService.initConnection(mockedZConnection);

    verify(mockedZConnection, times(1)).connect();
}

@Test
public void test_onStart_throw_IO_exceptioon() throws Exception {
    ZConnectionService zConnectionService = new ZConnectionService();
    ZConnection mockedZConnection = mock(ZConnection.class);

    doNothing().when(mockedZConnection).connect();
    zConnectionService.initConnection(mockedZConnection);
    // Line above is the line that error message points to!

    verify(mockedZConnection, times(1)).connect();
}

Here comes the function under test

public void initConnection(ZConnection connection) {
    Log.d(TAG,"initConnection()");

    if (mConnection == null) {
        mConnection = connection;
    }

    if (!mActive) {
        mActive = true;

        if (mThread == null || !mThread.isAlive()) {
            mThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // The code here runs in a background thread.
                    Looper.prepare();
                    mTHandler = new Handler();

                    try {
                        mConnection.connect();
                    } catch (IOException e) {
                        Intent i = null;
                        i = new Intent(ZConnectionService.UI_NOTCONNECTED);
                        i.setPackage(getApplicationContext().getPackageName());
                        getApplicationContext().sendBroadcast(i);

                        e.printStackTrace();

                        // Stop the services all together.
                        stopSelf();
                    }

                    Looper.loop();
                }
            });

            mThread.start();
        }
    }
}

I expect that both tests should pass without any problem. In fact, both tests are passed when I ran them individually, but they fail when I run the whole suite and the error is:

Wanted but not invoked:
mockedZinkConnection.connect();
-> at com.app.z.ZConnectionServiceUnitTest.test_onStart_throw_IO_exceptioon(ZConnectionServiceUnitTest.java:207)
Actually, there were zero interactions with this mock.

Body:
I think the issue is a multithreading one.
When you call initConnection, it calls mConnection.connect() in a Thread
The problem you are having is that this Thread takes some time to complete and you end up calling verify(mockedZConnection, times(1)).connect(); before the Thread actually reached the connect() call.
A way to make sure about it is to join the Thread after you start it, it will wait until the Thread has finished before continuing:

mThread.start();
try {
    mThread.join();
} catch (InterruptedException i) {
    i.printStackTrace();

}

Now both tests should work.

This of course is not acceptable in the code, because it negated the use of a Thread. You will need an other way to test it.

A way I can think of would be to wait for the Thread to complete in your test before checking the mock:

@Test
public void test_onStart_throw_IO_exceptioon() throws Exception {
    ZConnectionService zConnectionService = new ZConnectionService();
    ZConnection mockedZConnection = mock(ZConnection.class);
    doNothing().when(mockedZConnection).connect();

    zConnectionService.initConnection(mockedZConnection);

    // Wait for the Thread to complete
    while(zConnectionService.mThread.isAlive()) {
        Thread.sleep(100);
    }
    verify(mockedZConnection, times(1)).connect();
}

Tried and it works fine for me. Not sure it is a best practice though as you need to make public some internals of your class, which violates encapsulation

maybe having a package protected isThreadAlive() method on your ZConnectionService class could be acceptable

boolean isThreadAlive() {
    return mThread.isAlive();
}

and the loop in the test

while(zConnectionService.isThreadAlive()) {
    Thread.sleep(100);
}


问:
How can I get all possible combinations of element in set? (power set)
I have a array of number:

```<code>$numbers = array(1,2,3);
</code>```

The order does not mean anything.  If the numbers given were 1, 2 and 3, then I would want to receive this as a result:

```<code>1
2
3
1 2
1 3
2 3
1 2 3
</code>```

How can I achieve that?

答:
Partially solved with:

PHP: How to get all possible combinations of 1D array?

Then added my own function to clean it up:

```<code>        function clean_depth_picker(&$result) {
                $results = array();
                foreach($result as $value) {
                        if ( substr_count($value, " ") == 0 ) {
                                $results[] = $value;
                        } else {
                                $arr = explode(" ", $value);
                                sort($arr);
                                $key = implode(" ", $arr);
                                if ( !in_array($key, $results) )
                                        $results[] = $key;
                        }
                }
                $result = $results;
        }
</code>```

Body:
I have a array of number:

$numbers = array(1,2,3);

The order does not mean anything.  If the numbers given were 1, 2 and 3, then I would want to receive this as a result:

1
2
3
1 2
1 3
2 3
1 2 3

How can I achieve that?

Body:
Partially solved with:

PHP: How to get all possible combinations of 1D array?

Then added my own function to clean it up:

        function clean_depth_picker(&$result) {
                $results = array();
                foreach($result as $value) {
                        if ( substr_count($value, " ") == 0 ) {
                                $results[] = $value;
                        } else {
                                $arr = explode(" ", $value);
                                sort($arr);
                                $key = implode(" ", $arr);
                                if ( !in_array($key, $results) )
                                        $results[] = $key;
                        }
                }
                $result = $results;
        }


问:
I need help replacing Application.Find with a new function for this old macro
I have an old 2003 xls macro that extracts data from all excel dump files in an "inbox" type subfolder. The files are generated daily and as far as I can tell from this old code, the Application.Find looks up all files it can find in this inbox and then goes through them one by one to sort the data and place it properly in the main document.

The problem of course is that Application.Find is used and does not exist in Excel anymore, requiring the use of the old Excel version to execute this macro. It's a pain to have to run an old version for the import of data and then a new version for all the other needs so I was hoping I could get some help to replace this old code with a new function that serves the same role.

I've looked around here and other places for peoples functions to find x amount of files in a given location and go through them one by one but I am not all that good at trying to integrate these more modern solutions with this older macro as it already has a structure in place to loop until all the Application.Find results have been completed.

I tried a Dir approach but was unsuccessful and I can't manage to get a filecount/array thing going so it can just work through whatever it finds in that subfolder.

```<code>With Application.FileSearch
    .NewSearch
    .LookIn = inbox
    .SearchSubFolders = False
    .FileType = msoFileTypeExcelWorkbooks
    If .Execute() > 0 Then
        Set basebook = ThisWorkbook
        For i = 1 To .FoundFiles.Count
            Set mybook = Workbooks.Open(.FoundFiles(i))
</code>```

The expected result is that this can loop harmlessly when executed since further down in the code after having gone through the data in the opened document, it will ask for the Next i and keep going until running out of files. However, as Application.Find no longer exists, it just stops at that point with the expected error message unless I run the 2003 version.

Any help at all would be really appreciated!

答:
This is how I loop through all the files in a folder:

```<code>Option Explicit
Sub Test()

    Dim FilePath As String, FileName As String
    Dim wb As Workbook

    FilePath = "Your Path"
    FileName = Dir(FilePath & "*.xls*")

    Do While FileName <> ""
        Set wb = Workbooks.Open(FilePath & FileName, UpdateLinks:=False, ReadOnly:=True)

        'Your Code

        FileName = Dir
    Loop

End Sub
</code>```

In this case, as you can see, looking for any file which extension containts xls so... xls, xlsx, xlsm, xlsb...

Hope it helps

Body:
I have an old 2003 xls macro that extracts data from all excel dump files in an "inbox" type subfolder. The files are generated daily and as far as I can tell from this old code, the Application.Find looks up all files it can find in this inbox and then goes through them one by one to sort the data and place it properly in the main document.

The problem of course is that Application.Find is used and does not exist in Excel anymore, requiring the use of the old Excel version to execute this macro. It's a pain to have to run an old version for the import of data and then a new version for all the other needs so I was hoping I could get some help to replace this old code with a new function that serves the same role.

I've looked around here and other places for peoples functions to find x amount of files in a given location and go through them one by one but I am not all that good at trying to integrate these more modern solutions with this older macro as it already has a structure in place to loop until all the Application.Find results have been completed.

I tried a Dir approach but was unsuccessful and I can't manage to get a filecount/array thing going so it can just work through whatever it finds in that subfolder.

With Application.FileSearch
    .NewSearch
    .LookIn = inbox
    .SearchSubFolders = False
    .FileType = msoFileTypeExcelWorkbooks
    If .Execute() > 0 Then
        Set basebook = ThisWorkbook
        For i = 1 To .FoundFiles.Count
            Set mybook = Workbooks.Open(.FoundFiles(i))

The expected result is that this can loop harmlessly when executed since further down in the code after having gone through the data in the opened document, it will ask for the Next i and keep going until running out of files. However, as Application.Find no longer exists, it just stops at that point with the expected error message unless I run the 2003 version.

Any help at all would be really appreciated!

Body:
This is how I loop through all the files in a folder:

Option Explicit
Sub Test()

    Dim FilePath As String, FileName As String
    Dim wb As Workbook

    FilePath = "Your Path"
    FileName = Dir(FilePath & "*.xls*")

    Do While FileName <> ""
        Set wb = Workbooks.Open(FilePath & FileName, UpdateLinks:=False, ReadOnly:=True)

        'Your Code

        FileName = Dir
    Loop

End Sub

In this case, as you can see, looking for any file which extension containts xls so... xls, xlsx, xlsm, xlsb...

Hope it helps


问:
Job queue with job affinity
I am currently facing a problem for which I am pretty sure there is an official name, but I don't know what to search the web for. I hope that if I describe the problem and the solution I have in mind, somebody is able to tell me the name of the design pattern (if there is one that matches what I am going to describe).

Basically, what I want to have is a job queue: I have multiple clients that create jobs (publishers), and a number of workers that process these jobs (consumers). Now I want to distribute the jobs created by the publishers to the various consumers, which is basically doable using almost any message queue with load balancing across a queue, e.g. using RabbitMQ or even MQTT 5.

However, now things get complicated... every job refers to an external entity, let's say a user. What I want is that the jobs for a single user get processed in order, but for multiple users in parallel. I do not have the requirement that the jobs for user X always go to worker Y, since they should be processed sequentially anyway.

Now I could solve this using RabbitMQ and its consistent hashing exchange, but then I have a data race when new workers enter the cluster, because RabbitMQ does not support re-locating the jobs that are already in a queue.

MQTT 5 does not support this either: Here this idea is known as "sticky shared subscriptions", but this is not official. It may be part of MQTT 6, or it may not. Who knows.

I have also taken a look at NSQ, NATS, and some other brokers. Most of them don't even support this very specific scenario, and those that do use consistent hashing, which has the previously mentioned data racing problem.

Now, the problem would be gone if the broker would not sort the jobs into queues, once the jobs arrive, but if it would track if a job for a specific user is already being processed: If so, it should delay all other jobs for this user, but all jobs for other users should still process. This is, AFAICS, not possible using RabbitMQ et al.

I am pretty sure that I am not the only person with a use case for that. I could e.g. think of users uploading videos to a video platform, and although uploaded videos are processed in parallel, all the videos uploaded by a single user are processed sequentially.

So, to cut a long story short: Is what I describe known under a common name? Something such as distributed job queue? Task dispatcher with task affinity? Or anything else? I have tried lots of terms, but didn't succeed. This may mean that there is no solution for this, but as said, it's hard to imagine that I'm the only person on the planet with this problem.

Any ideas what I could look for? And: Are there any tools that implement this? Any protocols?

PS: Just using a predefined routing key is not an option, since the user ids (which I just used as a made-up example here) are basically UUIDs, so there can be billions of it, so I need something more dynamic. Hence, consistent hashing is basically the correct approach, but as said, the distribution has to work piece by piece, not upfront, to avoid data races.

答:
what I want to have is a job queue: I have multiple clients that create jobs (publishers), and a number of workers that process these jobs (consumers). Now I want to distribute the jobs created by the publishers to the various consumers, which is basically doable using almost any message queue with load balancing across a queue, e.g. using RabbitMQ or even MQTT 5.

However, now things get complicated... every job refers to an external entity, let's say a user. What I want is that the jobs for a single user get processed in order, but for multiple users in parallel. I do not have the requirement that the jobs for user X always go to worker Y, since they should be processed sequentially anyway.

Evenif it was not this particular use case, I did a survey of (dynamic) task scheduling [0] [1] a couple month ago and nothing like that surfaced.

Every scheduling algorithm I read about have some properties that are common to all other tasks like priority, age, enqueue time, task name (and by extension average time to process). If you tasks were all linked to a user you could build a scheduler that takes user_id into account to pick task from the queue.

But I guess, you don't want to build your own scheduler, anyway it would be waste because, from experience with such need, existing message queues allow to implement your requirement.

To summarize your requirements you need:

A scheduler that run only one task per user at the same time.

The solution is to use a distributed lock, something like REDIS distlock and acquire the lock before the task starts and refresh it regularly during the task execution. If a new task for the same user comes in and try to execute it will fail to acquire the lock and will be re-enqueued.

Here is a pseudo-code:

```<code>def my_task(user_id, *args, **kwargs):
    if app.distlock(user_id, blocking=False):
        exec_my_task(user_id, *args, **kwargs)
    else:
        raise RetryTask()
</code>```

Don't forget to refresh and release the lock.

A similar approach is taken to enforce robots.txt delay between every requests in crawlers.

Title: Job queue with job affinity

Body:
what I want to have is a job queue: I have multiple clients that create jobs (publishers), and a number of workers that process these jobs (consumers). Now I want to distribute the jobs created by the publishers to the various consumers, which is basically doable using almost any message queue with load balancing across a queue, e.g. using RabbitMQ or even MQTT 5.

However, now things get complicated... every job refers to an external entity, let's say a user. What I want is that the jobs for a single user get processed in order, but for multiple users in parallel. I do not have the requirement that the jobs for user X always go to worker Y, since they should be processed sequentially anyway.

Evenif it was not this particular use case, I did a survey of (dynamic) task scheduling [0] [1] a couple month ago and nothing like that surfaced.

Every scheduling algorithm I read about have some properties that are common to all other tasks like priority, age, enqueue time, task name (and by extension average time to process). If you tasks were all linked to a user you could build a scheduler that takes user_id into account to pick task from the queue.

But I guess, you don't want to build your own scheduler, anyway it would be waste because, from experience with such need, existing message queues allow to implement your requirement.

To summarize your requirements you need:

A scheduler that run only one task per user at the same time.

The solution is to use a distributed lock, something like REDIS distlock and acquire the lock before the task starts and refresh it regularly during the task execution. If a new task for the same user comes in and try to execute it will fail to acquire the lock and will be re-enqueued.

Here is a pseudo-code:

def my_task(user_id, *args, **kwargs):
    if app.distlock(user_id, blocking=False):
        exec_my_task(user_id, *args, **kwargs)
    else:
        raise RetryTask()

Don't forget to refresh and release the lock.

A similar approach is taken to enforce robots.txt delay between every requests in crawlers.


答:
You need to rewrite ngClass like [ngClass]="{'class': true}"

In your code, you have to write ngClass as below

```<code>  <span class="row-icon" [ngClass]="{'pdf-class': doc.document_ext == 'pdf'}">
    {{doc.document_ext}}
  </span>
</code>```

Live Demo

Title: Use NgClass with a custom Pipe

Body:
You need to rewrite ngClass like [ngClass]="{'class': true}"

In your code, you have to write ngClass as below

  <span class="row-icon" [ngClass]="{'pdf-class': doc.document_ext == 'pdf'}">
    {{doc.document_ext}}
  </span>

Live Demo


问:
Error The type or namespace name 'name of my tables' could not be found()are you missing a ussing directive or an assembly refrence?)
I get this error (The type or namespace name 'name of my tables' could not be found()are you missing a ussing directive or an assembly refrence?)) in Context.cs file when i compile my ASP.NET MVC2 Web Application. I follow these guide http://subsonicproject.com/docs/Setting_up_SubSonic_3.0 but i cant solve this problem.</p>

答: I have seen this error after I made customizations to SQLServer.ttinclude to include only certain tables, but for which I forgot to make corresponding changes in ActiveRecord.tt. If you are just setting up and have made no modifications, probably you are not seeing the error for the same reason. But maybe try reloading your .tt and .ttinclude files from the SubSonic distribution so you are sure you didn't accidentally modify them (other than setting connection string etc.).</p>


问:
Vue: Using material-design-icons offline / size
I am using materialdesignicons in my vue project.

```<code>require ('../node_modules/@mdi/font/css/materialdesignicons.min.css);
Vue.use(Vuetify, {iconfont:'mdi'});
</code>```

I have a handful of icons which I dynamically create:

```<code> <v-icon>{{ some-mdi-file }}</v-icon>
</code>```

When I build for production via (npm run build) I get the following error:

```<code>asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  img/materialdesignicons-webfont.someHash.svg (3.77 MiB)
</code>```

That file size is huge because it includes every icon, regardless of whether it's being used. Is there a way to trim that file size down by only packaging the specific icons used. Is there a different package I should be using? Caveat: The project is hosted offline, so I need to include the fonts directly in my project.

I looked at vue-material-design-icons but it looks like it may not work for dynamic icon names and it says nothing about the overall file size/performance.

I have also looked here but clicking on the 'size warning' link brings me to a page where the Vue portion is not filled out
https://dev.materialdesignicons.com/getting-started/webfont

答:
I would recommend using the @mdi/js package for this which provides SVG paths for each icon and supports tree shaking. Currently Vuetify doesn't support SVG icons but it should in the future.

For now, it's easy enough to create a custom icon component:

```<code><template>
    <svg :class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
        <path :d="path" />
    </svg>
</template>

<script>
export default {
    name: 'my-icon',

    data: () => ({
        path: '',
    }),

    methods: {
        updatePath() {
            if (!this.$scopedSlots) return
            if (typeof this.$scopedSlots.default !== 'function') return

            this.path = this.$scopedSlots
                .default()
                .map((n) => n.text)
                .join('')
        },
    },

    mounted() {
        this.updatePath()
    },

    updated() {
        this.updatePath()
    },
}
</script>

<style scoped>
.icon {
    display: block;
    color: inherit;
    fill: currentColor;
    width: 24px;
    height: 24px;
}
<style>
</code>```

Then to use it you just need to import your component and the icon you want to use:

```<code><template>
    <div class="app">
        <my-icon>{{mdiCheck}}</my-icon>
    </div>
</template>

<script>
import MyIcon from 'path/to/my/icon.vue'
import { mdiCheck } from '@mdi/js'

export default {
    name: 'my-app',

    components: {
        MyIcon,
    }

    data: () => ({
        mdiCheck,
    }),
}
</script>
</code>```

Body:
I am using materialdesignicons in my vue project.

require ('../node_modules/@mdi/font/css/materialdesignicons.min.css);
Vue.use(Vuetify, {iconfont:'mdi'});

I have a handful of icons which I dynamically create:

 <v-icon>{{ some-mdi-file }}</v-icon>

When I build for production via (npm run build) I get the following error:

asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  img/materialdesignicons-webfont.someHash.svg (3.77 MiB)

That file size is huge because it includes every icon, regardless of whether it's being used. Is there a way to trim that file size down by only packaging the specific icons used. Is there a different package I should be using? Caveat: The project is hosted offline, so I need to include the fonts directly in my project.

I looked at vue-material-design-icons but it looks like it may not work for dynamic icon names and it says nothing about the overall file size/performance.

I have also looked here but clicking on the 'size warning' link brings me to a page where the Vue portion is not filled out
https://dev.materialdesignicons.com/getting-started/webfont

Body:
I would recommend using the @mdi/js package for this which provides SVG paths for each icon and supports tree shaking. Currently Vuetify doesn't support SVG icons but it should in the future.

For now, it's easy enough to create a custom icon component:

<template>
    <svg :class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
        <path :d="path" />
    </svg>
</template>

<script>
export default {
    name: 'my-icon',

    data: () => ({
        path: '',
    }),

    methods: {
        updatePath() {
            if (!this.$scopedSlots) return
            if (typeof this.$scopedSlots.default !== 'function') return

            this.path = this.$scopedSlots
                .default()
                .map((n) => n.text)
                .join('')
        },
    },

    mounted() {
        this.updatePath()
    },

    updated() {
        this.updatePath()
    },
}
</script>

<style scoped>
.icon {
    display: block;
    color: inherit;
    fill: currentColor;
    width: 24px;
    height: 24px;
}
<style>

Then to use it you just need to import your component and the icon you want to use:

<template>
    <div class="app">
        <my-icon>{{mdiCheck}}</my-icon>
    </div>
</template>

<script>
import MyIcon from 'path/to/my/icon.vue'
import { mdiCheck } from '@mdi/js'

export default {
    name: 'my-app',

    components: {
        MyIcon,
    }

    data: () => ({
        mdiCheck,
    }),
}
</script>


问:
C# WPF - Tasks vs Multithreading, and updating UI components from them
So basically I'm using C# to write a port scanning WPF application, that will scan over a thousand combinations of ports and IPs (x.x.x.x:xx). As a result, I have to split this process up into multiple threads to quicken the process and avoid making the UI freeze. Shown below is my code for the MainWindow:

```<code>namespace PortScannerTool
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            tb_portstatus.Text = "Click the button to query ports";
            dns_info.Text = tb_portstatus.Text;
        }

        private void Btn1_Click(object sender, RoutedEventArgs e)
        {

            CmdExec cmdobj = new CmdExec("127.0.0.0","8080");
            Thread query_status = new Thread(cmdobj.Runcmd);
            query_status.Start();
            tb_portstatus.Text = "Done!";
        }
    }
}
</code>```

```<code>namespace PortQueryApp
{
    class CmdExec
    {

        string command;
        public string dnsText;
        public string querystatusText;

        public CmdExec(string ip, string port)
        {
           this.command = $"-n {ip} -o {port}";
        }

        public void Runcmd()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "PortQry.exe";
            proc.StartInfo.Arguments = this.command;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            string query_output = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            string resolve_pass = "Name resolved";
            string resolve_fail = "Failed to resolve IP address to name";

            if (query_output.Contains(resolve_pass))
            {
                this.dnsText = "Resolved!";
            }
            if (query_output.Contains(resolve_fail))
            {
                this.dnsText = "Resolve Failed!";
            }

            this.querystatusText = "Done!";

        }
    }
}
</code>```

dns_info and tb_portstatus are XAML Textboxes. CmdExec.Rumcmd is the method that does the actual port scanning itself. If you look at the CmdExec class, PortQry.exe is the microsoft port query tool.

So I want to get the cmdobj.Runcmd method to update the UI once it's done running. But I don't know how to do so, I've Googled this extensively, and I'm getting some people suggesting using delegates, Tasks and BackgroundWorkers, not sure which method would be best for my case.

Could anyone give some suggestions or point me to any guides? That'd be awesome! Thanks!

Edit: Most examples have their Multithreaded method within the same class as well. I'm not sure if this is required, but should I use:

```<code> class CmdExec : MainWindow
{
   //Do stuff
}
</code>```

instead?

答:
You should use Threadless async (at least no managed threads).

You can await the work done the process with a custom awaiter. The work to do this is pretty involved. Luckily someone has already done this.

```<code>PM> Install-Package RunProcessAsTask
</code>```

Then your code just becomes

```<code>    public async Task<bool> Runcmd()
    {
        ProcessResults results = await ProcessEx.RunAsync(
            "PortQry.exe",
             command
        );
        if(results.StandardOutput.Any(output => output.Contains(resolve_pass)))
           return true;
        return false;
    }
</code>```

Body:
So basically I'm using C# to write a port scanning WPF application, that will scan over a thousand combinations of ports and IPs (x.x.x.x:xx). As a result, I have to split this process up into multiple threads to quicken the process and avoid making the UI freeze. Shown below is my code for the MainWindow:

namespace PortScannerTool
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            tb_portstatus.Text = "Click the button to query ports";
            dns_info.Text = tb_portstatus.Text;
        }

        private void Btn1_Click(object sender, RoutedEventArgs e)
        {

            CmdExec cmdobj = new CmdExec("127.0.0.0","8080");
            Thread query_status = new Thread(cmdobj.Runcmd);
            query_status.Start();
            tb_portstatus.Text = "Done!";
        }
    }
}

namespace PortQueryApp
{
    class CmdExec
    {

        string command;
        public string dnsText;
        public string querystatusText;

        public CmdExec(string ip, string port)
        {
           this.command = $"-n {ip} -o {port}";
        }

        public void Runcmd()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "PortQry.exe";
            proc.StartInfo.Arguments = this.command;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            string query_output = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            string resolve_pass = "Name resolved";
            string resolve_fail = "Failed to resolve IP address to name";

            if (query_output.Contains(resolve_pass))
            {
                this.dnsText = "Resolved!";
            }
            if (query_output.Contains(resolve_fail))
            {
                this.dnsText = "Resolve Failed!";
            }

            this.querystatusText = "Done!";

        }
    }
}

dns_info and tb_portstatus are XAML Textboxes. CmdExec.Rumcmd is the method that does the actual port scanning itself. If you look at the CmdExec class, PortQry.exe is the microsoft port query tool.

So I want to get the cmdobj.Runcmd method to update the UI once it's done running. But I don't know how to do so, I've Googled this extensively, and I'm getting some people suggesting using delegates, Tasks and BackgroundWorkers, not sure which method would be best for my case.

Could anyone give some suggestions or point me to any guides? That'd be awesome! Thanks!

Edit: Most examples have their Multithreaded method within the same class as well. I'm not sure if this is required, but should I use:

 class CmdExec : MainWindow
{
   //Do stuff
}

instead?

Body:
You should use Threadless async (at least no managed threads).

You can await the work done the process with a custom awaiter. The work to do this is pretty involved. Luckily someone has already done this.

PM> Install-Package RunProcessAsTask

Then your code just becomes

    public async Task<bool> Runcmd()
    {
        ProcessResults results = await ProcessEx.RunAsync(
            "PortQry.exe",
             command
        );
        if(results.StandardOutput.Any(output => output.Contains(resolve_pass)))
           return true;
        return false;
    }


问:
what functions are called when clicking on the titlebar of a form?
I have a form which includes an Unity process. Sometimes "something" happens that makes impossible to perform some actions on the process.
I discovered that clicking on the titlebar re-enables the possibility to perform the actions that i want on my process.

the "something" is my function:

```<code>private void button1_Click(object sender, EventArgs e)
        {
            myNCServer.SendMessage();
            myNCServer.SendMyObject();

            position = myNCServer.GetPosition();
            compteur++;
            unityHWNDLabel.Text = "position = " + position + " (Updated " + compteur + " times)";

        }
</code>```

so i would like to know what really happens so that i can re-enable my process without clicking on the titlebar

or if you have any other idea on how to handle this... =)

thanks a lot !

答:
```<code>    private const int WM_ACTIVATE = 0x0006;
    private readonly IntPtr WA_ACTIVE = new IntPtr(1);

    private void button1_Click(object sender, EventArgs e)
    {
        things();

        SendMessage(unityHWND, WM_ACTIVATE, WA_ACTIVE, IntPtr.Zero);
    }
</code>```

did the trick

thank you @Kr15

Body:
I have a form which includes an Unity process. Sometimes "something" happens that makes impossible to perform some actions on the process.
I discovered that clicking on the titlebar re-enables the possibility to perform the actions that i want on my process.

the "something" is my function:

private void button1_Click(object sender, EventArgs e)
        {
            myNCServer.SendMessage();
            myNCServer.SendMyObject();

            position = myNCServer.GetPosition();
            compteur++;
            unityHWNDLabel.Text = "position = " + position + " (Updated " + compteur + " times)";

        }

so i would like to know what really happens so that i can re-enable my process without clicking on the titlebar

or if you have any other idea on how to handle this... =)

thanks a lot !

Body:
    private const int WM_ACTIVATE = 0x0006;
    private readonly IntPtr WA_ACTIVE = new IntPtr(1);

    private void button1_Click(object sender, EventArgs e)
    {
        things();

        SendMessage(unityHWND, WM_ACTIVATE, WA_ACTIVE, IntPtr.Zero);
    }

did the trick

thank you @Kr15


问:
Get array value using Angular Dropdown
I am trying to use Angular Dropdown. The JSON is as follows-

```<code>{
       {
      "bookId":"1",
      "authors":{ "author1", "author2"}
       }
       {
      "bookId":"2",
      "authors":{ "author2", "author3"}
       }
}
</code>```

Have created a class named Book which stores the above values in Book Array named books.

In html code have the following -

```<code> <select [(ngModel)]="book.id" (ngModelChange)='onBookSelected($event)'>
            <option *ngFor="let book of books"
            [value] = "book.authors">{{book.id}}</option>
          </select>
</code>```

In the component have the onBookSelected as follows-

```<code>onBookSelected(val: any)
{
  console.log(val);
}
</code>```

I dont get the list of authors but get

```<code>[object Object],[object Object],[object Object]
</code>```

I also tried creating an array of class author and using it as follows-

```<code>onBookSelected(authorList : any)
{
  console.log(authorList );
}
</code>```

But get same output as

```<code>   [object Object],[object Object],[object Object]
</code>```

Could someone please help to get list of authors when the book is selected from the dropdown. Thanks

答:
Whats wrong with that? Authors is an Object. However it think you wanted it to be an array

```<code>  "authors":[ "author1", "author2"]
</code>```

That would print normally in the console.

if you do

```<code>onBookSelected(authorList : any)
{
  console.log(JSON.stringify(authorList));
}
</code>```

it will print what you expected.

Title: Get array value using Angular Dropdown

Body:
I am trying to use Angular Dropdown. The JSON is as follows-

{
       {
      "bookId":"1",
      "authors":{ "author1", "author2"}
       }
       {
      "bookId":"2",
      "authors":{ "author2", "author3"}
       }
}

Have created a class named Book which stores the above values in Book Array named books.

In html code have the following -

 <select [(ngModel)]="book.id" (ngModelChange)='onBookSelected($event)'>
            <option *ngFor="let book of books"
            [value] = "book.authors">{{book.id}}</option>
          </select>

In the component have the onBookSelected as follows-

onBookSelected(val: any)
{
  console.log(val);
}

I dont get the list of authors but get

[object Object],[object Object],[object Object]

I also tried creating an array of class author and using it as follows-

onBookSelected(authorList : any)
{
  console.log(authorList );
}

But get same output as

   [object Object],[object Object],[object Object]

Could someone please help to get list of authors when the book is selected from the dropdown. Thanks

Body:
Whats wrong with that? Authors is an Object. However it think you wanted it to be an array

  "authors":[ "author1", "author2"]

That would print normally in the console.

if you do

onBookSelected(authorList : any)
{
  console.log(JSON.stringify(authorList));
}

it will print what you expected.


问:
Dropdown menu does not select model
I want to create task model that has many required courses. But when I create a task, the dropdown menu does not attach any courses to it. (As in Task.first.courses returns nil and the course_id attribute is also nil).

Task Controller:

```<code>before_action :authenticate_company!, only: [:create, :destroy]
def create
  @courses = Course.all
  @task = current_company.tasks.build(task_params)
  if @task.save
    flash[:success] = "Task created!"
    redirect_to @task
  else
    render 'new'
  end
end

def new
  @courses = Course.all
  @task = Task.new
end

private

  def task_params
    params.require(:task).permit(:name, :description, files: [])
  end
</code>```

Course Model:

```<code>belongs_to :task, optional: true
</code>```

Task Model:

```<code>has_many :courses
</code>```

Add_task_id_to_courses Migration:

```<code>def change
  add_column :courses, :task_id, :integer
end
</code>```

Add_course_id_to_tasks Migration:

```<code>def change
  add_column :tasks, :course_id, :integer
end
</code>```

Tasks/new.html.erb:

```<code><%= form_for(@task) do |f| %>
  <div class="field">
    <%= f.text_area :name, placeholder: "Task Name" %>
  </div>
  <div class="field">
    <%= f.text_area :description, placeholder: "Add Description" %>
  </div>
  <div class="field">
    <%= f.file_field :files, multiple: true %>
  </div>
  <div class="field">
    <%= f.collection_select :course_ids, @courses, :id, :name, {include_blank: true}, {multiple: true} %>
  </div>
  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
</code>```

答:
Course belongs_to :task, Task has_many :courses. It means that you need only task_id in courses table. Remove course_id from tasks table. course_ids is a method, generated from has_many association, not a column name.

But it is not the cause of the issue. You forgot to add course_ids to permitted params.

```<code>def task_params
  params.require(:task).permit(:name, :description, files: [], course_ids: [])
end
</code>```

Don't forget to check server logs when something goes wrong. Now you should see there something like Unpermitted parameters: course_ids

Title: Dropdown menu does not select model

Body:
I want to create task model that has many required courses. But when I create a task, the dropdown menu does not attach any courses to it. (As in Task.first.courses returns nil and the course_id attribute is also nil).

Task Controller:

before_action :authenticate_company!, only: [:create, :destroy]
def create
  @courses = Course.all
  @task = current_company.tasks.build(task_params)
  if @task.save
    flash[:success] = "Task created!"
    redirect_to @task
  else
    render 'new'
  end
end

def new
  @courses = Course.all
  @task = Task.new
end

private

  def task_params
    params.require(:task).permit(:name, :description, files: [])
  end

Course Model:

belongs_to :task, optional: true

Task Model:

has_many :courses

Add_task_id_to_courses Migration:

def change
  add_column :courses, :task_id, :integer
end

Add_course_id_to_tasks Migration:

def change
  add_column :tasks, :course_id, :integer
end

Tasks/new.html.erb:

<%= form_for(@task) do |f| %>

    <%= f.text_area :name, placeholder: "Task Name" %>

    <%= f.text_area :description, placeholder: "Add Description" %>

    <%= f.file_field :files, multiple: true %>

    <%= f.collection_select :course_ids, @courses, :id, :name, {include_blank: true}, {multiple: true} %>

  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

Body:
Course belongs_to :task, Task has_many :courses. It means that you need only task_id in courses table. Remove course_id from tasks table. course_ids is a method, generated from has_many association, not a column name.

But it is not the cause of the issue. You forgot to add course_ids to permitted params.

def task_params
  params.require(:task).permit(:name, :description, files: [], course_ids: [])
end

Don't forget to check server logs when something goes wrong. Now you should see there something like Unpermitted parameters: course_ids


问:
How to do the key and value output from the dictionary in the label?
There are 10 labels and a dictionary which consists of the key-name of the player, a label-record (in seconds).

The first 5 labels are made under the names (ie, as a table of records), and the remaining 5 labels under the results.

I need to derive this data from the dictionary and sort it by label, the less seconds, the higher the person in the ranking.

It is necessary to do something so that the player, who in the first place displays his name and result.

10 labels in the table are arranged like this (I am writing the label numbers):

```<code>label18 label28

label19 label29

label20 label30

label21 label31

label22 label32
</code>```

There is also a code for how to make a dictionary (it may be useful):

```<code>private static Dictionary<string, int> AllNames()
    {
        return File
          .ReadLines(@"C:\Users\HP\Desktop\картинки\results.txt")
          .Where(line => string.IsNullOrWhiteSpace(line))
          .Select(item => item.Split(' '))
          .ToDictionary(items => items[0],
                        items => int.Parse(items[1]));
    }
</code>```

This should all happen by clicking on the button: "Show rating", which is on this form.

答:
Providing that you want put names into label18..labe22 and values into label28..label32 a simple Linq should do

```<code> using System.Linq;

 ...

 private void updateRatingLabels() {
   var tops = AllNames()
     .OrderBy(pair => pair.Value)                      // less seconds - better rank
     .ThenBy(pair => pair.Key, StringComparer.Ordinal) // On tie, use names
     .Take(5)                                          // Top 5 or less
     .ToArray();

   // Clear all the labels
   for (int i = 18; i <= 22; ++i)
     Controls.Find($"label{i}", true).First().Text = "";

   for (int i = 28; i <= 32; ++i)
     Controls.Find($"label{i}", true).First().Text = "";

   // Put best results
   for (int i = 0; i < tops.Length; ++i) {
     Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
     Controls.Find($"label{i + 28}", true).First().Text = tops[i].Value.ToString();
   }
 }
</code>```

Then

```<code>  private void buttonShow_Rating_Click(object sender, EventArgs e) {
    updateRatingLabels();
  }
</code>```

Body:
There are 10 labels and a dictionary which consists of the key-name of the player, a label-record (in seconds).

The first 5 labels are made under the names (ie, as a table of records), and the remaining 5 labels under the results.

I need to derive this data from the dictionary and sort it by label, the less seconds, the higher the person in the ranking.

It is necessary to do something so that the player, who in the first place displays his name and result.

10 labels in the table are arranged like this (I am writing the label numbers):

label18 label28

label19 label29

label20 label30

label21 label31

label22 label32

There is also a code for how to make a dictionary (it may be useful):

private static Dictionary<string, int> AllNames()
    {
        return File
          .ReadLines(@"C:\Users\HP\Desktop\картинки\results.txt")
          .Where(line => string.IsNullOrWhiteSpace(line))
          .Select(item => item.Split(' '))
          .ToDictionary(items => items[0],
                        items => int.Parse(items[1]));
    }

This should all happen by clicking on the button: "Show rating", which is on this form.

Body:
Providing that you want put names into label18..labe22 and values into label28..label32 a simple Linq should do

 using System.Linq;

 ...

 private void updateRatingLabels() {
   var tops = AllNames()
     .OrderBy(pair => pair.Value)                      // less seconds - better rank
     .ThenBy(pair => pair.Key, StringComparer.Ordinal) // On tie, use names
     .Take(5)                                          // Top 5 or less
     .ToArray();

   // Clear all the labels
   for (int i = 18; i <= 22; ++i)
     Controls.Find($"label{i}", true).First().Text = "";

   for (int i = 28; i <= 32; ++i)
     Controls.Find($"label{i}", true).First().Text = "";

   // Put best results
   for (int i = 0; i < tops.Length; ++i) {
     Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
     Controls.Find($"label{i + 28}", true).First().Text = tops[i].Value.ToString();
   }
 }

Then

  private void buttonShow_Rating_Click(object sender, EventArgs e) {
    updateRatingLabels();
  }


问:
Match Lines From Two Lists With Wildcards In One List
I have two lists, one of which contains wildcards (in this case represented by *). I would like to compare the two lists and create an output of those that match, with each wildcard * representing a single character.

For example:

File 1

```<code>123456|Jane|Johnson|Pharmacist|janejohnson@gmail.com
09876579|Frank|Roberts|Butcher|frankie1@hotmail.com
092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk
</code>```

File 2

```<code>1***6|Jane|Johnson|Pharmacist|janejohnson@gmail.com
09876579|Frank|Roberts|Butcher|f**1@hotmail.com
092362936|Joe|Jordan|J*****|joe@joesjoinery.com
928|Bob|Horton|Farmer|b*****n@f*********.co.uk
</code>```

Output

```<code>092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk
</code>```

Explanation

The first two lines are not considered matches because the number of *s is not equal to the number of characters shown in the first file. The latter two are, so they are added to output.

I have tried to reason out ways to do this in AWK and using Join, but I don't know any way to even start trying to achieve this. Any help would be greatly appreciated.

答:
```<code>sed 's/\./\\./g; s/\*/./g' file2 | xargs -I{} grep {} file1
</code>```

Explanation:

I'd take advantage of regular expression matching. To do that, we need to turn every asterisk * into a dot ., which represents any character in regular expressions. As a side effect of enabling regular expressions, we need to escape all special characters, particularly the ., in order for them to be taken literally. In a regular expression, we need to use \. to represent a dot (as opposed to any character).

The first step is perform these substitutions with sed, the second is passing every resulting line as a search pattern to grep, and search file1 for that pattern. The glue that allows to do this is xargs, where a {} is a placeholder representing a single line from the results of the sed command.

Note:

This is not a general, safe solution you can simply copy and paste: you should watch out for any characters, in your file containing the asterisks, that are considered special in grep regular expressions.

Update:

jhnc extends the escaping to any of the following characters: .\^$[], thus accounting for almost all sorts of email addresses. He/she then avoids the use of xargs by employing -f - to pass the results of sed as search expressions to grep:

```<code>sed 's/[.\\^$[]/\\&/g; s/[*]/./g' file2 | grep -f - file1
</code>```

This solution is both more general and more efficient, see comment below.

Body:
I have two lists, one of which contains wildcards (in this case represented by *). I would like to compare the two lists and create an output of those that match, with each wildcard * representing a single character.

For example:

File 1

123456|Jane|Johnson|Pharmacist|janejohnson@gmail.com
09876579|Frank|Roberts|Butcher|frankie1@hotmail.com
092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk

File 2

1***6|Jane|Johnson|Pharmacist|janejohnson@gmail.com
09876579|Frank|Roberts|Butcher|f**1@hotmail.com
092362936|Joe|Jordan|J*****|joe@joesjoinery.com
928|Bob|Horton|Farmer|b*****n@f*********.co.uk

Output

092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk

Explanation

The first two lines are not considered matches because the number of *s is not equal to the number of characters shown in the first file. The latter two are, so they are added to output.

I have tried to reason out ways to do this in AWK and using Join, but I don't know any way to even start trying to achieve this. Any help would be greatly appreciated.

Body:
sed 's/\./\\./g; s/\*/./g' file2 | xargs -I{} grep {} file1

Explanation:

I'd take advantage of regular expression matching. To do that, we need to turn every asterisk * into a dot ., which represents any character in regular expressions. As a side effect of enabling regular expressions, we need to escape all special characters, particularly the ., in order for them to be taken literally. In a regular expression, we need to use \. to represent a dot (as opposed to any character).

The first step is perform these substitutions with sed, the second is passing every resulting line as a search pattern to grep, and search file1 for that pattern. The glue that allows to do this is xargs, where a {} is a placeholder representing a single line from the results of the sed command.

Note:

This is not a general, safe solution you can simply copy and paste: you should watch out for any characters, in your file containing the asterisks, that are considered special in grep regular expressions.

Update:

jhnc extends the escaping to any of the following characters: .\^$[], thus accounting for almost all sorts of email addresses. He/she then avoids the use of xargs by employing -f - to pass the results of sed as search expressions to grep:

sed 's/[.\\^$[]/\\&/g; s/[*]/./g' file2 | grep -f - file1

This solution is both more general and more efficient, see comment below.


问:
Get Geometry from revit element
I have Created the following code and Iam stuck at extracting geometry from the element(in my case it going to be a CAD import)

I am expecting solutions to these:

How to classify or filter geometry types in the iron python.

what is a indexer#

I really didnt understand this but tried this too..

options = Autodesk.Revit.DB.Options()

Selected = Ui.Selection.GetElementIds()

test=(Selected[0])

Cad = doc.GetElement(test)

curves = Cad.Geometry

print(curves)

NewCurve = doc.Create.NewDetailCurve(view,curves[options])

Actual code:

```<code>#Import Autodesk stuffs
import clr
import System
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI.Selection import *

clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)

clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager

# Import iron python packages
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)

import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

app = __revit__.Application
Ui = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
view = doc.ActiveView

from Autodesk.Revit.UI import Selection

Selected = Ui.Selection.GetElementIds()

test=(Selected[0])

Cad = doc.GetElement(test)

curves = Cad.Geometry

print(curves)

NewCurve = doc.Create.NewDetailCurve(view,curves)
</code>```

答: You should debug through your code step by step. In the debugger, you can see the actual values of each of your variables. I believe, just from looking at your code, that your variable curves is a GeometryElement instance. You need to dig deeper into the internal structure of that element to access the actual Curve object that you feed into NewDetailCurve. NewDetailCurve is complaining that you are passing it a more complex object, not a Curve object.

Title: Get Geometry from revit element

Body:
I have Created the following code and Iam stuck at extracting geometry from the element(in my case it going to be a CAD import)

I am expecting solutions to these:

How to classify or filter geometry types in the iron python.

what is a indexer#

I really didnt understand this but tried this too..

options = Autodesk.Revit.DB.Options()

Selected = Ui.Selection.GetElementIds()

test=(Selected[0])

Cad = doc.GetElement(test)

curves = Cad.Geometry

print(curves)

NewCurve = doc.Create.NewDetailCurve(view,curves[options])

Actual code:

#Import Autodesk stuffs
import clr
import System
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI.Selection import *

clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)

clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager

# Import iron python packages
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)

import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

app = __revit__.Application
Ui = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
view = doc.ActiveView

from Autodesk.Revit.UI import Selection

Selected = Ui.Selection.GetElementIds()

test=(Selected[0])

Cad = doc.GetElement(test)

curves = Cad.Geometry

print(curves)

NewCurve = doc.Create.NewDetailCurve(view,curves)


问:
How to add custom menu icon in menubar on macOS with electron?
I want to add custom menu in menu bar in mac with electron (nodejs).
How can this be done in electron?

As an example there is:

答: I think you are looking for the Tray API</p>


问:
Which representation of a 2D matrix is faster
which way is faster and compiler/cache friendlier, use M[a][b] or M[a*b] when working with matrices?

I tried writing both ways on compiler explorer in a function that allocates, initialises and returns a matrix but I don't know assembly and how much time each instruction takes

int **M = malloc(sizeof(int*)*m)
for(i=0; i<m; ++i) {
  *M = malloc(sizeof(int)*n);
  for(int j = 0; j < n; ++j){
    M[j] = j;
  }
```

<p>vs</p>

<pre class="lang-c prettyprint-override"><code>int *M = malloc(m*n*sizeof(int));
for(i = 0; i < m*n; ++i) M[i] = i;
</code>```

I expect the second way to be faster.

答:
The code with with the malloc calls will be slower. More interesting how fast access to the particular cell is

```<code>void foo(int * const * const M, const size_t x, const size_t y, const int val)
{
    M[x][y] = val;
}

void foo2(int * const M, const size_t x, const size_t y, const size_t rowsize, const int val)
{
    M[x + rowsize * y] = val;
}
</code>```

https://godbolt.org/z/iv0VPV

```<code>foo:
        mov     rax, QWORD PTR [rdi+rsi*8]
        mov     DWORD PTR [rax+rdx*4], ecx
        ret
foo2:
        imul    rcx, rdx
        add     rcx, rsi
        mov     DWORD PTR [rdi+rcx*4], r8d
        ret
</code>```

the result is obvious;

Body:
which way is faster and compiler/cache friendlier, use M[a][b] or M[a*b] when working with matrices?

I tried writing both ways on compiler explorer in a function that allocates, initialises and returns a matrix but I don't know assembly and how much time each instruction takes

int **M = malloc(sizeof(int*)*m)
for(i=0; i<m; ++i) {
  *M = malloc(sizeof(int)*n);
  for(int j = 0; j < n; ++j){
    M[j] = j;
  }

vs

int *M = malloc(m*n*sizeof(int));
for(i = 0; i < m*n; ++i) M[i] = i;

I expect the second way to be faster.

Body:
The code with with the malloc calls will be slower. More interesting how fast access to the particular cell is

void foo(int * const * const M, const size_t x, const size_t y, const int val)
{
    M[x][y] = val;
}

void foo2(int * const M, const size_t x, const size_t y, const size_t rowsize, const int val)
{
    M[x + rowsize * y] = val;
}

https://godbolt.org/z/iv0VPV

foo:
        mov     rax, QWORD PTR [rdi+rsi*8]
        mov     DWORD PTR [rax+rdx*4], ecx
        ret
foo2:
        imul    rcx, rdx
        add     rcx, rsi
        mov     DWORD PTR [rdi+rcx*4], r8d
        ret

the result is obvious;