问:
Azure pipeline with custom variables as condition
We would like to optimize our pipelines to avoid running steps that are not needed for the particular case.
I have created the variable shouldTriggerAnyBuild but it always seems to be true (or ignored), as the specified steps always runs, even though the none of the steps later, where the conditions are combined from, are run.

What is the problem with the script, or how can I debug it?

```<code>trigger:
- master
- stage
- release/*

pool:
  vmImage: 'macOS-latest'

variables:
  shouldTriggerAnyBuild: $[ or(and(eq(variables['Build.SourceBranch'], 'refs/heads/master'), not(startsWith(variables['Build.SourceVersionMessage'], 'release:'))), eq(variables['Build.SourceBranch'], 'refs/heads/stage'), startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')) ]

steps:
- task: UseRubyVersion@0
  inputs:
    versionSpec: '~> 2.6'

- script: echo "y" | $ANDROID_HOME/tools/bin/sdkmanager --install 'system-images;android-29;google_apis;x86'
  displayName: 'install/setup android sdkmanager'
  condition: variables.shouldTriggerAnyBuild

- script: gem install bundler
  displayName: 'gem install bundler'
  condition: variables.shouldTriggerAnyBuild

- script: bundle install
  displayName: 'bundle install'
  condition: variables.shouldTriggerAnyBuild

- script: bundle exec fastlane ciBuildDev
  displayName: 'build dev'
  condition: and(eq(variables['Build.SourceBranch'], 'refs/heads/master'),  not(startsWith(variables['Build.SourceVersionMessage'], 'release:')))

- script: bundle exec fastlane ciDeployToTest
  displayName: 'build stage'
  condition: eq(variables['Build.SourceBranch'], 'refs/heads/stage')

- script: bundle exec fastlane ciDeployToGooglePlay
  displayName: 'build release'
  condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')

- task: PublishBuildArtifacts@1
  displayName: "Publish artifacts .apk"
  condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')
  inputs:
    PathtoPublish: ./app/build/outputs/apk/prod/app-prod-unsigned.apk
    ArtifactName: Prod_app_apk

</code>```

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops

答:
What is the problem with the script?

Conditions are written as expressions. condition: variables.shouldTriggerAnyBuild won't take effect.
Instead you can use condition: eq(variables['SHOULDTRIGGERANYBUILD'], 'True') for conditional step. I think it's the direct cause of your issue. Also, feel free to use condition: eq(variables['shouldTriggerAnyBuild'], 'True') if you want, it also works.

How to debug it?

Here's a quick way to debug the value when necessary:

1.Change the second value to a impossible variable, then you can check the real value for your custom variable when the step is skipped:

2.If you want to make all thing clear, then you can do something like:

```<code>- task: CmdLine@2
  inputs:
    script: |
      echo Hello world
  condition: eq(and(eq(variables['Build.SourceBranch'], 'refs/heads/master'), not(startsWith(variables['Build.SourceVersionMessage'], 'release:'))),'True')

- task: CmdLine@2
  inputs:
    script: |
      echo Hello world
  condition: eq(eq(variables['Build.SourceBranch'], 'refs/heads/stage'),'True')

- task: CmdLine@2
  inputs:
    script: |
      echo Hello world
  condition: eq(startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'),'True')
</code>```

Since your variable is the combination of and(eq(variables['Build.SourceBranch'], 'refs/heads/master'), not(startsWith(variables['Build.SourceVersionMessage'], 'release:'))), eq(variables['Build.SourceBranch'], 'refs/heads/stage') and startsWith(variables['Build.SourceBranch'], 'refs/heads/release/') via Or function, you can divide them to debug how the shouldTriggerAnyBuild is expanded as always True.

In this way, you can debug them easily to find how the variable is expanded:

Note:

1.Or function: Evaluates True if any parameter is true.

2.Most of the time we choose to skip current task if one of previous tasks have failed, so you can consider combining succeeded() and your variable shouldTriggerAnyBuild. Examples here.

Body:
We would like to optimize our pipelines to avoid running steps that are not needed for the particular case.
I have created the variable shouldTriggerAnyBuild but it always seems to be true (or ignored), as the specified steps always runs, even though the none of the steps later, where the conditions are combined from, are run.

What is the problem with the script, or how can I debug it?

trigger:
- master
- stage
- release/*

pool:
  vmImage: 'macOS-latest'

variables:
  shouldTriggerAnyBuild: $[ or(and(eq(variables['Build.SourceBranch'], 'refs/heads/master'), not(startsWith(variables['Build.SourceVersionMessage'], 'release:'))), eq(variables['Build.SourceBranch'], 'refs/heads/stage'), startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')) ]

steps:
- task: UseRubyVersion@0
  inputs:
    versionSpec: '~> 2.6'

- script: echo "y" | $ANDROID_HOME/tools/bin/sdkmanager --install 'system-images;android-29;google_apis;x86'
  displayName: 'install/setup android sdkmanager'
  condition: variables.shouldTriggerAnyBuild

- script: gem install bundler
  displayName: 'gem install bundler'
  condition: variables.shouldTriggerAnyBuild

- script: bundle install
  displayName: 'bundle install'
  condition: variables.shouldTriggerAnyBuild

- script: bundle exec fastlane ciBuildDev
  displayName: 'build dev'
  condition: and(eq(variables['Build.SourceBranch'], 'refs/heads/master'),  not(startsWith(variables['Build.SourceVersionMessage'], 'release:')))

- script: bundle exec fastlane ciDeployToTest
  displayName: 'build stage'
  condition: eq(variables['Build.SourceBranch'], 'refs/heads/stage')

- script: bundle exec fastlane ciDeployToGooglePlay
  displayName: 'build release'
  condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')

- task: PublishBuildArtifacts@1
  displayName: "Publish artifacts .apk"
  condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')
  inputs:
    PathtoPublish: ./app/build/outputs/apk/prod/app-prod-unsigned.apk
    ArtifactName: Prod_app_apk

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops

Body:
What is the problem with the script?

Conditions are written as expressions. condition: variables.shouldTriggerAnyBuild won't take effect.
Instead you can use condition: eq(variables['SHOULDTRIGGERANYBUILD'], 'True') for conditional step. I think it's the direct cause of your issue. Also, feel free to use condition: eq(variables['shouldTriggerAnyBuild'], 'True') if you want, it also works.

How to debug it?

Here's a quick way to debug the value when necessary:

1.Change the second value to a impossible variable, then you can check the real value for your custom variable when the step is skipped:

2.If you want to make all thing clear, then you can do something like:

- task: CmdLine@2
  inputs:
    script: |
      echo Hello world
  condition: eq(and(eq(variables['Build.SourceBranch'], 'refs/heads/master'), not(startsWith(variables['Build.SourceVersionMessage'], 'release:'))),'True')

- task: CmdLine@2
  inputs:
    script: |
      echo Hello world
  condition: eq(eq(variables['Build.SourceBranch'], 'refs/heads/stage'),'True')

- task: CmdLine@2
  inputs:
    script: |
      echo Hello world
  condition: eq(startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'),'True')

Since your variable is the combination of and(eq(variables['Build.SourceBranch'], 'refs/heads/master'), not(startsWith(variables['Build.SourceVersionMessage'], 'release:'))), eq(variables['Build.SourceBranch'], 'refs/heads/stage') and startsWith(variables['Build.SourceBranch'], 'refs/heads/release/') via Or function, you can divide them to debug how the shouldTriggerAnyBuild is expanded as always True.

In this way, you can debug them easily to find how the variable is expanded:

Note:

1.Or function: Evaluates True if any parameter is true.

2.Most of the time we choose to skip current task if one of previous tasks have failed, so you can consider combining succeeded() and your variable shouldTriggerAnyBuild. Examples here.


来源: stackexchange

问:
Dialogflow: Forcing certain intents to be invalid given context
I want to make knock knock jokes using dialogflow, but I found that I can trigger one knock knock joke from the context of another. For example I have the following intents:

knockknock: training phrase (knock knock joke), response (knock knock)

whosethere: trainging phrase (who dat), response (annie, orange)

punchline-annie: training phrase (annie who), response (annie thing you can do I can do better)

punchline-orange: training phrase (orange who), response (orange you glad...)

If the bot responds with annie, I can respond with orange who and get the orange punchline to the joke. How can I prevent this from happening? I only want the orange punchline to be able to be called when the response from the whosethere intent was orange.

答:
Thank you @andreas030241 for the information. I figured out how to get the logic to work by learning how to use fulfillment. I set the response of the knockknock-whosethere intent inside the inline editor, and created an associated context name, that I then used as the input context for whichever punchline intent I wanted to be valid. The example code is below. Much appreciation!</p>

```<code>  function punchline(agent) {
    var names = [`Annie`,`Orange`,`Lena`,`Quiche`,`Wa`,`A little old lady`];
    var context_names = ['annie-punchline','orange-punchline','lena-punchline','quiche-punchline','wa-punchline','alittleoldlady-punchline'];
    var number = Math.floor(Math.random() * names.length);
    agent.add(names[number]);
    agent.setContext({
        name: context_names[number],
        lifespan: 1,
        });
  }

  let intentMap = new Map();
  intentMap.set('knockknock-whosethere', punchline);
  agent.handleRequest(intentMap);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Thank you @andreas030241 for the information. I figured out how to get the logic to work by learning how to use fulfillment. I set the response of the knockknock-whosethere intent inside the inline editor, and created an associated context name, that I then used as the input context for whichever punchline intent I wanted to be valid. The example code is below. Much appreciation!

  function punchline(agent) {
    var names = [`Annie`,`Orange`,`Lena`,`Quiche`,`Wa`,`A little old lady`];
    var context_names = ['annie-punchline','orange-punchline','lena-punchline','quiche-punchline','wa-punchline','alittleoldlady-punchline'];
    var number = Math.floor(Math.random() * names.length);
    agent.add(names[number]);
    agent.setContext({
        name: context_names[number],
        lifespan: 1,
        });
  }

  let intentMap = new Map();
  intentMap.set('knockknock-whosethere', punchline);
  agent.handleRequest(intentMap);


问:
can any one tell me the name of alert view that should do the works of **C# show dialog**
can any one tell me the name of alert view that should do the works of   C# show dialog .
other actions will not work without dismissing it(EVEN DELEGATES ALSO).

答:
As far as know, You have to do this manually. You can lock your task when the alert is shown and then unlock it again when it is dismissed getting help from these posts.

is there a way to pause an NSTHread indefinitely and have it resumed from another thread?

How to pause an NSThread until notified?

ContentLicense: CC BY-SA 3.0


问:
xpath expression to find either one type of element or another
I am trying to get either a parent li or tr from an element with specific text.

As it stands I am just trying different separate xpath expressions, but I am curious if I can just make one that goes something like this:

```<code>'//[tr | li]//*[contains(text(), "Some Text")]'
</code>```

or

```<code>'//*[contains(text(), "Some Text")]/[ancestor::tr | ancestor::li]'
</code>```

I have found that I can just string the statements together like so:

```<code>'//li[descendant::*[contains(text(), "Some Text")]] | //tr[descendant::*[contains(text(), "Some Text")]]'
</code>```

but that isn't ideal either.

答:
Instead of

```<code>//[tr | li]
</code>```

use

```<code>//*[self::tr or self::li]
</code>```

Body:
I am trying to get either a parent li or tr from an element with specific text.

As it stands I am just trying different separate xpath expressions, but I am curious if I can just make one that goes something like this:

'//[tr | li]//*[contains(text(), "Some Text")]'

or

'//*[contains(text(), "Some Text")]/[ancestor::tr | ancestor::li]'

I have found that I can just string the statements together like so:

'//li[descendant::*[contains(text(), "Some Text")]] | //tr[descendant::*[contains(text(), "Some Text")]]'

but that isn't ideal either.

Body:
Instead of

//[tr | li]

use

//*[self::tr or self::li]


问:
Join two tables, run a calculation based on their columns, and set a column based on the results
Why does my query break after this? I'm essentially running calculations based off the columns of both tables and then setting their PVPLevel when rn is a certain value between 1 and 5000.

SET PVPRanking.PVPLevel = CASE

```<code>USE DNWorld
GO

WITH cte AS (
  SELECT PVPScores.PVPWin, PVPScores.PVPLose, PVPRanking.Death, PVPRanking.[Kill], PVPRanking.PVPExp,
RANK() OVER (ORDER BY (((PVPScores.PVPWin * 1) + (PVPRanking.[Kill] * 0.2) + (PVPRanking.PvpExp * 0.002)) - ((PVPScores.PVPLose * 0.5) + (PVPRanking.Death * 0.1) + (PVPScores.PvPGiveUp * 0.5))) DESC, PVPScores.CharacterID DESC ) AS rn
  FROM PvPRanking
INNER JOIN PVPScores
      ON PVPRanking.CharacterID = PVPScores.CharacterID

)
UPDATE cte
SET PVPRanking.PVPLevel = CASE
  WHEN rn = 1 THEN 26 -- #1 Rank Champion
  WHEN rn BETWEEN 2 AND 10 THEN 25 -- Reita
    WHEN rn BETWEEN 11 and 20 THEN 24 -- Warlord
    WHEN rn BETWEEN 21 and 30 then 23 -- Slayer
    WHEN rn BETWEEN 31 and 40 then 22 -- WATCH OUT
    WHEN rn BETWEEN 41 and 50 then 21 -- Royalty
    WHEN rn BETWEEN 51 and 60 then 20 -- Knight of Justice
    WHEN rn BETWEEN 61 and 70 then 19 -- Furious Fiend
    WHEN rn BETWEEN 71 and 85 then 18 -- Devil of PVP
    WHEN rn BETWEEN 86 and 100 then 17 -- God Of PvP
  WHEN rn BETWEEN 101 and 125 then 16 -- Death God
  WHEN rn BETWEEN 126 and 150 then 15 -- Master
  WHEN rn BETWEEN 151 and 175 then 14 -- Unpredictable Demon
  WHEN rn BETWEEN 176 and 250 then 13 -- Demon
  WHEN rn BETWEEN 251 and 300 then 12 -- Crazy Fiend
  WHEN rn BETWEEN 301 and 400 then 11 -- Fiend
  WHEN rn BETWEEN 401 and 500 then 10 -- Bloodthirsty
  WHEN rn BETWEEN 501 and 600 then 9 -- Kavalan
  WHEN rn BETWEEN 601 and 700 then 8 -- Keepo
  WHEN rn BETWEEN 701 and 800 then 7 -- Senior PvP Tactician
  WHEN rn BETWEEN 801 and 900 then 6 -- PvP Tactician
  WHEN rn BETWEEN 901 and 1000 then 5 -- Senior Apprentice
  WHEN rn BETWEEN 1001 and 1100 then 4 -- Apprentice
  WHEN rn BETWEEN 1101 and 1500 then 3 -- Lesser Novice
  WHEN rn BETWEEN 1501 and 2000 then 2 -- Novice
  WHEN rn BETWEEN 2000 and 5000 then 1 -- Egg

  ELSE 1

END
WHERE rn <= 5000;
</code>```

答:
It appears that you only need to include PVPLevel in the select list of the CTE:

```<code>WITH cte AS (
    SELECT ps.PVPWin, ps.PVPLose, pr.Death, pr.[Kill], pr.PVPExp, pr.PVPLevel,
           RANK() OVER (ORDER BY (((ps.PVPWin * 1) + (pr.[Kill] * 0.2) + (pr.PvpExp * 0.002)) - ((ps.PVPLose * 0.5) + (pr.Death * 0.1) + (ps.PvPGiveUp * 0.5))) DESC, ps.CharacterID DESC ) AS rn
    FROM PvPRanking pr
    INNER JOIN PVPScores ps ON pr.CharacterID = ps.CharacterID
)
</code>```

Then, continue with your current update query as is.  Note that the update itself could be simplified a bit, resting on that the range checks are always increasing from top to bottom:

```<code>UPDATE cte
SET PVPLevel = CASE WHEN rn = 1 THEN 26    -- #1 Rank Champion
                    WHEN rn <= 10 THEN 25  -- Reita
                    WHEN rn <= 20 THEN 24  -- Warlord
                    WHEN rn <= 30 THEN 23  -- Slayer
                    WHEN rn <= 40 THEN 22  -- WATCH OUT
                    WHEN rn <= 50 THEN 21  -- Royalty
                    WHEN rn <= 60 THEN 20  -- Knight of Justice
                    WHEN rn <= 70 THEN 19  -- Furious Fiend
                    WHEN rn <= 85 THEN 18  -- Devil of PVP
                    WHEN rn <= 100 THEN 17 -- God Of PvP
                    WHEN rn <= 125 THEN 16 -- Death God
                    WHEN rn <= 150 THEN 15 -- Master
                    WHEN rn <= 175 THEN 14 -- Unpredictable Demon
                    WHEN <= 250 THEN 13    -- Demon
                    WHEN <= 300 THEN 12    -- Crazy Fiend
                    WHEN <= 400 THEN 11    -- Fiend
                    WHEN <= 500 THEN 10    -- Bloodthirsty
                    WHEN <= 600 THEN 9     -- Kavalan
                    WHEN <= 700 THEN 8     -- Keepo
                    WHEN <= 800 THEN 7     -- Senior PvP Tactician
                    WHEN rn <= 900 THEN 6  -- PvP Tactician
                    WHEN rn <= 1000 THEN 5 -- Senior Apprentice
                    WHEN rn <= 1100 THEN 4 -- Apprentice
                    WHEN rn <= 1500 THEN 3 -- Lesser Novice
                    WHEN rn <= 2000 THEN 2 -- Novice
                    WHEN rn <= 5000 THEN 1 -- Egg
                    ELSE 1 END
WHERE rn <= 5000;
</code>```

Body:
Why does my query break after this? I'm essentially running calculations based off the columns of both tables and then setting their PVPLevel when rn is a certain value between 1 and 5000.

SET PVPRanking.PVPLevel = CASE

USE DNWorld
GO

WITH cte AS (
  SELECT PVPScores.PVPWin, PVPScores.PVPLose, PVPRanking.Death, PVPRanking.[Kill], PVPRanking.PVPExp,
RANK() OVER (ORDER BY (((PVPScores.PVPWin * 1) + (PVPRanking.[Kill] * 0.2) + (PVPRanking.PvpExp * 0.002)) - ((PVPScores.PVPLose * 0.5) + (PVPRanking.Death * 0.1) + (PVPScores.PvPGiveUp * 0.5))) DESC, PVPScores.CharacterID DESC ) AS rn
  FROM PvPRanking
INNER JOIN PVPScores
      ON PVPRanking.CharacterID = PVPScores.CharacterID

)
UPDATE cte
SET PVPRanking.PVPLevel = CASE
  WHEN rn = 1 THEN 26 -- #1 Rank Champion
  WHEN rn BETWEEN 2 AND 10 THEN 25 -- Reita
    WHEN rn BETWEEN 11 and 20 THEN 24 -- Warlord
    WHEN rn BETWEEN 21 and 30 then 23 -- Slayer
    WHEN rn BETWEEN 31 and 40 then 22 -- WATCH OUT
    WHEN rn BETWEEN 41 and 50 then 21 -- Royalty
    WHEN rn BETWEEN 51 and 60 then 20 -- Knight of Justice
    WHEN rn BETWEEN 61 and 70 then 19 -- Furious Fiend
    WHEN rn BETWEEN 71 and 85 then 18 -- Devil of PVP
    WHEN rn BETWEEN 86 and 100 then 17 -- God Of PvP
  WHEN rn BETWEEN 101 and 125 then 16 -- Death God
  WHEN rn BETWEEN 126 and 150 then 15 -- Master
  WHEN rn BETWEEN 151 and 175 then 14 -- Unpredictable Demon
  WHEN rn BETWEEN 176 and 250 then 13 -- Demon
  WHEN rn BETWEEN 251 and 300 then 12 -- Crazy Fiend
  WHEN rn BETWEEN 301 and 400 then 11 -- Fiend
  WHEN rn BETWEEN 401 and 500 then 10 -- Bloodthirsty
  WHEN rn BETWEEN 501 and 600 then 9 -- Kavalan
  WHEN rn BETWEEN 601 and 700 then 8 -- Keepo
  WHEN rn BETWEEN 701 and 800 then 7 -- Senior PvP Tactician
  WHEN rn BETWEEN 801 and 900 then 6 -- PvP Tactician
  WHEN rn BETWEEN 901 and 1000 then 5 -- Senior Apprentice
  WHEN rn BETWEEN 1001 and 1100 then 4 -- Apprentice
  WHEN rn BETWEEN 1101 and 1500 then 3 -- Lesser Novice
  WHEN rn BETWEEN 1501 and 2000 then 2 -- Novice
  WHEN rn BETWEEN 2000 and 5000 then 1 -- Egg

  ELSE 1

END
WHERE rn <= 5000;

Body:
It appears that you only need to include PVPLevel in the select list of the CTE:

WITH cte AS (
    SELECT ps.PVPWin, ps.PVPLose, pr.Death, pr.[Kill], pr.PVPExp, pr.PVPLevel,
           RANK() OVER (ORDER BY (((ps.PVPWin * 1) + (pr.[Kill] * 0.2) + (pr.PvpExp * 0.002)) - ((ps.PVPLose * 0.5) + (pr.Death * 0.1) + (ps.PvPGiveUp * 0.5))) DESC, ps.CharacterID DESC ) AS rn
    FROM PvPRanking pr
    INNER JOIN PVPScores ps ON pr.CharacterID = ps.CharacterID
)

Then, continue with your current update query as is.  Note that the update itself could be simplified a bit, resting on that the range checks are always increasing from top to bottom:

UPDATE cte
SET PVPLevel = CASE WHEN rn = 1 THEN 26    -- #1 Rank Champion
                    WHEN rn <= 10 THEN 25  -- Reita
                    WHEN rn <= 20 THEN 24  -- Warlord
                    WHEN rn <= 30 THEN 23  -- Slayer
                    WHEN rn <= 40 THEN 22  -- WATCH OUT
                    WHEN rn <= 50 THEN 21  -- Royalty
                    WHEN rn <= 60 THEN 20  -- Knight of Justice
                    WHEN rn <= 70 THEN 19  -- Furious Fiend
                    WHEN rn <= 85 THEN 18  -- Devil of PVP
                    WHEN rn <= 100 THEN 17 -- God Of PvP
                    WHEN rn <= 125 THEN 16 -- Death God
                    WHEN rn <= 150 THEN 15 -- Master
                    WHEN rn <= 175 THEN 14 -- Unpredictable Demon
                    WHEN <= 250 THEN 13    -- Demon
                    WHEN <= 300 THEN 12    -- Crazy Fiend
                    WHEN <= 400 THEN 11    -- Fiend
                    WHEN <= 500 THEN 10    -- Bloodthirsty
                    WHEN <= 600 THEN 9     -- Kavalan
                    WHEN <= 700 THEN 8     -- Keepo
                    WHEN <= 800 THEN 7     -- Senior PvP Tactician
                    WHEN rn <= 900 THEN 6  -- PvP Tactician
                    WHEN rn <= 1000 THEN 5 -- Senior Apprentice
                    WHEN rn <= 1100 THEN 4 -- Apprentice
                    WHEN rn <= 1500 THEN 3 -- Lesser Novice
                    WHEN rn <= 2000 THEN 2 -- Novice
                    WHEN rn <= 5000 THEN 1 -- Egg
                    ELSE 1 END
WHERE rn <= 5000;


问:
Flexbox div not taking up entire horizontal space
I have an angular page with 3 components i'm trying to get to fill the entire horizontal space. Currently the parent flexbox div is not expanding to the full length, even though I have width: 100% on it. I am able to change the width using pixel values instead, however I have no idea how wide the viewport is going to be when the page is loaded. I have tried setting the margin and padding to 0, making sure the child flexdivs widths add up to 100%, etc...

Relevant html:

```<code><div fxLayout="row" fxLayoutGap="15px" id="bottomContainer">
      <div fxFlex="1 0 40%"><mat-card gdArea="chart">
        <mat-card-subtitle>Messages Flagged <br>{{period}}<button mat-icon-button [matMenuTriggerFor]="menu"><mat-icon>more_vert</mat-icon></button></mat-card-subtitle>
        <mat-menu #menu="matMenu">
          <button mat-menu-item (click)="period = 'Week'; periodInt = 0; changeMessagesFlaggedChartPeriod('Week')">Week</button>
          <button mat-menu-item (click)="period = 'Month'; periodInt = 1; changeMessagesFlaggedChartPeriod('Month')">Month</button>
          <button mat-menu-item (click)="period = 'Year'; periodInt = 2; changeMessagesFlaggedChartPeriod('Year')">Year</button>
        </mat-menu>
        <mat-card-content gdAreas="chart | list" gdRows="auto">
          <div style="display: block">
            <canvas baseChart
                    [datasets]="this.currentMessagesFlaggedDataset"
                    [labels]="this.MESSAGES_FLAGGED_LABELS"
                    chartType="radar"
                    [options]="this.messagesFlaggedChartOptions"
                    [colors]="this.channelData.chartColors"
                    height="100%"
                    width="100%"
          ></canvas>
          </div>
        </mat-card-content>
      </mat-card></div>

      <div fxFlex="1 1 30%"><mat-card class="mat-elevation-z2 channelUserTableContainer">
        <mat-card-subtitle>Most Negative Users</mat-card-subtitle>
        <table mat-table class="channelUserTable" [dataSource]="channelData.negativeUsers">
          <!-- Username column -->
          <ng-container matColumnDef="username">
            <th mat-header-cell *matHeaderCellDef>Username</th>
            <td mat-cell *matCellDef="let element"> {{element.username}}</td>
          </ng-container>

          <!-- Number of flags column -->
          <ng-container matColumnDef="numFlags">
            <th mat-header-cell class="textAlignRight" *matHeaderCellDef>Number of Flags</th>
            <td mat-cell class="textAlignRight" *matCellDef="let element"> {{element.numFlags}}</td>
          </ng-container>

          <tr mat-header-row *matHeaderRowDef="userTableColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: userTableColumns;"></tr>
        </table>
      </mat-card></div>

      <div fxFlex="1 1 30%"><mat-card class="mat-elevation-z2 channelUserTableContainer">
        <mat-card-subtitle>Most Positive Users</mat-card-subtitle>
        <table mat-table class="channelUserTable" [dataSource]="channelData.positiveUsers">
          <!-- Username column -->
          <ng-container matColumnDef="username">
            <th mat-header-cell *matHeaderCellDef>Username</th>
            <td mat-cell *matCellDef="let element"> {{element.username}}</td>
          </ng-container>

          <!-- Number of flags column -->
          <ng-container matColumnDef="numFlags">
            <th mat-header-cell class="textAlignRight" *matHeaderCellDef>Number of Flags</th>
            <td mat-cell class="textAlignRight" *matCellDef="let element"> {{element.numFlags}}</td>
          </ng-container>

          <tr mat-header-row *matHeaderRowDef="userTableColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: userTableColumns;"></tr>
        </table>
      </mat-card></div>
    </div>
</code>```

CSS:

```<code>  padding-left: 16px;
  padding-top: 16px;
}

#channelHeaderText {
  font-size: x-large;
  font-weight: bold;
}

.mindChartNoMargin :nth-child(1) {
  margin: 0;
}

.channelUserTable {
  width: 100%;
}

.channelUserTableContainer {
  background-color: white;
}

.textAlignRight {
  text-align: right;
}

#bottomContainer {
  width: 100%;
}
</code>```

Help is much appreciated

答:
Try moving the width to the container instead, also try making the container a flexbox and the items flex too.

```<code>.channelUserTableContainer {
    background-color: white;
    width: 100%;
    display: flex;
}

.channelUserTable {
    display: flex;
}
</code>```

I like to add a dotted line to understand how the flexboxes are working so you could also add a dotted border

border: dotted;

Body:
I have an angular page with 3 components i'm trying to get to fill the entire horizontal space. Currently the parent flexbox div is not expanding to the full length, even though I have width: 100% on it. I am able to change the width using pixel values instead, however I have no idea how wide the viewport is going to be when the page is loaded. I have tried setting the margin and padding to 0, making sure the child flexdivs widths add up to 100%, etc...

Relevant html:

<mat-card gdArea="chart">
        <mat-card-subtitle>Messages Flagged
{{period}}<button mat-icon-button [matMenuTriggerFor]="menu"><mat-icon>more_vert</mat-icon></button></mat-card-subtitle>
        <mat-menu #menu="matMenu">
          <button mat-menu-item (click)="period = 'Week'; periodInt = 0; changeMessagesFlaggedChartPeriod('Week')">Week</button>
          <button mat-menu-item (click)="period = 'Month'; periodInt = 1; changeMessagesFlaggedChartPeriod('Month')">Month</button>
          <button mat-menu-item (click)="period = 'Year'; periodInt = 2; changeMessagesFlaggedChartPeriod('Year')">Year</button>
        </mat-menu>
        <mat-card-content gdAreas="chart | list" gdRows="auto">

            <canvas baseChart
                    [datasets]="this.currentMessagesFlaggedDataset"
                    [labels]="this.MESSAGES_FLAGGED_LABELS"
                    chartType="radar"
                    [options]="this.messagesFlaggedChartOptions"
                    [colors]="this.channelData.chartColors"
                    height="100%"
                    width="100%"
          ></canvas>

        </mat-card-content>
      </mat-card>

<mat-card class="mat-elevation-z2 channelUserTableContainer">
        <mat-card-subtitle>Most Negative Users</mat-card-subtitle>

          <ng-container matColumnDef="username">
            Username
             {{element.username}}
          </ng-container>

          <ng-container matColumnDef="numFlags">
            Number of Flags
             {{element.numFlags}}
          </ng-container>

      </mat-card>

<mat-card class="mat-elevation-z2 channelUserTableContainer">
        <mat-card-subtitle>Most Positive Users</mat-card-subtitle>

          <ng-container matColumnDef="username">
            Username
             {{element.username}}
          </ng-container>

          <ng-container matColumnDef="numFlags">
            Number of Flags
             {{element.numFlags}}
          </ng-container>

      </mat-card>

CSS:

  padding-left: 16px;
  padding-top: 16px;
}

#channelHeaderText {
  font-size: x-large;
  font-weight: bold;
}

.mindChartNoMargin :nth-child(1) {
  margin: 0;
}

.channelUserTable {
  width: 100%;
}

.channelUserTableContainer {
  background-color: white;
}

.textAlignRight {
  text-align: right;
}

#bottomContainer {
  width: 100%;
}

Help is much appreciated

Body:
Try moving the width to the container instead, also try making the container a flexbox and the items flex too.

.channelUserTableContainer {
    background-color: white;
    width: 100%;
    display: flex;
}

.channelUserTable {
    display: flex;
}

I like to add a dotted line to understand how the flexboxes are working so you could also add a dotted border

border: dotted;


问:
Download files automatically in Internet Explorer 11 with Python and Selenium
I am trying to download some Excels files throught multiple Internet Explorer 11 windows at the same time by using Python and Selenium. The problem appens when the "Save As" Pop Up  appears and the only way to click to save button is send keys (alt + s). But to do that, the focus must be over the browser window, and as I sais before, I need launch mulitples IE11 windows at the same time and doing the same thing.

Tools like AutoIt, Robot or just events send keys doesn't be valid because these tools use operating system, I think there must be a solution like javascript, or Python to handle each window browser that should works.

I appreciate yout Help, Thanks!!

答:
As far as I know, WebDriver has no capability to access the IE Download dialog boxes presented by browsers when you click on a download link or button. But, we can bypass these dialog boxes using a separate program called "wget".

By using this program, first, we could get the hyperlink href attribute value, and then, execute the Command Prompt Command to download the file from the link.

Sample code:

```<code>import time
import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

cap = DesiredCapabilities().INTERNETEXPLORER
cap['ignoreZoomSetting'] = True
driver = webdriver.Ie("D:\\Downloads\\webdriver\\IEDriverServer_x64_3.14.0\\IEDriverServer.exe",capabilities= cap)

driver.get("<website url>")

time.sleep(3)

btn = driver.find_element_by_id("btnDowloadReport")

hrefurl = btn.get_attribute("href")

os.system('cmd /c D:\\temp\\wget.exe -P D:\\temp --no-check-certificate ' + hrefurl)

print("*******************")
</code>```

Html resource:

```<code><a id="btnDowloadReport" href="https://github.com//sakinala/AutomationTesting/raw/master/samplefile.pdf" >Download</a>
</code>```

[Note]: please remember to change to webdriver path and website url to your owns.

More detail information about using wget, you could refer to this article.

Body:
As far as I know, WebDriver has no capability to access the IE Download dialog boxes presented by browsers when you click on a download link or button. But, we can bypass these dialog boxes using a separate program called "wget".

By using this program, first, we could get the hyperlink href attribute value, and then, execute the Command Prompt Command to download the file from the link.

Sample code:

import time
import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

cap = DesiredCapabilities().INTERNETEXPLORER
cap['ignoreZoomSetting'] = True
driver = webdriver.Ie("D:\\Downloads\\webdriver\\IEDriverServer_x64_3.14.0\\IEDriverServer.exe",capabilities= cap)

driver.get("<website url>")

time.sleep(3)

btn = driver.find_element_by_id("btnDowloadReport")

hrefurl = btn.get_attribute("href")

os.system('cmd /c D:\\temp\\wget.exe -P D:\\temp --no-check-certificate ' + hrefurl)

print("*******************")

Html resource:

<a id="btnDowloadReport" href="https://github.com//sakinala/AutomationTesting/raw/master/samplefile.pdf" >Download</a>

[Note]: please remember to change to webdriver path and website url to your owns.

More detail information about using wget, you could refer to this article.


问:
Does Event Hub read its own Capture files?
I've read multiple articles describing how the Event Hub "Capture Feature" can be used to retain messages beyond 7 days using Blob Storage or Data Lake; but none say if those messages can be replayed to a Consumer if it were to rewind the Offset backwards beyond 7 days.

Should I assume the Capture feature claim is a little "tongue in cheek" and in actuality it's an export feature and does not integrate with or extend Event Hub's native transient storage?

Thanks

-John

答:
Yes, your assumption is correct. The capture feature just stores the data into blob storage or ADLS, but it cannot be used to replay by just rewinding the Offset backwards beyond 7 days.

If you want to replay, you need to resend the data from storage to eventhub again. Here is an example of reading the captured data, you can take use of it and re-send it by yourself for replay purpose.

Hope it can help you.


问:
C#, Why passing an int[] to a HashSet<T> adds a default element of value zero
I'm a beginner in C# so I hope to get your help here. I just wanted to know why passing an array with a specific size adds a default element of value 0 to the HashSet.
Example:

```<code>int[] arr = new int[4];
HshSet<int> myHashSet = new HashSet<int>(arr);
myHashSet.Count(); //The count is equal to 1 and the first element's value is zero.
</code>```

Can you please explain to me why this happens? Is this behavior unique for HashSets only or does it also apply to the other generic collections?

答:
arr is initialized as an array of four zeros, since that's the default value for an int.  You haven't actually given the array any specific values just initialized it with a length.

HashSets can not contain duplicate values so when you give it four zeros via its constructor the last three are discarded.

Body:
I'm a beginner in C# so I hope to get your help here. I just wanted to know why passing an array with a specific size adds a default element of value 0 to the HashSet.
Example:

int[] arr = new int[4];
HshSet<int> myHashSet = new HashSet<int>(arr);
myHashSet.Count(); //The count is equal to 1 and the first element's value is zero.

Can you please explain to me why this happens? Is this behavior unique for HashSets only or does it also apply to the other generic collections?


问:
Translate Keys to char
I want to translate a given set of System.Windows.Forms.Keys and a System.Windows.Forms.InputLanguage to the corresponding System.Char.

Tried some experiments with MapVirtualKeyEx, but there is now way to consider keyboard state, and ToUnicodeEx is a pain with dead keys.

My goal is a function ...

```<code>static char? FromKeys(Keys keys, InputLanguage inputLanguage)
{
    // As I think what can be helpful and I got trying to find a solution for this problem:
    Keys vkCode = keys & Keys.KeyCode;
    Keys modifiers = keys & Keys.Modifiers;

    byte[] keyboardState = new byte[256];

    keyboardState[vkCode] = 1 << 7;

    if (modifiers.HasFlag(Keys.Shift))
    {
        keyboardState[(int)Keys.ShiftKey] = 1 << 7;
    }

    if (modifiers.HasFlag(Keys.Control))
    {
        keyboardState[(int)Keys.ControlKey] = 1 << 7;
    }

    if (modifiers.HasFlag(Keys.Alt))
    {
        keyboardState[(int)Keys.Menu] = 1 << 7;
    }

    // [Put your code here]
}
</code>```

... which should be called like this:

```<code>FromKeys(Keys.A | Keys.Shift, InputLanguage.CurrentInputLanguage); // = 'A'
FromKeys(Keys.Escape, InputLanguage.DefaultInputLanguage); // = null
FromKeys(Keys.Oemtilde, InputLanguage.FromCulture(new CultureInfo("de-DE"))); // = 'ö'
FromKeys(Keys.E | Keys.Control | Keys.Alt, InputLanguage.FromCulture(new CultureInfo("de-DE"))); // = '€'
</code>```

(Be aware of Keys.Shift and Keys.ShiftKey!)

How would this function look like?

The answer I'll choose should provide a way to translate one "normal" System.Windows.Forms.Keys with an optional combination of the modifiers (Keys.Shift, Keys.Alt, Keys.Control) to a System.Char. Multiple successively calls have to result in the same character. No hardcoded keyboard layouts, the InputLanguage defines the layout to use.

As a help to understand what I'm trying to to: Generate a KeyPressEventArgs with just the KeyEventArgs (and the correct InputLangauge) given.

Dead keys should not affect FromKeys!

答:
I'm not certain this will work, but you might take a look at ToUnicodeEx. It lets you set the keyboard state as well as the input locale.

Another possibility, although pretty involved, would be to turn your events into strings that are compatible with SendKeys, and then send the string to your application.

You'd have to set the culture for the main thread and use a separate thread to do the sending.

I don't know how well something like that would work, and it's kind of expensive (in terms of time) to try it.

Title: Translate Keys to char

Body:
I want to translate a given set of System.Windows.Forms.Keys and a System.Windows.Forms.InputLanguage to the corresponding System.Char.

Tried some experiments with MapVirtualKeyEx, but there is now way to consider keyboard state, and ToUnicodeEx is a pain with dead keys.

My goal is a function ...

static char? FromKeys(Keys keys, InputLanguage inputLanguage)
{
    // As I think what can be helpful and I got trying to find a solution for this problem:
    Keys vkCode = keys & Keys.KeyCode;
    Keys modifiers = keys & Keys.Modifiers;

    byte[] keyboardState = new byte[256];

    keyboardState[vkCode] = 1 << 7;

    if (modifiers.HasFlag(Keys.Shift))
    {
        keyboardState[(int)Keys.ShiftKey] = 1 << 7;
    }

    if (modifiers.HasFlag(Keys.Control))
    {
        keyboardState[(int)Keys.ControlKey] = 1 << 7;
    }

    if (modifiers.HasFlag(Keys.Alt))
    {
        keyboardState[(int)Keys.Menu] = 1 << 7;
    }

    // [Put your code here]
}

... which should be called like this:

FromKeys(Keys.A | Keys.Shift, InputLanguage.CurrentInputLanguage); // = 'A'
FromKeys(Keys.Escape, InputLanguage.DefaultInputLanguage); // = null
FromKeys(Keys.Oemtilde, InputLanguage.FromCulture(new CultureInfo("de-DE"))); // = 'ö'
FromKeys(Keys.E | Keys.Control | Keys.Alt, InputLanguage.FromCulture(new CultureInfo("de-DE"))); // = '€'

(Be aware of Keys.Shift and Keys.ShiftKey!)

How would this function look like?

The answer I'll choose should provide a way to translate one "normal" System.Windows.Forms.Keys with an optional combination of the modifiers (Keys.Shift, Keys.Alt, Keys.Control) to a System.Char. Multiple successively calls have to result in the same character. No hardcoded keyboard layouts, the InputLanguage defines the layout to use.

As a help to understand what I'm trying to to: Generate a KeyPressEventArgs with just the KeyEventArgs (and the correct InputLangauge) given.

Dead keys should not affect FromKeys!


问:
How to set values in a bidimensional array?
First of all, sorry about my skills; my coding background is zero and I am just trying to modify an script to fit my needs.

I need to setValues in a two-rows datasheet data range.

The current script sets the values in the first row.
How should I modify the script so I can get the data from my 4 values in 2 rows?

Current behaviour:

My go-to behaviour:

Function to run: Print

```<code>function Print() {

   SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet").getRange(1, 1, 1, 2).setValues(Data());

}

function Data() {

    var array = [];

                      var score = "retrieved score";
                      var time = (2+2);
                      var device = "device";
                      var speed = 3+3;

    array.push([score,time]);

    Utilities.sleep(1000);

    return array;
}
</code>```

答:
Problem

Trying to set 2 x 2 matrix of values to 1 x 2 range

Solution

Your values have to match dimensions of the range. The sheet is a matrix consisting of cells:

```
|       |       col 1       | col 2 |
| ----- | ----------------- | ----- |
| row 1 | "retrieved score" |   4   |
| row 2 | "device"          |   6   |
```

2-dimensional arrays are basically the same, where outer level represents rows and inner - columns:

```<code>[
  [ "retrieved score", 4 ],
  [ "device", 6 ]
]
</code>```

Thus, with a simple modification, the cells should be filled correctly:

```<code>function Print() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();

  const rng = ss.getSheetByName("sheet").getRange(1, 1, 2, 2);

  const values = Data();

  rng.setValues(values);

}

function Data() {

  var array = [];

  var score = "retrieved score";
  var time = 2+2;
  var device = "device";
  var speed = 3+3;

  array.push([score, time], [device, speed]);

  Utilities.sleep(1000);

  return array;
}
</code>```

Notes

It does not make sense to me that you need to use the sleep() utility method here. Operations on an in-memory array are synchronous and atomic (which is not true for setValues, as it is an I/O operation).

References

push() method reference on MDN

setValues() method reference

Body:
First of all, sorry about my skills; my coding background is zero and I am just trying to modify an script to fit my needs.

I need to setValues in a two-rows datasheet data range.

The current script sets the values in the first row.
How should I modify the script so I can get the data from my 4 values in 2 rows?

Current behaviour:

My go-to behaviour:

Function to run: Print

function Print() {

   SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet").getRange(1, 1, 1, 2).setValues(Data());

}

function Data() {

    var array = [];

                      var score = "retrieved score";
                      var time = (2+2);
                      var device = "device";
                      var speed = 3+3;

    array.push([score,time]);

    Utilities.sleep(1000);

    return array;
}

Body:
Problem

Trying to set 2 x 2 matrix of values to 1 x 2 range

Solution

Your values have to match dimensions of the range. The sheet is a matrix consisting of cells:

|       |       col 1       | col 2 |
| ----- | ----------------- | ----- |
| row 1 | "retrieved score" |   4   |
| row 2 | "device"          |   6   |

2-dimensional arrays are basically the same, where outer level represents rows and inner - columns:

[
  [ "retrieved score", 4 ],
  [ "device", 6 ]
]

Thus, with a simple modification, the cells should be filled correctly:

function Print() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();

  const rng = ss.getSheetByName("sheet").getRange(1, 1, 2, 2);

  const values = Data();

  rng.setValues(values);

}

function Data() {

  var array = [];

  var score = "retrieved score";
  var time = 2+2;
  var device = "device";
  var speed = 3+3;

  array.push([score, time], [device, speed]);

  Utilities.sleep(1000);

  return array;
}

Notes

It does not make sense to me that you need to use the sleep() utility method here. Operations on an in-memory array are synchronous and atomic (which is not true for setValues, as it is an I/O operation).

References

push() method reference on MDN

setValues() method reference


问:
How to clear all Hibernate cache (ehcache) using Spring?
I am using 2nd level cache and query cache.
May I know how to programmatically clear all caches ?</p>

答:
Same as @Dino's answer, shortened syntax for JPA 2.0 API:</p>

```<code>@Autowired
private EntityManagerFactory entityManagerFactory;

public void clearHibernateCaches() {
    entityManagerFactory.getCache().unwrap(org.hibernate.Cache.class).evictAllRegions();
}
</code>```

Body:
Same as @Dino's answer, shortened syntax for JPA 2.0 API:

@Autowired
private EntityManagerFactory entityManagerFactory;

public void clearHibernateCaches() {
    entityManagerFactory.getCache().unwrap(org.hibernate.Cache.class).evictAllRegions();
}


问:
Setting MFA phone number for a user AAD B2C
I'm trying to set a phone number for a user for MFA:

This gives me the error:

"Partial failure in authentication methods update Unable to update
  phone methods for user"

Why is that? The phone number is still stored. Am I correct the number in the field is stored into strongAuthenticationPhoneNumber property which cannot be read?

答:
It appears that there is something wrong with this feature in Azure Portal currently and it also exists in Azure AD (Not just in B2C).

If you are using admin account which is a guest user, the backend will give an error: 401 Unauthorized. But the update will be successful.

If a normal admin account is used, the update will be successful without any errors.


问:
js/date : How to compare a French string date like "Vendredi 22 Mai à 22h" with current Date()
I'm trying to compare a French date in string format like Vendredi 22 Mai à 22h (literally `Friday 22 May at 10pm`` with the current date in javascript with node.js :

const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'); // or maybe with new Date.now()
const dateToCompare = "Vendredi 22 Mai à 22h"

if (dateNow <= dateToCompare) {
    // Code here
}
```

Thanks for help !

答:
I made somethink like this if it could help someone else (definitely not the best code given my JS skills) :</p>

```<code>const dateFormat = require('dateformat');
const monthsArr = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];

const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss');
const currentYear = dateFormat(new Date(), 'yyyy');

// Split each word
let eventDate = textDescription.split(' ');
// Organize the array to save only the necessary values : day in number, month in number and hours:minutes
eventDate = [
    eventDate[3],
    monthsArr.indexOf(eventDate[4]),
    eventDate[6]
];
// Split hours:minutes
// Modify hours number in date array
// Push minutes number to the date array
const eventHourMin = eventDate[2].split('h');
eventDate[2] = eventHourMin[0];
eventDate.push(eventHourMin[1]);
// Full date converted as yyyy-mm-dd HH:MM:ss
const formattedEventDate = dateFormat(new Date(currentYear, eventDate[1], eventDate[0], eventDate[2], eventDate[3], '00'), 'yyyy-mm-dd HH:MM:ss');
// If event date is not expired
if (dateNow < formattedEventDate) {
    // code here...
}
</code>```

Body:
I'm trying to compare a French date in string format like Vendredi 22 Mai à 22h (literally `Friday 22 May at 10pm`` with the current date in javascript with node.js :

const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'); // or maybe with new Date.now()
const dateToCompare = "Vendredi 22 Mai à 22h"

if (dateNow <= dateToCompare) {
    // Code here
}

Thanks for help !

Body:
I made somethink like this if it could help someone else (definitely not the best code given my JS skills) :

const dateFormat = require('dateformat');
const monthsArr = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];

const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss');
const currentYear = dateFormat(new Date(), 'yyyy');

// Split each word
let eventDate = textDescription.split(' ');
// Organize the array to save only the necessary values : day in number, month in number and hours:minutes
eventDate = [
    eventDate[3],
    monthsArr.indexOf(eventDate[4]),
    eventDate[6]
];
// Split hours:minutes
// Modify hours number in date array
// Push minutes number to the date array
const eventHourMin = eventDate[2].split('h');
eventDate[2] = eventHourMin[0];
eventDate.push(eventHourMin[1]);
// Full date converted as yyyy-mm-dd HH:MM:ss
const formattedEventDate = dateFormat(new Date(currentYear, eventDate[1], eventDate[0], eventDate[2], eventDate[3], '00'), 'yyyy-mm-dd HH:MM:ss');
// If event date is not expired
if (dateNow < formattedEventDate) {
    // code here...
}


问:
Android ViewBinding unable to render LinearLayout configuration
The ViewBinding implementation is unable to render the layout configuration for LinearLayout used in my code, while the same layout works with the older technique of findViewById()

I have setup the gradle to use ViewBinding

```<code>android {
    ...
    buildFeatures {
        viewBinding = true
}
</code>```

Below is the activity which uses a LinearLayout

activity_main.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:orientation="vertical"
    tools:context=".MainActivity">

  <ImageView
        ... />

  <Button
        ... />

</LinearLayout>
</code>```

The corresponding Kotlin class includes the binding instance with its root view passed to setContentView()

MainActivity.kt

```<code>private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    ...

    setContentView(binding.root)
}
</code>```

While the Layout editor renders a correct alignment of the app, once it is launched onto the emulator the layout configuration such as center_vertical alignment set using layout_gravity of LinearLayout is ignored.

Is something incorrect or missing the way ViewBinding is implemented?

答:
There are one possibility is that your LinearLayout have not any id.

When you are doing binding.root it keeps a reference of root view which is LinearLayout in your case.

As per the official document:

If view binding is enabled for a module, a binding class is generated
  for each XML layout file that the module contains. Each binding class
  contains references to the root view and all views that have an ID.

Give id to your LinearLayout android:id="rootView, rebuild your project and try to run.
I hope, it will solve your issue.

Thanks & Happy coding..!

Body:
The ViewBinding implementation is unable to render the layout configuration for LinearLayout used in my code, while the same layout works with the older technique of findViewById()

I have setup the gradle to use ViewBinding

android {
    ...
    buildFeatures {
        viewBinding = true
}

Below is the activity which uses a LinearLayout

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:orientation="vertical"
    tools:context=".MainActivity">

  <ImageView
        ... />

  <Button
        ... />

</LinearLayout>

The corresponding Kotlin class includes the binding instance with its root view passed to setContentView()

MainActivity.kt

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    ...

    setContentView(binding.root)
}

While the Layout editor renders a correct alignment of the app, once it is launched onto the emulator the layout configuration such as center_vertical alignment set using layout_gravity of LinearLayout is ignored.

Is something incorrect or missing the way ViewBinding is implemented?


问:
How to enforce usage rules on Custom Kotlin DSL
Im investigating Kotlin DSLs following these examples:-

https://github.com/zsmb13/VillageDSL

Im am interested in how to enforce usage rules on all attributes exposed by the DSL.

Taking the following example:-

```<code>val v = village {
    house {
        person {
            name = "Emily"
            age = 31
        }
         person {
            name = "Jane"
            age = 19
        }
    }
}
</code>```

I would like to enforce a rule which stops users of the DSL being able to enter duplicate attributes as shown below

```<code>val v = village {
    house {
        person {
            name = "Emily"
            name = "Elizabeth"
            age = 31
        }
         person {
            name = "Jane"
            age = 19
            age = 56
        }
    }
}
</code>```

I've tried with Kotlin contracts e.g.

```<code>contract { callsInPlace(block, EXACTLY_ONCE) }
</code>```

However these are only allowed in top level functions and I could not see how to employ a contract when using following the Builder pattern in DSLs, e.g.

```<code>@SimpleDsl1
class PersonBuilder(initialName: String, initialAge: Int) {
    var name: String = initialName
    var age: Int = initialAge

    fun build(): Person {
        return Person(name, age)
    }
}
</code>```

Is it possible to achieve my desired effect of enforcing the setting of each attribute only one per person?

答:
While writing this, I noticed that the Bug I referenced in my comments has been fixed, so I continued down that code path only to realize, there is a language limitation, at the bottom I will include an example of what I meant in the comments.

Both of these examples would be failures at runtime.

```<code>    fun test_person() {
    val village = village {
        house {
            person {
                name = "Emily"
    //            ::name setTo "Emily" // Commented for 2nd example of Person
                age = 31
            }
            person {
                name = "Jane"
                age = 19
            }
        }
        house {
            person {
                name = "Tim"
     //           name = "Tom" // Will break with exception
                age = 20
            }
        }
    }

    println("What is our village: \n$village")
}
</code>```

The runtime breaking example that works with exceptions:

```<code>class Village {
    val houses = mutableListOf<House>()

    fun house(people: House.() -> Unit) {
        val house = House()
        house.people()
        houses.add(house)
    }

    override fun toString(): String {
        val strB = StringBuilder("Village:\n")
        houses.forEach { strB.append("  $it \n") }
        return strB.toString()
    }
}

fun village(houses: Village.() -> Unit): Village  {
    val village = Village()
    village.houses()
    return village
}

class House {
    val people = mutableListOf<Person>()

    fun person(qualities: Person.() -> Unit) {
        val person = Person()
        person.qualities()
        people.add(person)
    }

    override fun toString(): String {
        val strB = StringBuilder("House:\n")
        people.forEach{ strB.append("    $it \n")}
        return strB.toString()
    }
}

class Person {
    var age by SetOnce<Int>()
    var name by SetOnce<String>()

    override fun toString(): String {
        return "Person: { Name: $name, Age: $age }"
    }
}

class SetOnce <T> : ReadWriteProperty<Any?, T?> {
    private var default: T? = null

    override fun getValue(thisRef: Any?, property: KProperty<*>): T? = default

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
        if (default != null) throw Exception("Duplicate set for ${property.name} on $thisRef")
        else default = value
    }
}
</code>```

The Non-working example that was intended to use lateinit properties to control the setting of a value once, but you cannot use a reference, it must be the literal ::foo syntax. Like I said, I didn't realize that bug was fixed, and did not know this was a limitation in the language

```<code>class Person {
    lateinit var name: String
    lateinit var age: Number // Number because primitives can't be lateinit

    /** @throws Exception when setting a property a second time */
    infix fun <T> KMutableProperty0<T>.setTo(value: T) {
        val prop = getProp<T>(this.name)

        if (prop.isInitialized.not()) this.set(value)
        else throw Exception("Duplicate set for ${this.name}")
    }

    private fun <T> getProp(name: String): KMutableProperty0<T> {

        return when(name) {
            "name" -> ::name
            "age" -> ::age
            else -> throw Exception("Non-existent property: $name")
        } as KMutableProperty0<T>
    }
}
</code>```

As contracts mature and the rules are relaxed, we could potentially write something like:

```<code>@OptIn(ExperimentalContracts::class)
infix fun <T> KMutableProperty0<T>.setTo(value: T) {
    contract { returns() implies this@setTo.isInitialized }
    this.set(value)
}
</code>```

Which would give us the capability to move this all to IDE errors, but we're not there yet sadly.

Body:
Im investigating Kotlin DSLs following these examples:-

https://github.com/zsmb13/VillageDSL

Im am interested in how to enforce usage rules on all attributes exposed by the DSL.

Taking the following example:-

val v = village {
    house {
        person {
            name = "Emily"
            age = 31
        }
         person {
            name = "Jane"
            age = 19
        }
    }
}

I would like to enforce a rule which stops users of the DSL being able to enter duplicate attributes as shown below

val v = village {
    house {
        person {
            name = "Emily"
            name = "Elizabeth"
            age = 31
        }
         person {
            name = "Jane"
            age = 19
            age = 56
        }
    }
}

I've tried with Kotlin contracts e.g.

contract { callsInPlace(block, EXACTLY_ONCE) }

However these are only allowed in top level functions and I could not see how to employ a contract when using following the Builder pattern in DSLs, e.g.

@SimpleDsl1
class PersonBuilder(initialName: String, initialAge: Int) {
    var name: String = initialName
    var age: Int = initialAge

    fun build(): Person {
        return Person(name, age)
    }
}

Is it possible to achieve my desired effect of enforcing the setting of each attribute only one per person?

Body:
While writing this, I noticed that the Bug I referenced in my comments has been fixed, so I continued down that code path only to realize, there is a language limitation, at the bottom I will include an example of what I meant in the comments.

Both of these examples would be failures at runtime.

    fun test_person() {
    val village = village {
        house {
            person {
                name = "Emily"
    //            ::name setTo "Emily" // Commented for 2nd example of Person
                age = 31
            }
            person {
                name = "Jane"
                age = 19
            }
        }
        house {
            person {
                name = "Tim"
     //           name = "Tom" // Will break with exception
                age = 20
            }
        }
    }

    println("What is our village: \n$village")
}

The runtime breaking example that works with exceptions:

class Village {
    val houses = mutableListOf<House>()

    fun house(people: House.() -> Unit) {
        val house = House()
        house.people()
        houses.add(house)
    }

    override fun toString(): String {
        val strB = StringBuilder("Village:\n")
        houses.forEach { strB.append("  $it \n") }
        return strB.toString()
    }
}

fun village(houses: Village.() -> Unit): Village  {
    val village = Village()
    village.houses()
    return village
}

class House {
    val people = mutableListOf<Person>()

    fun person(qualities: Person.() -> Unit) {
        val person = Person()
        person.qualities()
        people.add(person)
    }

    override fun toString(): String {
        val strB = StringBuilder("House:\n")
        people.forEach{ strB.append("    $it \n")}
        return strB.toString()
    }
}

class Person {
    var age by SetOnce<Int>()
    var name by SetOnce<String>()

    override fun toString(): String {
        return "Person: { Name: $name, Age: $age }"
    }
}

class SetOnce <T> : ReadWriteProperty<Any?, T?> {
    private var default: T? = null

    override fun getValue(thisRef: Any?, property: KProperty<*>): T? = default

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
        if (default != null) throw Exception("Duplicate set for ${property.name} on $thisRef")
        else default = value
    }
}

The Non-working example that was intended to use lateinit properties to control the setting of a value once, but you cannot use a reference, it must be the literal ::foo syntax. Like I said, I didn't realize that bug was fixed, and did not know this was a limitation in the language

class Person {
    lateinit var name: String
    lateinit var age: Number // Number because primitives can't be lateinit

    /** @throws Exception when setting a property a second time */
    infix fun <T> KMutableProperty0<T>.setTo(value: T) {
        val prop = getProp<T>(this.name)

        if (prop.isInitialized.not()) this.set(value)
        else throw Exception("Duplicate set for ${this.name}")
    }

    private fun <T> getProp(name: String): KMutableProperty0<T> {

        return when(name) {
            "name" -> ::name
            "age" -> ::age
            else -> throw Exception("Non-existent property: $name")
        } as KMutableProperty0<T>
    }
}

As contracts mature and the rules are relaxed, we could potentially write something like:

@OptIn(ExperimentalContracts::class)
infix fun <T> KMutableProperty0<T>.setTo(value: T) {
    contract { returns() implies this@setTo.isInitialized }
    this.set(value)
}

Which would give us the capability to move this all to IDE errors, but we're not there yet sadly.


问:
How can I run all the targets in an Ant buildfile?
I would like to execute all targets instead of specifying each one.

For example:

```<code><?xml version="1.0"?>
<project name="Kte" default="all" basedir="/home/Kte">

    <target name="target1">
    </target>

    <target name="target2">
    </target>
</project>
</code>```

Currently I have use:

```<code>$ ant target1
$ ant target2
</code>```

I'd like to use:

```<code>$ ant
</code>```

and have both targets get built  (this is just an example. Reality I have a long ever changing Ant buildfile with sub-ant files so would be very handy to have an "all" feature.

答:
Because Ant is declarative it doesn't do this sort of thing nicely.  You might consider a script task though.

Ant buildfiles have an implicit un-named target that 'holds' all the tasks that are not part of named targets.  So this, placed at the top-level, would do what you describe.

```<code><script language="javascript"><![CDATA[
    importClass( java.util.Vector );

    vec = new Vector( project.getTargets().keySet() );
    vec.setSize( vec.size( ) - 1 );
    project.executeTargets( vec );
]]>
</script>
</code>```

(The implicit target appears at the end of the list, hence the size adjustment to prevent recursion.)

If you put that script in a 'runner' target - which would execute all other targets in the buildfile - you would need to remove the 'runner' from the Vector (and the implicit target-with-no-name) to prevent recursion.

Body:
I would like to execute all targets instead of specifying each one.

For example:

<?xml version="1.0"?>
<project name="Kte" default="all" basedir="/home/Kte">

    <target name="target1">
    </target>

    <target name="target2">
    </target>
</project>

Currently I have use:

$ ant target1
$ ant target2

I'd like to use:

$ ant

and have both targets get built  (this is just an example. Reality I have a long ever changing Ant buildfile with sub-ant files so would be very handy to have an "all" feature.

Body:
Because Ant is declarative it doesn't do this sort of thing nicely.  You might consider a script task though.

Ant buildfiles have an implicit un-named target that 'holds' all the tasks that are not part of named targets.  So this, placed at the top-level, would do what you describe.

<script language="javascript"><![CDATA[
    importClass( java.util.Vector );

    vec = new Vector( project.getTargets().keySet() );
    vec.setSize( vec.size( ) - 1 );
    project.executeTargets( vec );
]]>
</script>

(The implicit target appears at the end of the list, hence the size adjustment to prevent recursion.)

If you put that script in a 'runner' target - which would execute all other targets in the buildfile - you would need to remove the 'runner' from the Vector (and the implicit target-with-no-name) to prevent recursion.


问:
How to combine attributes in Core Data using Swift?
I have a basic app that allows a user to select from an array of animals: [Cat, Bird, Dog] and record number of times they see it throughout the day. I am using Core Data to save each user's session. When I fetch the results from Core Data they look something like:

Animal: Bird, Seen: 2

Animal: Cat, Seen: 1

Animal: Bird, Seen: 4

Sessions is the entity while the attributes are animal: String and seen: Int.

I then have a label for each animal with the total times seen.
Example: Bird - Total: 6, Cat - Total: 1, Dog - Total 0

How can I add the attribute "seen" together for each of the animal attributes to produce a total amount for each one? The code below produces the fetched core data results.

```<code> let context = coreDataStack.managedContext
 let fetchRequest = NSFetchRequest<Sessions>(entityName: "Sessions")

   do {
                let tasks = try context.fetch(fetchRequest)

                   for task in tasks {
                    print("Animal: \(task.animal)")
                    print("Seen: \(String(describing: seen))")
                   }
               } catch let error {
                   print("Error: \(error.localizedDescription)")
               }
</code>```

答:
according to your question, I guess every data entry will have:

animal name (String)

seen count (Int)

So, maybe you can try using a dictionary to hold the total count for each of your animals

```<code>var animalCount = [String : Int]()

for task in tasks {
    if animalCount[task.animal] == nil {
        animalCount[task.animal] = task.seen
            //I assume this seen is a property of this task
    } else {
        animalCount[task.animal] = animalCount[task.animal]! + task.seen
    }
}
animalCount.forEach{print("Animal: \($0.key) - Total: \($0.value)")}
</code>```

Body:
I have a basic app that allows a user to select from an array of animals: [Cat, Bird, Dog] and record number of times they see it throughout the day. I am using Core Data to save each user's session. When I fetch the results from Core Data they look something like:

Animal: Bird, Seen: 2

Animal: Cat, Seen: 1

Animal: Bird, Seen: 4

Sessions is the entity while the attributes are animal: String and seen: Int.

I then have a label for each animal with the total times seen.
Example: Bird - Total: 6, Cat - Total: 1, Dog - Total 0

How can I add the attribute "seen" together for each of the animal attributes to produce a total amount for each one? The code below produces the fetched core data results.

 let context = coreDataStack.managedContext
 let fetchRequest = NSFetchRequest<Sessions>(entityName: "Sessions")

   do {
                let tasks = try context.fetch(fetchRequest)

                   for task in tasks {
                    print("Animal: \(task.animal)")
                    print("Seen: \(String(describing: seen))")
                   }
               } catch let error {
                   print("Error: \(error.localizedDescription)")
               }

Body:
according to your question, I guess every data entry will have:

animal name (String)

seen count (Int)

So, maybe you can try using a dictionary to hold the total count for each of your animals

var animalCount = [String : Int]()

for task in tasks {
    if animalCount[task.animal] == nil {
        animalCount[task.animal] = task.seen
            //I assume this seen is a property of this task
    } else {
        animalCount[task.animal] = animalCount[task.animal]! + task.seen
    }
}
animalCount.forEach{print("Animal: \($0.key) - Total: \($0.value)")}


问:
The model does not have a valid input feature of type image -> Create ML
I have created an ML Model using Create ML, which is about emotion recognition.

As an input file, I have uploaded a CSV file. The data consists of 48x48 pixel grayscale images of faces. The faces have been automatically registered so that the face is more or less centered and occupies about the same amount of space in each image. The task is to categorize each face based on the emotion shown in the facial expression into one of seven categories (0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral).

The model which I got has more than 87% accuracy, but when I use it in my Xcode project I get the following error:

  func setup() {
    do {
      // Gender request
      requests.append(VNCoreMLRequest(
        model: try VNCoreMLModel(for: GenderNet().model),
        completionHandler: handleGenderClassification
      ))
      // Age request
      requests.append(VNCoreMLRequest(
        model: try VNCoreMLModel(for: AgeNet().model),
        completionHandler: handleAgeClassification
      ))
      // Emotions request
      requests.append(VNCoreMLRequest(
        model: try VNCoreMLModel(for: test().model),
        completionHandler: handleEmotionClassification
      ))
    } catch {
      assertionFailure("Can't load Vision ML model: \(error)")
    }
  }
```

```      Fatal error: Can't load Vision ML model: Error Domain=com.apple.vis Code=15
    "The model does not have a valid input feature of type image"
    UserInfo={NSLocalizedDescription=The model does not have a valid input feature of type image}:
    file /Users/ivandimitrov/Desktop/Faces/Faces/ClassificationService.swift, line 38
```

Do you have any ideas on how to fix that?

答:
Your input is not being recognized as an image, you can verify this by clicking on your model in Xcode:

My input is of type Image, but yours is likely another type.

When running your conversion script eg coremltools.converters.tensorflow.convert(model, ...), you need to provide the parameter image_input_names which should match the name of your input layer.

Body:
I have created an ML Model using Create ML, which is about emotion recognition.

As an input file, I have uploaded a CSV file. The data consists of 48x48 pixel grayscale images of faces. The faces have been automatically registered so that the face is more or less centered and occupies about the same amount of space in each image. The task is to categorize each face based on the emotion shown in the facial expression into one of seven categories (0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral).

The model which I got has more than 87% accuracy, but when I use it in my Xcode project I get the following error:

  func setup() {
    do {
      // Gender request
      requests.append(VNCoreMLRequest(
        model: try VNCoreMLModel(for: GenderNet().model),
        completionHandler: handleGenderClassification
      ))
      // Age request
      requests.append(VNCoreMLRequest(
        model: try VNCoreMLModel(for: AgeNet().model),
        completionHandler: handleAgeClassification
      ))
      // Emotions request
      requests.append(VNCoreMLRequest(
        model: try VNCoreMLModel(for: test().model),
        completionHandler: handleEmotionClassification
      ))
    } catch {
      assertionFailure("Can't load Vision ML model: \(error)")
    }
  }

      Fatal error: Can't load Vision ML model: Error Domain=com.apple.vis Code=15
    "The model does not have a valid input feature of type image"
    UserInfo={NSLocalizedDescription=The model does not have a valid input feature of type image}:
    file /Users/ivandimitrov/Desktop/Faces/Faces/ClassificationService.swift, line 38

Do you have any ideas on how to fix that?


问:
How to pass URL from ListView item to web browser URL
How can the URL data within a list view item be passed to a web browser to open? My current code isn't working for some reason.

The name 'item' does not exist in the current context

page class

```<code>    public sealed partial class MainPage : Page
    {
        public List<ListItem> listItemCompanies;

        public MainPage()
        {
            this.InitializeComponent();

            listItemCompanies = ItemManager.GetListItems();
        }

        private async void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            foreach (var item in e.AddedItems)
            {
                showWebsite();
            }
        }

        private async void showWebsite()
        {
            var title = item as ListItem;

            var uriWeb = new Uri(title.CompanyURL);
            var uriSuccess = await Launcher.LaunchUriAsync(uriWeb);
        }
    }
}
</code>```

list item class

```<code>namespace MyApp.Models
{
    public class ListItem
    {
        public string CompanyTitle { get; set; }
        public string CompanyURL { get; set; }
    }

    public class ItemManager
    {
        public static List<ListItem> GetListItems()
        {
            var items = new List<ListItem>
            {
                new ListItem { CompanyTitle = "Apple", CompanyURL = "www.apple.com" },
                new ListItem { CompanyTitle = "Google", CompanyURL = "www.google.com" },
                new ListItem { CompanyTitle = "Microsoft", CompanyURL = "www.microsoft.com" }
            };

            return items;
        }
    }
}
</code>```

答:
Based on the document of Uri, there are essentially three components to a URI, the first part is scheme. Taking the web URL as an example, the scheme part is "http://". So when you try to create a Uri class, you also need to pass the "http://" instead of only "www.apple.com". In addition, when the ListView_SelectionChanged event is triggered, you can call the SelectedItem property of ListView to get the model you current click. For example:

```<code>private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    object item = (sender as ListView).SelectedItem;
    showWebsite(item);
}

private async void showWebsite(object item)
{
    var title = item as ListItem;

    var uriWeb = new Uri("http://" + title.CompanyURL);
    var uriSuccess = await Launcher.LaunchUriAsync(uriWeb);
}
</code>```

Update:

If you want to use ItemClick event, you need to set the IsItemClickEnabled of ListView as True.

.xaml:

```<code><ListView ... IsItemClickEnabled="True" ItemClick="ListView_ItemClick">
    ......
</ListView>
</code>```

.cs:

```<code>private void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
    object item = (sender as ListView).SelectedItem;
    showWebsite(item);
}
</code>```

Body:
How can the URL data within a list view item be passed to a web browser to open? My current code isn't working for some reason.

The name 'item' does not exist in the current context

page class

    public sealed partial class MainPage : Page
    {
        public List<ListItem> listItemCompanies;

        public MainPage()
        {
            this.InitializeComponent();

            listItemCompanies = ItemManager.GetListItems();
        }

        private async void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            foreach (var item in e.AddedItems)
            {
                showWebsite();
            }
        }

        private async void showWebsite()
        {
            var title = item as ListItem;

            var uriWeb = new Uri(title.CompanyURL);
            var uriSuccess = await Launcher.LaunchUriAsync(uriWeb);
        }
    }
}

list item class

namespace MyApp.Models
{
    public class ListItem
    {
        public string CompanyTitle { get; set; }
        public string CompanyURL { get; set; }
    }

    public class ItemManager
    {
        public static List<ListItem> GetListItems()
        {
            var items = new List<ListItem>
            {
                new ListItem { CompanyTitle = "Apple", CompanyURL = "www.apple.com" },
                new ListItem { CompanyTitle = "Google", CompanyURL = "www.google.com" },
                new ListItem { CompanyTitle = "Microsoft", CompanyURL = "www.microsoft.com" }
            };

            return items;
        }
    }
}

Body:
Based on the document of Uri, there are essentially three components to a URI, the first part is scheme. Taking the web URL as an example, the scheme part is "http://". So when you try to create a Uri class, you also need to pass the "http://" instead of only "www.apple.com". In addition, when the ListView_SelectionChanged event is triggered, you can call the SelectedItem property of ListView to get the model you current click. For example:

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    object item = (sender as ListView).SelectedItem;
    showWebsite(item);
}

private async void showWebsite(object item)
{
    var title = item as ListItem;

    var uriWeb = new Uri("http://" + title.CompanyURL);
    var uriSuccess = await Launcher.LaunchUriAsync(uriWeb);
}

Update:

If you want to use ItemClick event, you need to set the IsItemClickEnabled of ListView as True.

.xaml:

<ListView ... IsItemClickEnabled="True" ItemClick="ListView_ItemClick">
    ......
</ListView>

.cs:

private void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
    object item = (sender as ListView).SelectedItem;
    showWebsite(item);
}


问:
How to customize form django with fields of the diferents Models
I need to display a field on a form and another field on a Model in html page.

```<code>class CatracaForm(forms.Form):
    ra = forms.CharField(label='RA', max_length=30)

class MotivoForm(forms.ModelForm):
    class Meta:
        model = Motivo
        fields = ['descrmotivo', 'obs']
</code>```

In my HTML page I want show ra and descrmotivo field.
The descrmotivo field  should be a combobox component.

How to make this?

答:
```<code># if you want to show 'ra' and 'descrmotivo', then you can define a custom field in the same class.

class MotivoForm(forms.ModelForm):
    ra = forms.CharField(label='RA', max_length=30)
    class Meta:
        model = Motivo
        fields = ['descrmotivo', 'ra']

# If you want to show combobox for 'descrmotivo' field, then you can use 'choices' option in your model, For example

models.py

PROGRESS_STATUS = (
    ('Assigned','Assigned'),
    ('In Progress','In Progress'),
    ('Completed','Completed'),
)

class Motivo(models.Model):
    descrmotivo = models.CharField(choices=PROGRESS_STATUS, max_length=100)

    def __str__(self):
        return self.descrmotivo

# this will show a combobox which will have an option of 'Assigned', 'In Progress', 'Completed'
</code>```

Body:
I need to display a field on a form and another field on a Model in html page.

class CatracaForm(forms.Form):
    ra = forms.CharField(label='RA', max_length=30)

class MotivoForm(forms.ModelForm):
    class Meta:
        model = Motivo
        fields = ['descrmotivo', 'obs']

In my HTML page I want show ra and descrmotivo field.
The descrmotivo field  should be a combobox component.

How to make this?


问:
Change ListView status when found new result
Could anybody help me I already spent about 2 hours just for fixing my problem with ListView

what I did is, if the text (from lbloutputName.text) found in ListView item, it will highlight and will show the status of Processing...

Here's my question. How I can change the status to Done if the searchItem found new text from my output logs?

Here's what I'm thinking but I don't know how to do it.

For example, if I found STRING1 the status will be Processing... and it will highlight the item in the ListView and then if found new STRING2, STRING1 status must change to Done. and then STRING2 will be Processing again.

Here's the code:

Dim searchItem As String = lblOutputName.Text

For Each lvi As ListViewItem In LV.Items
    For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
        If lvisub.Text = searchItem Then
            lvi.BackColor = Color.SteelBlue
            lvi.ForeColor = Color.White
            lvi.SubItems.Add("Processing...")
            LV.Focus()
            Exit For
        End If
    Next
Next
```

Here's my screenshot for my tool:

答:
I already solved the problem specially with updating the status and also the flickering problem with using (maybe might help other too)

```<code>Public Class ffListView
    Inherits ListView

    Public Sub New()
        Me.DoubleBuffered = True
    End Sub
End Class
</code>```

and I modified my code with your ideas. althought I did not used your given code but it's really help me a lot to fix my problem.
I just decided instead of displaying the processing and done. I just display the progress

```<code> Dim searchItem As String = lblOutputName.Text
                For Each lvi As ListViewItem In LV.Items
                    For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
                        If lvisub.Text = searchItem Then
                            lvi.BackColor = Color.FromArgb(0, 99, 177)
                            lvi.ForeColor = Color.White
                            lvi.Text = String.Format("{0:F}", Progress).ToString & "%"

                            If lvi.Text = "100.00%" Then
                                lvi.BackColor = Color.FromArgb(4, 117, 24)
                                lvi.ForeColor = Color.White
                            End If
                            If abort Then
                                lvi.BackColor = Color.DarkRed
                                lvi.ForeColor = Color.White
                            End If
                            Exit For

                        End If

                    Next
                Next
</code>```

Body:
Could anybody help me I already spent about 2 hours just for fixing my problem with ListView

what I did is, if the text (from lbloutputName.text) found in ListView item, it will highlight and will show the status of Processing...

Here's my question. How I can change the status to Done if the searchItem found new text from my output logs?

Here's what I'm thinking but I don't know how to do it.

For example, if I found STRING1 the status will be Processing... and it will highlight the item in the ListView and then if found new STRING2, STRING1 status must change to Done. and then STRING2 will be Processing again.

Here's the code:

Dim searchItem As String = lblOutputName.Text

For Each lvi As ListViewItem In LV.Items
    For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
        If lvisub.Text = searchItem Then
            lvi.BackColor = Color.SteelBlue
            lvi.ForeColor = Color.White
            lvi.SubItems.Add("Processing...")
            LV.Focus()
            Exit For
        End If
    Next
Next

Here's my screenshot for my tool:

Body:
I already solved the problem specially with updating the status and also the flickering problem with using (maybe might help other too)

Public Class ffListView
    Inherits ListView

    Public Sub New()
        Me.DoubleBuffered = True
    End Sub
End Class

and I modified my code with your ideas. althought I did not used your given code but it's really help me a lot to fix my problem.
I just decided instead of displaying the processing and done. I just display the progress

 Dim searchItem As String = lblOutputName.Text
                For Each lvi As ListViewItem In LV.Items
                    For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
                        If lvisub.Text = searchItem Then
                            lvi.BackColor = Color.FromArgb(0, 99, 177)
                            lvi.ForeColor = Color.White
                            lvi.Text = String.Format("{0:F}", Progress).ToString & "%"

                            If lvi.Text = "100.00%" Then
                                lvi.BackColor = Color.FromArgb(4, 117, 24)
                                lvi.ForeColor = Color.White
                            End If
                            If abort Then
                                lvi.BackColor = Color.DarkRed
                                lvi.ForeColor = Color.White
                            End If
                            Exit For

                        End If

                    Next
                Next


问:
Fortran array input
I haven't done any Fortran programming for year and it seems I'm rather rusty now. So, I won't provide you with all my failed attempts but will humbly ask you to help me with the following.
I've got the following "input" file

```<code>1 5 e 4
A b & 1
c Z ; b
y } " N
t r ' +
</code>```

It can have more columns and/or rows. I would now like to assign each of these ASCII characters to arrays x(i,j) so that I can process them further after ICHAR conversions. In this example i=1,4, j=1,5, but it can be any No depending on the input file. The simplest example

```<code>PROGRAM Example
integer :: i, j
CHARACTER, ALLOCATABLE, DIMENSION(:,:) :: A
READ *, A
ALLOCATE (A(i,j))
PRINT *, A
END PROGRAM Example
</code>```

compiles (Example.f95) but

```<code>cat input | ./Example.f95
</code>```

does not give any output.
I would greatly appreciate an advice on how to import the afore-mentioned strings into the program as x(i,j) terms of an array.

答:
You need to read the first line and determine how characters there in the line.  Then read the entire file to determine the number of lines.  Allocate the 2D array to hold characters.  Then read the file and parse each line into the 2D array.  There are more elegant ways of doing this, but here you go

```<code>  program foo

  implicit none

  character(len=:), allocatable :: s
  character, allocatable :: a(:,:)
  integer fd, i, j, n, nr, nc
  !
  ! Open file for reading
  !
  open(newunit=fd, file='tmp.dat', status='old', err=9)
  !
  ! Determine number of characters in a row.  Assumes all rows
  ! are of the same length.
  !
  n = 128
1 if (allocated(s)) then
     deallocate(s)
     n = 2 * n
  end if
  allocate(character(len=n) :: s)
  read(fd,'(A)') s
  if (len_trim(s) == 128) goto 1
  s = adjustl(s)
  n = len_trim(s)
  deallocate(s)
  !
  ! Allocate a string of the correct length.
  !
  allocate(character(len=n) :: s)
  !
  ! Count the number of rows
  !
  rewind(fd)
  nr = 0
  do
     read(fd,*,end=2)
     nr = nr + 1
  end do
  !
  ! Read file and store individual characters in a(:,:)
  !
2 rewind(fd)
  nc = n / 2 + 1
  allocate(a(nr,nc))
  do i = 1, nr
     read(fd,'(A)') s
     do j = 1, nc
        a(i,j) = s(2*j-1:2*j-1)
     end do
  end do
  close(fd)
  write(s,'(I0)') nc
  s = '('  // trim(s) // '(A,1X))'
  do i = 1, nr
     write(*,s) a(i,:)
  end do
  stop
9 write(*,'(A)') 'Error: cannot open tmp.dat'
  end program foo
</code>```

Apparently, GOTO is verbotem, here.  Here's an elegant solution.

```<code>  program foo

  implicit none

  character, allocatable :: s(:), a(:,:)
  integer fd, i, j, n, nr, nc

  ! Open file for reading
  open(newunit=fd, file='tmp.dat', status='old', access='stream', err=9)

  inquire(fd, size = n) ! Determine file size.
  allocate(s(n))        ! Allocate space
  read(fd) s            ! Read the entire file

  close(fd)

  nr = count(ichar(s) == 10)             ! Number of rows
  nc = (count(ichar(s) /= 32) - nr) / nr ! Number of columns

  a = reshape(pack(s, ichar(s) /= 32 .and. ichar(s) /= 10), [nc,nr])
  a = transpose(a)

  do i = 1, nr
     do j = 1, nc
        write(*,'(A,1X)',advance='no') a(i,j)
     end do
     write(*,*)
  end do
  stop
9 write(*,'(A)') 'Error: cannot open tmp.dat'
  end program foo
</code>```

Title: Fortran array input

Body:
I haven't done any Fortran programming for year and it seems I'm rather rusty now. So, I won't provide you with all my failed attempts but will humbly ask you to help me with the following.
I've got the following "input" file

1 5 e 4
A b & 1
c Z ; b
y } " N
t r ' +

It can have more columns and/or rows. I would now like to assign each of these ASCII characters to arrays x(i,j) so that I can process them further after ICHAR conversions. In this example i=1,4, j=1,5, but it can be any No depending on the input file. The simplest example

PROGRAM Example
integer :: i, j
CHARACTER, ALLOCATABLE, DIMENSION(:,:) :: A
READ *, A
ALLOCATE (A(i,j))
PRINT *, A
END PROGRAM Example

compiles (Example.f95) but

cat input | ./Example.f95

does not give any output.
I would greatly appreciate an advice on how to import the afore-mentioned strings into the program as x(i,j) terms of an array.

Body:
You need to read the first line and determine how characters there in the line.  Then read the entire file to determine the number of lines.  Allocate the 2D array to hold characters.  Then read the file and parse each line into the 2D array.  There are more elegant ways of doing this, but here you go

  program foo

  implicit none

  character(len=:), allocatable :: s
  character, allocatable :: a(:,:)
  integer fd, i, j, n, nr, nc
  !
  ! Open file for reading
  !
  open(newunit=fd, file='tmp.dat', status='old', err=9)
  !
  ! Determine number of characters in a row.  Assumes all rows
  ! are of the same length.
  !
  n = 128
1 if (allocated(s)) then
     deallocate(s)
     n = 2 * n
  end if
  allocate(character(len=n) :: s)
  read(fd,'(A)') s
  if (len_trim(s) == 128) goto 1
  s = adjustl(s)
  n = len_trim(s)
  deallocate(s)
  !
  ! Allocate a string of the correct length.
  !
  allocate(character(len=n) :: s)
  !
  ! Count the number of rows
  !
  rewind(fd)
  nr = 0
  do
     read(fd,*,end=2)
     nr = nr + 1
  end do
  !
  ! Read file and store individual characters in a(:,:)
  !
2 rewind(fd)
  nc = n / 2 + 1
  allocate(a(nr,nc))
  do i = 1, nr
     read(fd,'(A)') s
     do j = 1, nc
        a(i,j) = s(2*j-1:2*j-1)
     end do
  end do
  close(fd)
  write(s,'(I0)') nc
  s = '('  // trim(s) // '(A,1X))'
  do i = 1, nr
     write(*,s) a(i,:)
  end do
  stop
9 write(*,'(A)') 'Error: cannot open tmp.dat'
  end program foo

Apparently, GOTO is verbotem, here.  Here's an elegant solution.

  program foo

  implicit none

  character, allocatable :: s(:), a(:,:)
  integer fd, i, j, n, nr, nc

  ! Open file for reading
  open(newunit=fd, file='tmp.dat', status='old', access='stream', err=9)

  inquire(fd, size = n) ! Determine file size.
  allocate(s(n))        ! Allocate space
  read(fd) s            ! Read the entire file

  close(fd)

  nr = count(ichar(s) == 10)             ! Number of rows
  nc = (count(ichar(s) /= 32) - nr) / nr ! Number of columns

  a = reshape(pack(s, ichar(s) /= 32 .and. ichar(s) /= 10), [nc,nr])
  a = transpose(a)

  do i = 1, nr
     do j = 1, nc
        write(*,'(A,1X)',advance='no') a(i,j)
     end do
     write(*,*)
  end do
  stop
9 write(*,'(A)') 'Error: cannot open tmp.dat'
  end program foo


问:
Tracing user permissions in Google Cloud IAM
On a certain project, how can one see 'WHO' assigned 'WHOM', 'WHAT' role or permissions?
Example: Person 1 is IAM Admin, and granted Person 2 BigQuery Admin role. Is there a way to trace Person 1 granted Person 2 the respective role?</p>

答:
You can search the IAM setpolicy logs via advance filter in cloud console > logging > log viewer:

```<code>protoPayload.methodName="SetIamPolicy"
protoPayload.serviceName="cloudresourcemanager.googleapis.com"
protoPayload.serviceData.policyDelta.bindingDeltas.member="Person2 account"
protoPayload.request.policy.bindings.role="role name"
</code>```

Expand the log, the Person 1 account will shows in "authenticationInfo" section, please note that IAM setpolicy log is kept in 400 days.

Body:
You can search the IAM setpolicy logs via advance filter in cloud console > logging > log viewer:

protoPayload.methodName="SetIamPolicy"
protoPayload.serviceName="cloudresourcemanager.googleapis.com"
protoPayload.serviceData.policyDelta.bindingDeltas.member="Person2 account"
protoPayload.request.policy.bindings.role="role name"

Expand the log, the Person 1 account will shows in "authenticationInfo" section, please note that IAM setpolicy log is kept in 400 days.


问:
Most efficient way in Python to iterate over a large file (10GB+)
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

```<code>    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1
</code>```

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)

答:
This is not a 5-line answer to your question, but there was an excellent tutorial given at PyCon'08 called Generator Tricks for System Programmers. There is also a followup tutorial called A Curious Course on Coroutines and Concurrency.

The Generator tutorial specifically uses big log file processing as its example.

Body:
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)


问:
VS 2010 Test Runner error "The agent process was stopped while the test was running."
In Visual Studio 2010, I have a number of unit tests. When I run multiple tests at one time using test lists, I sometimes reveive the following error for one or more of the tests:

The agent process was stopped while
the test was running.

It is never the same test failing, and if I try to run the test again, it succeeds.

I found this bug report on Connect, which seems to be the same problem, but it does not offer a solution.

Has anyone else seen this behaviour ? How I can avoid it ?

Edit

I am still experiencing this bug, and so is many of my colleagues on the same software/hardware setup. I have evaluated the answers so far, but they don't resolve the problem. I am starting a bounty for a solution to this problem.

答:
For anyone happening upon this old question and wondering what's being thrown from their thread(s), here's a tip. Using Task.Run (as opposed to, say, Thread.Start) will report child thread exceptions much more reliably. In short, instead of this:

```<code>Thread t = new Thread(FunctionThatThrows);
t.Start();
t.Join();
</code>```

Do this:

```<code>Task t = Task.Run(() => FunctionThatThrows());
t.Wait();
</code>```

And your error logs should be much more useful.

ContentLicense: CC BY-SA 2.5

Body:
For anyone happening upon this old question and wondering what's being thrown from their thread(s), here's a tip. Using Task.Run (as opposed to, say, Thread.Start) will report child thread exceptions much more reliably. In short, instead of this:

Thread t = new Thread(FunctionThatThrows);
t.Start();
t.Join();

Do this:

Task t = Task.Run(() => FunctionThatThrows());
t.Wait();

And your error logs should be much more useful.