问:
Alternative to parsing json with option [ either [A,B ] ] in scala
For example, here payload is optional and it has 3 variants:

How can I parse the json with types like option[either[A,B,C]] but to use abstract data type using things sealed trait or sum type?

Below is a minimal example with some boiler plate:

https://scalafiddle.io/sf/K6RUWqk/1

```<code>
// Start writing your ScalaFiddle code here
val json =
  """[
       {
         "id": 1,
         "payload" : "data"
       },
       {
         "id": 2.1,
         "payload" : {
           "field1" : "field1",
           "field2" : 5,
           "field3" : true
         }
       },
      {
         "id": 2.2,
         "payload" : {
           "field1" : "field1",
         }
       },
       {
         "id": 3,
          payload" : 4
       },
       {
         "id":4,
          "
       }
     ]"""

final case class Data(field1: String, field2: Option[Int])
type Payload = Either[String, Data]
final case class Record(id: Int, payload: Option[Payload])

import io.circe.Decoder
import io.circe.generic.semiauto.deriveDecoder

implicit final val dataDecoder: Decoder[Data] = deriveDecoder
implicit final val payloadDecoder: Decoder[Payload] = Decoder[String] either Decoder[Data]
implicit final val recordDecoder: Decoder[Record] = deriveDecoder

val result = io.circe.parser.decode[List[Record]](json)
println(result)
</code>```

答:
Your code is almost fine, you have just syntax issues in your json and Record.id should be Double instead of Int - because it is how this field present in your json ("id": 2.1). Please, find fixed version below:

```<code>val json =
      s"""[
       {
         "id": 1,
         "payload" : "data"
       },
       {
         "id": 2.1,
         "payload" : {
           "field1" : "field1",
           "field2" : 5,
           "field3" : true
         }
       },
       {
         "id": 2.2,
         "payload" : {
           "field1" : "field1"
         }
       },

       {
         "id": 3,
         "payload" : 4
       },

       {
         "id": 4
       }
     ]"""

    type Payload = Either[String, Data]
    final case class Data(field1: String, field2: Option[Int])
    final case class Record(id: Double, payload: Option[Payload]) // id is a Double in your json in some cases

    import io.circe.Decoder
    import io.circe.generic.semiauto.deriveDecoder

    implicit val dataDecoder: Decoder[Data] = deriveDecoder
    implicit val payloadDecoder: Decoder[Payload] = Decoder[String] either Decoder[Data]
    implicit val recordDecoder: Decoder[Record] = deriveDecoder

    val result = io.circe.parser.decode[List[Record]](json)
    println(result)
</code>```

Which produced in my case:

```<code>Right(List(Record(1.0,Some(Left(data))), Record(2.1,Some(Right(Data(field1,Some(5))))), Record(2.2,Some(Right(Data(field1,None)))), Record(3.0,Some(Left(4))), Record(4.0,None)))
</code>```

UPDATE:

The more general approach would be to use so-called Sum Types or in simple words - general sealed trait with several different implementations. Please, see for more details next Circe doc page : https://circe.github.io/circe/codecs/adt.html

In your case it can be achieved something like this:

```<code>import cats.syntax.functor._
  import io.circe.Decoder
  import io.circe.generic.semiauto.deriveDecoder

  sealed trait Payload

  object Payload {
    implicit val decoder: Decoder[Payload] = {
      List[Decoder[Payload]](
        Decoder[StringPayload].widen,
        Decoder[IntPayload].widen,
        Decoder[ObjectPayload].widen
      ).reduce(_ or _)
    }
  }

  case class StringPayload(value: String) extends Payload

  object StringPayload {
    implicit val decoder: Decoder[StringPayload] = Decoder[String].map(StringPayload.apply)
  }

  case class IntPayload(value: Int) extends Payload

  object IntPayload {
    implicit val decoder: Decoder[IntPayload] = Decoder[Int].map(IntPayload.apply)
  }

  case class ObjectPayload(field1: String, field2: Option[Int]) extends Payload

  object ObjectPayload {
    implicit val decoder: Decoder[ObjectPayload] = deriveDecoder
  }

  final case class Record(id: Double, payload: Option[Payload])

  object Record {
    implicit val decoder: Decoder[Record] = deriveDecoder
  }

  def main(args: Array[String]): Unit = {
    val json =
      s"""[
       {
         "id": 1,
         "payload" : "data"
       },
       {
         "id": 2.1,
         "payload" : {
           "field1" : "field1",
           "field2" : 5,
           "field3" : true
         }
       },
       {
         "id": 2.2,
         "payload" : {
           "field1" : "field1"
         }
       },
       {
         "id": 3,
         "payload" : "4"
       },
       {
         "id": 4
       }
     ]"""

    val result = io.circe.parser.decode[List[Record]](json)
    println(result)
  }
</code>```

which produced in my case next output:

```<code>Right(List(Record(1.0,Some(StringPayload(data))), Record(2.1,Some(ObjectPayload(field1,Some(5)))), Record(2.2,Some(ObjectPayload(field1,None))), Record(3.0,Some(StringPayload(4))), Record(4.0,None)))
</code>```

Hope this helps!

Body:
For example, here payload is optional and it has 3 variants:

How can I parse the json with types like option[either[A,B,C]] but to use abstract data type using things sealed trait or sum type?

Below is a minimal example with some boiler plate:

https://scalafiddle.io/sf/K6RUWqk/1

// Start writing your ScalaFiddle code here
val json =
  """[
       {
         "id": 1,
         "payload" : "data"
       },
       {
         "id": 2.1,
         "payload" : {
           "field1" : "field1",
           "field2" : 5,
           "field3" : true
         }
       },
      {
         "id": 2.2,
         "payload" : {
           "field1" : "field1",
         }
       },
       {
         "id": 3,
          payload" : 4
       },
       {
         "id":4,
          "
       }
     ]"""

final case class Data(field1: String, field2: Option[Int])
type Payload = Either[String, Data]
final case class Record(id: Int, payload: Option[Payload])

import io.circe.Decoder
import io.circe.generic.semiauto.deriveDecoder

implicit final val dataDecoder: Decoder[Data] = deriveDecoder
implicit final val payloadDecoder: Decoder[Payload] = Decoder[String] either Decoder[Data]
implicit final val recordDecoder: Decoder[Record] = deriveDecoder

val result = io.circe.parser.decode[List[Record]](json)
println(result)

Body:
Your code is almost fine, you have just syntax issues in your json and Record.id should be Double instead of Int - because it is how this field present in your json ("id": 2.1). Please, find fixed version below:

val json =
      s"""[
       {
         "id": 1,
         "payload" : "data"
       },
       {
         "id": 2.1,
         "payload" : {
           "field1" : "field1",
           "field2" : 5,
           "field3" : true
         }
       },
       {
         "id": 2.2,
         "payload" : {
           "field1" : "field1"
         }
       },

       {
         "id": 3,
         "payload" : 4
       },

       {
         "id": 4
       }
     ]"""

    type Payload = Either[String, Data]
    final case class Data(field1: String, field2: Option[Int])
    final case class Record(id: Double, payload: Option[Payload]) // id is a Double in your json in some cases

    import io.circe.Decoder
    import io.circe.generic.semiauto.deriveDecoder

    implicit val dataDecoder: Decoder[Data] = deriveDecoder
    implicit val payloadDecoder: Decoder[Payload] = Decoder[String] either Decoder[Data]
    implicit val recordDecoder: Decoder[Record] = deriveDecoder

    val result = io.circe.parser.decode[List[Record]](json)
    println(result)

Which produced in my case:

Right(List(Record(1.0,Some(Left(data))), Record(2.1,Some(Right(Data(field1,Some(5))))), Record(2.2,Some(Right(Data(field1,None)))), Record(3.0,Some(Left(4))), Record(4.0,None)))

UPDATE:

The more general approach would be to use so-called Sum Types or in simple words - general sealed trait with several different implementations. Please, see for more details next Circe doc page : https://circe.github.io/circe/codecs/adt.html

In your case it can be achieved something like this:

import cats.syntax.functor._
  import io.circe.Decoder
  import io.circe.generic.semiauto.deriveDecoder

  sealed trait Payload

  object Payload {
    implicit val decoder: Decoder[Payload] = {
      List[Decoder[Payload]](
        Decoder[StringPayload].widen,
        Decoder[IntPayload].widen,
        Decoder[ObjectPayload].widen
      ).reduce(_ or _)
    }
  }

  case class StringPayload(value: String) extends Payload

  object StringPayload {
    implicit val decoder: Decoder[StringPayload] = Decoder[String].map(StringPayload.apply)
  }

  case class IntPayload(value: Int) extends Payload

  object IntPayload {
    implicit val decoder: Decoder[IntPayload] = Decoder[Int].map(IntPayload.apply)
  }

  case class ObjectPayload(field1: String, field2: Option[Int]) extends Payload

  object ObjectPayload {
    implicit val decoder: Decoder[ObjectPayload] = deriveDecoder
  }

  final case class Record(id: Double, payload: Option[Payload])

  object Record {
    implicit val decoder: Decoder[Record] = deriveDecoder
  }

  def main(args: Array[String]): Unit = {
    val json =
      s"""[
       {
         "id": 1,
         "payload" : "data"
       },
       {
         "id": 2.1,
         "payload" : {
           "field1" : "field1",
           "field2" : 5,
           "field3" : true
         }
       },
       {
         "id": 2.2,
         "payload" : {
           "field1" : "field1"
         }
       },
       {
         "id": 3,
         "payload" : "4"
       },
       {
         "id": 4
       }
     ]"""

    val result = io.circe.parser.decode[List[Record]](json)
    println(result)
  }

which produced in my case next output:

Right(List(Record(1.0,Some(StringPayload(data))), Record(2.1,Some(ObjectPayload(field1,Some(5)))), Record(2.2,Some(ObjectPayload(field1,None))), Record(3.0,Some(StringPayload(4))), Record(4.0,None)))

Hope this helps!


来源: stackexchange

问:
Error in Opening Electron App in Mac:"file:///Applications/../Contents/Resources/app.asar/dist/index.html"
I have build the electron app for mac but when I ran it , it is giving the below error

"Not allowed to load local resource: file:///Applications/e-admin.app/Contents/Resources/app.asar/dist/index.html".

Here are the steps I did.

1) electron-builder build --mac
It created the following files are dist folder.
a) e-admin-0.0.0.dmg , e-admin-0.0.0-mac.zip,index.html and a mac folder
b) in mac folder I could see mac/e-admin.app/Contents/Resources/app.asar file( not the folder)

2) I double clicked and installed  the e-admin-0.0.0.dmg and moved to application folder.
3) Opened the app.

Do I have to do any thing with app.asar file?(unpack or some thing?) or any etc procedure to make it work?

my package.json

```<code>{
  "name": "e-admin",
  "version": "0.0.0",
  "scripts": {
    "postinstall": "electron-builder install-app-deps",
    "ng": "ng",
    "start": "npm-run-all -p electron:serve ng:serve",
    "build": "npm run electron:serve-tsc && ng build",
    "build:dev": "npm run build -- -c dev",
    "build:prod": "npm run build -- -c production",
    "ng:serve": "ng serve",
    "ng:serve:web": "ng serve -c web -o",
    "electron:serve-tsc": "tsc -p tsconfig-serve.json",
    "electron:serve": "wait-on http-get://localhost:4200/ && npm run electron:serve-tsc && electron . --serve",
    "electron:local": "npm run build:prod && electron .",
    "electron:linux": "npm run build:prod && electron-builder build --linux",
    "electron:windows": "npm run build:prod && electron-builder build --windows",
    "electron:mac": "npm run build:prod && electron-builder build --mac",
    "test": "ng test",
    "e2e": "npm run build:prod && cross-env TS_NODE_PROJECT='e2e/tsconfig.e2e.json' mocha --timeout 300000 --require ts-node/register e2e/**/*.e2e.ts",
    "version": "conventional-changelog -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md",
    "lint": "ng lint"
  },
  "main": "main.js",
  "private": true,
  "dependencies": {...}
</code>```

and angular.josn file

```<code>"projects": {
    "eAdmin": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
....
</code>```

main.ts contains

```<code>if (serve) {
    require('electron-reload')(__dirname, {
      electron: require(`${__dirname}/node_modules/electron`)
    });
    win.loadURL('http://localhost:4200');
  } else {
    win.loadURL(url.format({
      pathname: path.join(__dirname, 'dist/index.html'),
      protocol: 'file:',
      slashes: true
    }));
  }
</code>```

答:
After muiltple trial and error, The following changes worked for me

1) index.html

```<code>`<base href="/">`
</code>```

to

```<code><base href="./">
</code>```

2) in main.ts, change the directory name dist to something else

from :

```<code>win.loadURL(url.format({
  pathname: path.join(__dirname, 'dist/index.html'),
  protocol: 'file:',
  slashes: true
}));
</code>```

To:

```<code>win.loadURL(url.format({
  pathname: path.join(__dirname, 'angular_build/index.html'),
  protocol: 'file:',
  slashes: true
}));
</code>```

3) Angular.js

```<code>"outputPath": "dist/",
</code>```

to

```<code>"outputPath": "angular_build/",
</code>```

Although I have seen suggesions to change step 2 & 3 , I was quite skepitcal.
Looks like dist directlory some how does not work and have to change to some thing like as mentioned above

ContentLicense: CC BY-SA 4.0

Body:
I have build the electron app for mac but when I ran it , it is giving the below error

"Not allowed to load local resource: file:///Applications/e-admin.app/Contents/Resources/app.asar/dist/index.html".

Here are the steps I did.

1) electron-builder build --mac
It created the following files are dist folder.
a) e-admin-0.0.0.dmg , e-admin-0.0.0-mac.zip,index.html and a mac folder
b) in mac folder I could see mac/e-admin.app/Contents/Resources/app.asar file( not the folder)

2) I double clicked and installed  the e-admin-0.0.0.dmg and moved to application folder.
3) Opened the app.

Do I have to do any thing with app.asar file?(unpack or some thing?) or any etc procedure to make it work?

my package.json

{
  "name": "e-admin",
  "version": "0.0.0",
  "scripts": {
    "postinstall": "electron-builder install-app-deps",
    "ng": "ng",
    "start": "npm-run-all -p electron:serve ng:serve",
    "build": "npm run electron:serve-tsc && ng build",
    "build:dev": "npm run build -- -c dev",
    "build:prod": "npm run build -- -c production",
    "ng:serve": "ng serve",
    "ng:serve:web": "ng serve -c web -o",
    "electron:serve-tsc": "tsc -p tsconfig-serve.json",
    "electron:serve": "wait-on http-get://localhost:4200/ && npm run electron:serve-tsc && electron . --serve",
    "electron:local": "npm run build:prod && electron .",
    "electron:linux": "npm run build:prod && electron-builder build --linux",
    "electron:windows": "npm run build:prod && electron-builder build --windows",
    "electron:mac": "npm run build:prod && electron-builder build --mac",
    "test": "ng test",
    "e2e": "npm run build:prod && cross-env TS_NODE_PROJECT='e2e/tsconfig.e2e.json' mocha --timeout 300000 --require ts-node/register e2e/**/*.e2e.ts",
    "version": "conventional-changelog -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md",
    "lint": "ng lint"
  },
  "main": "main.js",
  "private": true,
  "dependencies": {...}

and angular.josn file

"projects": {
    "eAdmin": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
....

main.ts contains

if (serve) {
    require('electron-reload')(__dirname, {
      electron: require(`${__dirname}/node_modules/electron`)
    });
    win.loadURL('http://localhost:4200');
  } else {
    win.loadURL(url.format({
      pathname: path.join(__dirname, 'dist/index.html'),
      protocol: 'file:',
      slashes: true
    }));
  }

Body:
After muiltple trial and error, The following changes worked for me

1) index.html

`<base href="/">`

to

<base href="./">

2) in main.ts, change the directory name dist to something else

from :

win.loadURL(url.format({
  pathname: path.join(__dirname, 'dist/index.html'),
  protocol: 'file:',
  slashes: true
}));

To:

win.loadURL(url.format({
  pathname: path.join(__dirname, 'angular_build/index.html'),
  protocol: 'file:',
  slashes: true
}));

3) Angular.js

"outputPath": "dist/",

to

"outputPath": "angular_build/",

Although I have seen suggesions to change step 2 & 3 , I was quite skepitcal.
Looks like dist directlory some how does not work and have to change to some thing like as mentioned above


问:
Conditionally include the branch name in an Azure DevOps build name
I'm using Azure DevOps to build a pipeline, but I wish to change the name of the build. This is entirely possible according to the documentation.

With that in mind, I tested the following, which worked. So far so good...

```<code>name: '1.0.$(Rev:r)-$(Build.SourceBranchName)'
</code>```

1.0.1-master

However, one of my requirements is to exclude the branch name if it's 'master', so I tried the following. This seemed to work in the first instance, as a 'master' did not have a branch name appended, but when I ran a feature branch I found that $(Build.SourceBranchName) was not being expanded.

```<code>variables:
  ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
    branchName: ''
  ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
    branchName: '-$(Build.SourceBranchName)'

name: '1.0.$(Rev:r)$(branchName)'
</code>```

I've since tried ${{ variables.Build.SourceBranchName }} and $[variables.Build.SourceBranchName] as described in the documentation, but as written they token is either ignored or returns an empty string. The three formats leave me with the following build names.

1.0.1-$(Build.SourceBranchName)

  1.0.1-

  1.0.1-$[variables.Build.SourceBranchName]

The documentation around custom naming makes mention of a variable $(SourceBranchName), but I've tried this and it also fails.

What I find confusing is that the expressions in the variables: segment can access the variable values as described here, but seemingly the variables: segment itself is unable to.

Is it possible to conditionally name the build so that I can include/exclude the branch name as required?

答:
Is it possible to conditionally name the build so that I can
  include/exclude the branch name as required?

An alternative workaround is to use PowerShell task to update the build number. Check this official document:

You can use something like: ##vso[build.updatebuildnumber]my-new-build-number.

Example:

```<code>name: 1.0.$(Rev:r)

steps:

- task: PowerShell@2
  condition: and(succeeded(), ne(variables['Build.SourceBranchName'], 'master'))
  inputs:
    targetType: 'inline'
    script: |
      $buildNumber = $Env:BUILD_BUILDNUMBER
      $revision= $buildNumber.Substring($buildNumber.LastIndexOf('.') + 1)
      Write-Host "##vso[build.updatebuildnumber]1.0.$revision-$(Build.SourceBranchName)"
</code>```

Copy this to your yaml, then it can work to meet your requirements above. About how to use $(rev:r) in task, get hint from this issue, thanks to Shayki Abramczyk!

Hope all above helps :)

Body:
I'm using Azure DevOps to build a pipeline, but I wish to change the name of the build. This is entirely possible according to the documentation.

With that in mind, I tested the following, which worked. So far so good...

name: '1.0.$(Rev:r)-$(Build.SourceBranchName)'

1.0.1-master

However, one of my requirements is to exclude the branch name if it's 'master', so I tried the following. This seemed to work in the first instance, as a 'master' did not have a branch name appended, but when I ran a feature branch I found that $(Build.SourceBranchName) was not being expanded.

variables:
  ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
    branchName: ''
  ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
    branchName: '-$(Build.SourceBranchName)'

name: '1.0.$(Rev:r)$(branchName)'

I've since tried ${{ variables.Build.SourceBranchName }} and $[variables.Build.SourceBranchName] as described in the documentation, but as written they token is either ignored or returns an empty string. The three formats leave me with the following build names.

1.0.1-$(Build.SourceBranchName)

  1.0.1-

  1.0.1-$[variables.Build.SourceBranchName]

The documentation around custom naming makes mention of a variable $(SourceBranchName), but I've tried this and it also fails.

What I find confusing is that the expressions in the variables: segment can access the variable values as described here, but seemingly the variables: segment itself is unable to.

Is it possible to conditionally name the build so that I can include/exclude the branch name as required?

Body:
Is it possible to conditionally name the build so that I can
  include/exclude the branch name as required?

An alternative workaround is to use PowerShell task to update the build number. Check this official document:

You can use something like: ##vso[build.updatebuildnumber]my-new-build-number.

Example:

name: 1.0.$(Rev:r)

steps:

- task: PowerShell@2
  condition: and(succeeded(), ne(variables['Build.SourceBranchName'], 'master'))
  inputs:
    targetType: 'inline'
    script: |
      $buildNumber = $Env:BUILD_BUILDNUMBER
      $revision= $buildNumber.Substring($buildNumber.LastIndexOf('.') + 1)
      Write-Host "##vso[build.updatebuildnumber]1.0.$revision-$(Build.SourceBranchName)"

Copy this to your yaml, then it can work to meet your requirements above. About how to use $(rev:r) in task, get hint from this issue, thanks to Shayki Abramczyk!

Hope all above helps :)


问:
Nested 3 level LINQ query
Here is my working SQL query I want write LINQ to
I have no idea to convert write 3 level nested query

```<code>Select *
from demo.dbo.Account
where accType = 3
and LinkAcc IN (
  select accNum
  from demo.dbo.Account
  here inkAcc IN (
    select accNum
    from demo.dbo.Account
    where memberid = 20
    and accType= 0
  )
  and accType = 2
)
</code>```

答:
When writing LINQ equivalents to a SQL IN(), you have to think about it in reverse.

Rather than the SQL

where entity-value IN sub-values

the LINQ expression becomes

where sub-values contains entity-value

Because writing this in one monolithic LINQ statement is mind-bending, I have broken each subquery into a separate variable.

```<code>using System.Linq;

public IEnumerable<Account> FilterAccounts(IEnumerable<Account> accounts)

  // start with the deepest subquery first
  var memberAccountNums = accounts
    .Where(x => x.MemberId == 20 && x.AccType == 0)
    .Select(x => x.AccNum)
    .ToArray();

  var linkAccountNums = accounts
    .Where(x => x.AccType == 2 && memberAccountNums.Contains(x.AccNum))
    .Select(x => x.AccNum)
    .ToArray();

  var result = accounts
    .Where(x => x.AccType == 3 && linkAccountNums.Contains(x.AccNum))
    .ToArray();

  return result;
}
</code>```

I have used a method here to demonstrate a compilable version of the code (assuming the class and property names are correct). You would obviously want to parameterise this to meet your needs.

If you want to combine them for some reason (say LINQ-to-SQL), then you could write it as one query, or you could instead use a series of IQueryable variables instead of calling .ToArray().

I have created a working demo here: https://dotnetfiddle.net/pg0WLC

I assume that the logic is you want to return all accounts with AccType 3 where there is also a matching AccNum for AccType 0 and 2? This assumes that the MemberId property will match if the AccNum properties do.

Another way of doing this with LINQ would be to use group by:

```<code>int[] types = new int[] { 0, 2, 3 };

return accounts
  .Where(x => x.MemberId == 20 && types.Contains(x.AccType))
  .GroupBy(x => x.AccNum)
  .Where(x => x.Count() == types.Count())
  .SelectMany(x => x)
  .Where(x => x.AccType == 3);
</code>```

Title: Nested 3 level LINQ query

Body:
Here is my working SQL query I want write LINQ to
I have no idea to convert write 3 level nested query

Select *
from demo.dbo.Account
where accType = 3
and LinkAcc IN (
  select accNum
  from demo.dbo.Account
  here inkAcc IN (
    select accNum
    from demo.dbo.Account
    where memberid = 20
    and accType= 0
  )
  and accType = 2
)

Body:
When writing LINQ equivalents to a SQL IN(), you have to think about it in reverse.

Rather than the SQL

where entity-value IN sub-values

the LINQ expression becomes

where sub-values contains entity-value

Because writing this in one monolithic LINQ statement is mind-bending, I have broken each subquery into a separate variable.

using System.Linq;

public IEnumerable<Account> FilterAccounts(IEnumerable<Account> accounts)

  // start with the deepest subquery first
  var memberAccountNums = accounts
    .Where(x => x.MemberId == 20 && x.AccType == 0)
    .Select(x => x.AccNum)
    .ToArray();

  var linkAccountNums = accounts
    .Where(x => x.AccType == 2 && memberAccountNums.Contains(x.AccNum))
    .Select(x => x.AccNum)
    .ToArray();

  var result = accounts
    .Where(x => x.AccType == 3 && linkAccountNums.Contains(x.AccNum))
    .ToArray();

  return result;
}

I have used a method here to demonstrate a compilable version of the code (assuming the class and property names are correct). You would obviously want to parameterise this to meet your needs.

If you want to combine them for some reason (say LINQ-to-SQL), then you could write it as one query, or you could instead use a series of IQueryable variables instead of calling .ToArray().

I have created a working demo here: https://dotnetfiddle.net/pg0WLC

I assume that the logic is you want to return all accounts with AccType 3 where there is also a matching AccNum for AccType 0 and 2? This assumes that the MemberId property will match if the AccNum properties do.

Another way of doing this with LINQ would be to use group by:

int[] types = new int[] { 0, 2, 3 };

return accounts
  .Where(x => x.MemberId == 20 && types.Contains(x.AccType))
  .GroupBy(x => x.AccNum)
  .Where(x => x.Count() == types.Count())
  .SelectMany(x => x)
  .Where(x => x.AccType == 3);


问:
PLSQL :NEW and :OLD
Can anyone help me understand when to use :NEW and :OLD in PLSQL blocks, I'm finding it very difficult to understand their usage.

答: :OLD and :NEW are variables of type Record and is identical in columns to the table row on which the trigger is fired. They are only available for row level triggers. Since triggers are fired on a predefined event automatically so :OLD and :NEW also get their value automatically . As the name suggests , :OLD will have the complete row values existing in table ( i.e has the existing values in case of update and delete ) and :NEW will have new values for that rows ( i.e. has the row value in case of update and insert ).</p>

Title: PLSQL :NEW and :OLD


问:
How do I split the screen into two areas, while having a form in the center?
I've been trying to achieve the below design for a couple of hours now but can't figure out the best way to approach this problem with Jetpack Compose, and I can't find a solid doc describing Compose's layout approach/guidelines.

I tried a bunch of things including the following nesting, but no luck:

```<code>Container
 Row - green background, align Top
 Row - white background, align Buttom
 Container (Form) - align Center
</code>```

How can I achieve this design?

Thanks!

答:
I think Stack Layout will help you. Like this

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MainContainer()
        }
    }
}

@Preview
@Composable
fun MainContainer() {
    Stack {

        Align(Alignment.TopCenter) {
            Column(arrangement = Arrangement.Center) {
                Container(
                    background(Color.Green),
                    alignment = Alignment.TopCenter,
                    //height = 350.dp,
                    width = 450.dp,
                    expanded = true
                ) {
                    Text("Up")
                }
            }
        }

        Align(alignment = Alignment.BottomCenter) {
            Column(background(Color.Yellow), arrangement = Arrangement.Center) {
                Container(alignment = Alignment.Center, height = 350.dp, width = 450.dp) {
                    Text("Down")
                }
            }
        }

        Align(Alignment.Center) {
            Column(background(Color.White), arrangement = Arrangement.Center) {
                Container(alignment = Alignment.Center, height = 250.dp, width = 250.dp) {
                    Clip(shape = RoundedCornerShape(8.dp)) {
                        LoginContainer()
                    }
                }
            }
        }
    }
}

@Composable
fun LoginContainer() {
    Column {
        Text("Username")
        Text("Password")
        Button("Login")
    }
}
</code>```

Body:
I've been trying to achieve the below design for a couple of hours now but can't figure out the best way to approach this problem with Jetpack Compose, and I can't find a solid doc describing Compose's layout approach/guidelines.

I tried a bunch of things including the following nesting, but no luck:

Container
 Row - green background, align Top
 Row - white background, align Buttom
 Container (Form) - align Center

How can I achieve this design?

Thanks!

Body:
I think Stack Layout will help you. Like this

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MainContainer()
        }
    }
}

@Preview
@Composable
fun MainContainer() {
    Stack {

        Align(Alignment.TopCenter) {
            Column(arrangement = Arrangement.Center) {
                Container(
                    background(Color.Green),
                    alignment = Alignment.TopCenter,
                    //height = 350.dp,
                    width = 450.dp,
                    expanded = true
                ) {
                    Text("Up")
                }
            }
        }

        Align(alignment = Alignment.BottomCenter) {
            Column(background(Color.Yellow), arrangement = Arrangement.Center) {
                Container(alignment = Alignment.Center, height = 350.dp, width = 450.dp) {
                    Text("Down")
                }
            }
        }

        Align(Alignment.Center) {
            Column(background(Color.White), arrangement = Arrangement.Center) {
                Container(alignment = Alignment.Center, height = 250.dp, width = 250.dp) {
                    Clip(shape = RoundedCornerShape(8.dp)) {
                        LoginContainer()
                    }
                }
            }
        }
    }
}

@Composable
fun LoginContainer() {
    Column {
        Text("Username")
        Text("Password")
        Button("Login")
    }
}


问:
How to get name of variable
I have simple question.
How to get name of variable time from this example:

```<code>let x = {
  color: string = red;
}

let y = getVarName(x.color);
console.log(y);
</code>```

Result: color

How i can get this result above? getVarName is example function which i want to make.

答:
The right question is How to get obj property's name based on it's value. Object contain no variable, only properties.

First use Obj.keys() to get the array of keys from the obj, then use find to get the key that match the obj property value you passed in :

```<code> getPropName = (value) => x.keys().find(key => x[key] === value)
</code>```

Title: How to get name of variable

Body:
I have simple question.
How to get name of variable time from this example:

let x = {
  color: string = red;
}

let y = getVarName(x.color);
console.log(y);

Result: color

How i can get this result above? getVarName is example function which i want to make.

Body:
The right question is How to get obj property's name based on it's value. Object contain no variable, only properties.

First use Obj.keys() to get the array of keys from the obj, then use find to get the key that match the obj property value you passed in :

 getPropName = (value) => x.keys().find(key => x[key] === value)


问:
What does map.put return?
I tried to get the return type of put method of the map interface. When I print for the first time it is printing null and after updating the key I get the previous value.
So, can anyone tell me what is the return type of the put method in the map interface?</p>

```<code>Map<Integer, String> map = new HashMap<Integer, String>();
System.out.println(map.put(1, "ABC"));
System.out.println(map.put(1, "XYZ"));

Output:
null
ABC
</code>```

答: According to documentation, it's a generic function that returns the same datatype as the map value. So, in your case it should return String.

Title: What does map.put return?

Body:
I tried to get the return type of put method of the map interface. When I print for the first time it is printing null and after updating the key I get the previous value.
So, can anyone tell me what is the return type of the put method in the map interface?

Map<Integer, String> map = new HashMap<Integer, String>();
System.out.println(map.put(1, "ABC"));
System.out.println(map.put(1, "XYZ"));

Output:
null
ABC


问:
How To Properly Update A Widget In Android 8.0 - Oreo - API 26
Let's say I have a widget for an app that has targetSDKVersion set to 26. This widget takes between 100ms and 10s to update. Most of the time under 1s. Before Android O, if onUpdate() was called on my AppWidgetProvider, I could launch a background service to update this widget. However, Android O returns an IllegalStateException if you attempt that behavior. The obvious solution of starting a foreground service seems like an extreme measure for something that will be done in under 10s 99% of the time.

Possible solutions

Start a foreground service to update the widget. Annoy the user with a notification that will be gone in 10s.

Use JobScheduler to schedule a job as quickly as possible. Your widget may or may not get updated for a while.

Attempt to do the work in a broadcast receiver. Lock up the UI thread for any other apps. Yuck.

Attempt to do work in the widget receiver. Lock up the UI thread for any other apps. Yuck.

Abuse GCM to get a background service running. A lot of work and feels hacky.

I don't personally like any of the above solutions. Hopefully I'm missing something.

(Even more frustrating is that my app is already loaded into memory by the system calling onUpdate(). I don't see how loading my app into memory to call onUpdate(), but then not giving my app 1s to update the widget off the UI thread is saving anyone any battery life.)

答:
You can use WorkManager to update a widget. Uses WorkManager on devices with API 14+. You need to override fun onReceive(context: Context?, intent: Intent?) like this:

```<code>val ACTION_AUTO_UPDATE : String = "AUTO_UPDATE";

override fun onReceive(context: Context?, intent: Intent?) {
    super.onReceive(context, intent)
    if(intent?.action.equals(ACTION_AUTO_UPDATE))
    {
        val appWidgetManager = AppWidgetManager.getInstance(context)
        val thisAppWidgetComponentName = ComponentName(context!!.getPackageName(), javaClass.name)
        val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidgetComponentName)
        for (appWidgetId in appWidgetIds) {
            // update widget
        }
    }
}
</code>```

And you should create PeriodicWorkRequest. You have to use for repeating work. Periodic work has a minimum interval of 15 minutes. We enqueue the periodicWork when widget is enabled:

```<code>override fun onEnabled(context: Context) {
    val periodicWorkRequest = PeriodicWorkRequest.Builder(YourWorker::class.java, 15, TimeUnit.MINUTES).build()
    WorkManager.getInstance(context).enqueueUniquePeriodicWork("YourWorker", ExistingPeriodicWorkPolicy.REPLACE,periodicWorkRequest)
}
</code>```

And cancel it when widget is disabled:

```<code>override fun onDisabled(context: Context) {
    WorkManager.getInstance(context).cancelAllWork()
}
</code>```

Finally we create worker class:

```<code>class YourWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
var context : Context? = null

init {
    context = ctx
}

override fun doWork(): Result {
    val alarmIntent = Intent(context, YourWidget::class.java)
    alarmIntent.action = YourWidget().ACTION_AUTO_UPDATE
    context?.sendBroadcast(alarmIntent)
    return Result.success()
}
</code>```

If you want to use WorkerManager you add to build.gradle implementation 'androidx.work:work-runtime:2.3.1'

You can find the sample here.

ContentLicense: CC BY-SA 3.0

Body:
You can use WorkManager to update a widget. Uses WorkManager on devices with API 14+. You need to override fun onReceive(context: Context?, intent: Intent?) like this:

val ACTION_AUTO_UPDATE : String = "AUTO_UPDATE";

override fun onReceive(context: Context?, intent: Intent?) {
    super.onReceive(context, intent)
    if(intent?.action.equals(ACTION_AUTO_UPDATE))
    {
        val appWidgetManager = AppWidgetManager.getInstance(context)
        val thisAppWidgetComponentName = ComponentName(context!!.getPackageName(), javaClass.name)
        val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidgetComponentName)
        for (appWidgetId in appWidgetIds) {
            // update widget
        }
    }
}

And you should create PeriodicWorkRequest. You have to use for repeating work. Periodic work has a minimum interval of 15 minutes. We enqueue the periodicWork when widget is enabled:

override fun onEnabled(context: Context) {
    val periodicWorkRequest = PeriodicWorkRequest.Builder(YourWorker::class.java, 15, TimeUnit.MINUTES).build()
    WorkManager.getInstance(context).enqueueUniquePeriodicWork("YourWorker", ExistingPeriodicWorkPolicy.REPLACE,periodicWorkRequest)
}

And cancel it when widget is disabled:

override fun onDisabled(context: Context) {
    WorkManager.getInstance(context).cancelAllWork()
}

Finally we create worker class:

class YourWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
var context : Context? = null

init {
    context = ctx
}

override fun doWork(): Result {
    val alarmIntent = Intent(context, YourWidget::class.java)
    alarmIntent.action = YourWidget().ACTION_AUTO_UPDATE
    context?.sendBroadcast(alarmIntent)
    return Result.success()
}

If you want to use WorkerManager you add to build.gradle implementation 'androidx.work:work-runtime:2.3.1'

You can find the sample here.


问:
How i can run command by run schedule and by button also?
I have created commands in kernel.php which is running twiceDaily(). I also want to attach it with button so I can run this command by clicking on that button. When I click on on button it should run at that moment.

Currently, I have just created twiceDaily command I need better way to implement button idea.

kernel.php

```<code>protected function schedule(Schedule $schedule)
{
    $schedule->job(new \App\Jobs\ResendAttachment)->twiceDaily(1, 13);
}
</code>```

I want to run command by cron job on server and by button also.

答:
Add a route, for example:

```<code>Route::get('/resentattachment', 'YourController@resentattachment')->name('resent.attachment');
</code>```

Call command from your controller

```<code>class YourController extends Controller
{
    public function resentattachment()
    {
        Artisan::call('yourcommand');
        echo 'Sent successfully';
        //add other stuff like a success view
    }
}
</code>```

Call this route on your button click.

Body:
I have created commands in kernel.php which is running twiceDaily(). I also want to attach it with button so I can run this command by clicking on that button. When I click on on button it should run at that moment.

Currently, I have just created twiceDaily command I need better way to implement button idea.

kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->job(new \App\Jobs\ResendAttachment)->twiceDaily(1, 13);
}

I want to run command by cron job on server and by button also.

Body:
Add a route, for example:

Route::get('/resentattachment', 'YourController@resentattachment')->name('resent.attachment');

Call command from your controller

class YourController extends Controller
{
    public function resentattachment()
    {
        Artisan::call('yourcommand');
        echo 'Sent successfully';
        //add other stuff like a success view
    }
}

Call this route on your button click.


问:
What is FLOPS in field of deep learning?
What is FLOPS in field of deep learning? Why we don't use the term just FLO?

We use the term FLOPS to measure the number of operations of a frozen deep learning network.

Following Wikipedia, FLOPS = floating point operations per second. When we test computing units, we should consider of the time. But in case of measuring deep learning network, how can I understand this concept of time? Shouldn't we use the term just FLO(floating point operations)?

Why do people use the term FLOPS? If there is anything I don't know, what is it?

==== attachment ===

Frozen deep learning networks that I mentioned is just a kind of software. It's not about hardware. In the field of deep learning, people use the term FLOPS to measure how many operations are needed to run the network model. In this case, in my opinion, we should use the term FLO. I thought people confused about the term FLOPS and I want to know if others think the same or if I'm wrong.

Please look at these cases:

how to calculate a net's FLOPs in CNN

https://iq.opengenus.org/floating-point-operations-per-second-flops-of-machine-learning-models/

答:
I not sure my answer is 100% correct. but this is what i understand.

FLOPS = Floating point operations per second

FLOPs = Floating point operations

FLOPS is a unit of speed. FLOPs is a unit of amount.


问:
How to check two month are equal or not from date format YYYY-MM-DD?
I have two dates like 2020-12-31 and 2020-12-01 in string format yyyy-mm-dd while check the month it should return true.

Suppose I compare 2020-11-31 and 2020-12-31 it should return false.

If there is a difference in only month and year, it should return true.

For example today Feb 18, 2020, Suppose I choose Feb 11, 2020, it should return true, If I choose Jan 11, 2020, then it should return false.

Date difference should not be considered

答:
Shorted, faster, and simpler solution is:

"2020-11-31".substr(5, 2) === "2020-12-31".substr(5, 2)
```


问:
Copy one column from one table to another in same database with respect to id phpmyadmin
I have 2 tables;event and payment

I want to copy data from column amount of table Payment TO column paid of table Event where Event.eid=Paymenet.event_id

Kindly help if any one knows this.

答:
do update</p>

```<code>UPDATE  event a
   JOIN payment b ON a.eid = b.event_id
   SET a.paid = b.payment
</code>```

Body:
do update

UPDATE  event a
   JOIN payment b ON a.eid = b.event_id
   SET a.paid = b.payment


问:
What to do when a private key of an organization in Hyperledger fabric gets compromised?
Hello I have a Hyperledger Network blockchain network running with 5 organization. If one of the private key of the organization gets compromised what are the steps or methods available to revoke the private key. Are there any mechanisms in Fabric where we can generate  new set of key pair for the same organization .</p>

答: You can generate the new certificate and private key pair from the Certificate authority and pass it to the configuration. In the meantime, you can add previous the certificate in the Certificate revocation list.</p>


问:
How do I properly nest this If statement
I'm capturing user input but restricting them between 1-100. I'm having some difficulty nesting this if statement correctly.
Goal:
user can input any amount between 1-100
if not, it sets automatically to 0.
I print the results at the end</p>

```<code>    // if statement to restrict use to 1-100
    hatNumber = in.readInt("How many beaver hats would you like?: \n");
    if (hatNumber <= 0 && hatNumber > 100) {
        System.out.println("Hats = " + hatNumber);
    } else {
        hatNumber = 0;
    }
    photoNumber = in.readInt("How many photographs would you like?: \n");
    if (photoNumber <= 0 && photoNumber > 100) {
        System.out.println("Photographs = " + photoNumber);
    } else {
        photoNumber = 0;

        jarNumber = in.readInt("How many Jars of maple syrup?: \n");

    if (jarNumber <= 0 && jarNumber > 100) {
            System.out.println("Jars = " + jarNumber);

        } else {
            jarNumber = 0;
            {

                System.out.println("Hats = " + hatNumber);
                System.out.println("Photographs = " + photoNumber);
                System.out.println("Jars = " + jarNumber);
</code>```

答:
First of all, If you are expecting a logic "User can input any amount between 1-100 if not, it sets automatically to 0 ". You should change if else check to

```<code>if (hatNumber > 0 && hatNumber <= 100) {
        System.out.println("Hats = " + hatNumber);
} else {
        hatNumber = 0;
}
</code>```

Final code will look like.

```<code>    hatNumber = in.readInt("How many beaver hats would you like?: \n");
    if (hatNumber > 0 && hatNumber <= 100) {
        System.out.println("Hats = " + hatNumber);
    } else {
        hatNumber = 0;
    }
    photoNumber = in.readInt("How many photographs would you like?: \n");
    if (photoNumber > 0 && photoNumber <= 100) {
        System.out.println("Photographs = " + photoNumber);
    } else {
        photoNumber = 0;
        jarNumber = in.readInt("How many Jars of maple syrup?: \n");
        if (jarNumber > 0 && jarNumber <= 100) {
            System.out.println("Jars = " + jarNumber);
        } else {
            jarNumber = 0;
        }
    }
    System.out.println("Hats = " + hatNumber);
    System.out.println("Photographs = " + photoNumber);
    System.out.println("Jars = " + jarNumber);
</code>```

Body:
I'm capturing user input but restricting them between 1-100. I'm having some difficulty nesting this if statement correctly.
Goal:
user can input any amount between 1-100
if not, it sets automatically to 0.
I print the results at the end

    // if statement to restrict use to 1-100
    hatNumber = in.readInt("How many beaver hats would you like?: \n");
    if (hatNumber <= 0 && hatNumber > 100) {
        System.out.println("Hats = " + hatNumber);
    } else {
        hatNumber = 0;
    }
    photoNumber = in.readInt("How many photographs would you like?: \n");
    if (photoNumber <= 0 && photoNumber > 100) {
        System.out.println("Photographs = " + photoNumber);
    } else {
        photoNumber = 0;

        jarNumber = in.readInt("How many Jars of maple syrup?: \n");

    if (jarNumber <= 0 && jarNumber > 100) {
            System.out.println("Jars = " + jarNumber);

        } else {
            jarNumber = 0;
            {

                System.out.println("Hats = " + hatNumber);
                System.out.println("Photographs = " + photoNumber);
                System.out.println("Jars = " + jarNumber);

Body:
First of all, If you are expecting a logic "User can input any amount between 1-100 if not, it sets automatically to 0 ". You should change if else check to

if (hatNumber > 0 && hatNumber <= 100) {
        System.out.println("Hats = " + hatNumber);
} else {
        hatNumber = 0;
}

Final code will look like.

    hatNumber = in.readInt("How many beaver hats would you like?: \n");
    if (hatNumber > 0 && hatNumber <= 100) {
        System.out.println("Hats = " + hatNumber);
    } else {
        hatNumber = 0;
    }
    photoNumber = in.readInt("How many photographs would you like?: \n");
    if (photoNumber > 0 && photoNumber <= 100) {
        System.out.println("Photographs = " + photoNumber);
    } else {
        photoNumber = 0;
        jarNumber = in.readInt("How many Jars of maple syrup?: \n");
        if (jarNumber > 0 && jarNumber <= 100) {
            System.out.println("Jars = " + jarNumber);
        } else {
            jarNumber = 0;
        }
    }
    System.out.println("Hats = " + hatNumber);
    System.out.println("Photographs = " + photoNumber);
    System.out.println("Jars = " + jarNumber);


问:
Ant Extract Classes Into Jar

Possible Duplicate:

  Clean way to combine multiple jars? Preferably using Ant

When I export a jar file from eclipse one of the options I get is to extract the class files from dependency jars into my final jar (other options include to just pack the jars into the my final jar or just leave everything outside of my final jar). There is of course a warning about licensing issues.

So here's the question -- what is the equivilant of this in apache ant? How can I make ant extract classes from jars that my program depends on and repack them into my final jar?

答:
Try something like this:

```<code><?xml version="1.0"?>
<project name="blah" basedir="." default="jar">
<target name="init">
  <property name="build" value="./build" />
  <property name="srcdir" value="./src" />
  <property name="lib.dir" value="./lib" />
  <property name="dist" value="./dist" />
  <property name="docs" value="./docs" />
  <property name="debug" value="true" />
  <path id="project.class.path">
    <pathelement path="${java.class.path}" />
    <fileset dir="${lib.dir}">
      <include name="*.jar" />
    </fileset>
  </path>
</target>
 <target name="compile" depends="init">
   <mkdir dir="${build}" />
   <javac debug="${debug}"
          optimize="${optimize}"
          destdir="${build}"
          deprecation="${deprecation}"
          source="1.6" target="1.6">
     <src path="${srcdir}" />
     <classpath refid="project.class.path" />
   </javac>
 </target>
 <target name="jar" depends="compile">
   <mkdir dir="${dist}" />
   <jar destfile="${dist}/${ant.project.name}.jar">
     <fileset dir="${build}">
       <include name="com/blah/blah/*.class" />
     </fileset>
   </jar>
 </target>
<target name="package" depends="compile, jar">
  <jar destfile="${dist}/${ant.project.name}-release.jar" basedir="${build}" includes="**/*.*">
    <manifest>
       <attribute name="Main-Class" value="com.blah.blah.Main" />
    </manifest>
    <zipgroupfileset dir="${lib.dir}" includes="*.jar" />
    <zipgroupfileset dir="${dist}" includes="${ant.project.name}.jar" />
  </jar>
</target>
</project>
</code>```

You would then go:

ant package

To generate a single jar file with all the classes in the lib folder.

Title: Ant Extract Classes Into Jar

Body:
Try something like this:

<?xml version="1.0"?>
<project name="blah" basedir="." default="jar">
<target name="init">
  <property name="build" value="./build" />
  <property name="srcdir" value="./src" />
  <property name="lib.dir" value="./lib" />
  <property name="dist" value="./dist" />
  <property name="docs" value="./docs" />
  <property name="debug" value="true" />
  <path id="project.class.path">
    <pathelement path="${java.class.path}" />
    <fileset dir="${lib.dir}">
      <include name="*.jar" />
    </fileset>
  </path>
</target>
 <target name="compile" depends="init">
   <mkdir dir="${build}" />
   <javac debug="${debug}"
          optimize="${optimize}"
          destdir="${build}"
          deprecation="${deprecation}"
          source="1.6" target="1.6">
     <src path="${srcdir}" />
     <classpath refid="project.class.path" />
   </javac>
 </target>
 <target name="jar" depends="compile">
   <mkdir dir="${dist}" />
   <jar destfile="${dist}/${ant.project.name}.jar">
     <fileset dir="${build}">
       <include name="com/blah/blah/*.class" />
     </fileset>
   </jar>
 </target>
<target name="package" depends="compile, jar">
  <jar destfile="${dist}/${ant.project.name}-release.jar" basedir="${build}" includes="**/*.*">
    <manifest>
       <attribute name="Main-Class" value="com.blah.blah.Main" />
    </manifest>
    <zipgroupfileset dir="${lib.dir}" includes="*.jar" />
    <zipgroupfileset dir="${dist}" includes="${ant.project.name}.jar" />
  </jar>
</target>
</project>

You would then go:

ant package

To generate a single jar file with all the classes in the lib folder.


问:
Vue - How to access Elements from B-table
I am using a "b-table" with ":fields" and ":items", I already know how to customize specific fields with "v-slot:cell(keyname)".
But know I want to get the value of each element in this column and display it differently depending on its value. Is there a way to do this?

My table looks like this

```<code>        <b-table
                striped hover
                responsive
                :fields="shotlist_tab.fields"
                :items="shotlist_tab.shots">

            <template v-slot:cell(frame)>
                <!-- ACCESS ELEMENT -->
                <div v-if="???">
                    <font-awesome-icon class="icon" :icon="['fas', 'image']"/>
                </div>
                <div v-else>
                    <img src="../../assets/logo.png" height="50" width="50" alt="frame"/>
                </div>
</code>```

I have already create a standard table with v-for="(object, index) in objects" where I can access each data with object.element
I want to replicate this with the b-table.

答:
The slots are scoped, meaning you are passed the cells value, along with additional information (i.e. the entire row data, the field definition for the cell, etc).

<template v-slot:cell(frame)="scope">

</template>
```

Refer to the docs for custom data rendering at: https://bootstrap-vue.js.org/docs/components/table#custom-data-rendering

Body:
I am using a "b-table" with ":fields" and ":items", I already know how to customize specific fields with "v-slot:cell(keyname)".
But know I want to get the value of each element in this column and display it differently depending on its value. Is there a way to do this?

My table looks like this

            <template v-slot:cell(frame)>

I have already create a standard table with v-for="(object, index) in objects" where I can access each data with object.element
I want to replicate this with the b-table.

Body:
The slots are scoped, meaning you are passed the cells value, along with additional information (i.e. the entire row data, the field definition for the cell, etc).

<template v-slot:cell(frame)="scope">
  <!-- You may need to adjust the condition/check for your situation -->
  <div v-if="scope.value === null">
    <font-awesome-icon class="icon" :icon="['fas', 'image']"/>
  </div>
  <div v-else>
    <img src="../../assets/logo.png" height="50" width="50" alt="frame"/>
  </div>
</template>

Refer to the docs for custom data rendering at: https://bootstrap-vue.js.org/docs/components/table#custom-data-rendering


问:
Can you use the width of a div to calcuate the Left property?
I am trying to set the left to be half of the width but I am unsure how to do that.

I figured you could use Calc() but I don't know how I would get the width property (set dynamically with slick.js)

```<code>.qpStar {
    position: relative;
    left: ???;
    top: 2px;
}
</code>```

I am trying to get a span to align on the left of the div using the left property.  It starts at the center of the div

答:
Try This ....

```<code> .qpStar {
        position: relative;
        left: 50%;
        top: 2px;
    }
</code>```

Another Way...

```<code>.qpStar {
        position: relative;
        transform: translateX(50%);
        top: 2px;
    }
</code>```

Body:
I am trying to set the left to be half of the width but I am unsure how to do that.

I figured you could use Calc() but I don't know how I would get the width property (set dynamically with slick.js)

.qpStar {
    position: relative;
    left: ???;
    top: 2px;
}

I am trying to get a span to align on the left of the div using the left property.  It starts at the center of the div

Body:
Try This ....

 .qpStar {
        position: relative;
        left: 50%;
        top: 2px;
    }

Another Way...

.qpStar {
        position: relative;
        transform: translateX(50%);
        top: 2px;
    }


问:
Rust best practices when specifying a constant hash map
I'm trying to set a constant, predefined hash map in Rust.  I'm not sure what the best practice is in Rust for this.

```<code>use std::collections::HashMap;

pub const Countries: HashMap<&str, &str> = [
    ("UK", "United Kingdom"),
    ("US", "United States")
].iter().cloned().collect();
</code>```

These will then be referenced later in the library.

If this is bad, I'm guessing a match in a function is the best way?

答:
You can use https://crates.io/crates/lazy_static (lazily executed at runtime).

I personally use https://crates.io/crates/phf (compile-time static collections) for this if the data is truly static.

```<code>use phf::{phf_map};

static COUNTRIES: phf::Map<&'static str, &'static str> = phf_map! {
    "US" => "United States",
    "UK" => "United Kingdom",
};
</code>```

Body:
I'm trying to set a constant, predefined hash map in Rust.  I'm not sure what the best practice is in Rust for this.

use std::collections::HashMap;

pub const Countries: HashMap<&str, &str> = [
    ("UK", "United Kingdom"),
    ("US", "United States")
].iter().cloned().collect();

These will then be referenced later in the library.

If this is bad, I'm guessing a match in a function is the best way?

Body:
You can use https://crates.io/crates/lazy_static (lazily executed at runtime).

I personally use https://crates.io/crates/phf (compile-time static collections) for this if the data is truly static.

use phf::{phf_map};

static COUNTRIES: phf::Map<&'static str, &'static str> = phf_map! {
    "US" => "United States",
    "UK" => "United Kingdom",
};


问:
How can I reduce my Kafka topic into a ktable of most recent state
I have some dummy data of manufacturers in a topic keyed by entity id:

```<code>{"ROWTIME": 1581884260481, "ROWKEY": "key1", "name": "nissan", "id": "key1", "founded": 1910}
{"ROWTIME": 1581884260481, "ROWKEY": "key2", "name": "toyota", "id": "key2", "founded": 0}
{"ROWTIME": 1581894249560, "ROWKEY": "key2", "name": "toyota", "id": "key2", "founded": 1920}
</code>```

1) I'd like to end up with a ktable containing the reduced state of the manufacturers:

```<code>{"name": "nissan", "id": "key1", "founded": 1910},
{"name": "toyota", "id": "key2", "founded": 1920}
</code>```

Q: What is the query syntax in ksql to produce that reduced state?

All of the docs were written prior to the pull/push query changes so I am not sure how I am supposed to build this.  Do I want a materialized view (which requires aggregates), or a ktable over a topic?  Do I need a CTaS?

1b) I've been thinking about this and it would probably be best if the topic stored just changes and not the whole record.  In that scenario I can just write events that will ultimately reduce into part of the state, instead of having to query the current record or trust the UI to pass back in the whole thing.

2) When I query this table I'd like two things to happen:

Give me the list of reduced state (the 2 records above)

If any updates happen (insert or update to the reduced list) send them over as they happen

Q: What query can I create to give both current and future values in a ktable?

emit changes seems to only go forward from that point in time.  Do I need two queries, or is there a way to do it in one?

Thanks for helping me fill in these gaps, it's appreciated.

答:
"rowtime" and "rowkey" are default fields added by "Ksql_server", which are useful columns during stream/table join (Windowing and partition).

1a) You can skip the columns at consumer level.  1b) didn;t able to
understand :(

The link will be helpful
(https://www.confluent.io/blog/kafka-streams-tables-part-1-event-streaming/)

You don;t need to make any change because if you have created a
KTable, new record will append only, which you can check with select
query.

Hope it will help.

Body:
I have some dummy data of manufacturers in a topic keyed by entity id:

{"ROWTIME": 1581884260481, "ROWKEY": "key1", "name": "nissan", "id": "key1", "founded": 1910}
{"ROWTIME": 1581884260481, "ROWKEY": "key2", "name": "toyota", "id": "key2", "founded": 0}
{"ROWTIME": 1581894249560, "ROWKEY": "key2", "name": "toyota", "id": "key2", "founded": 1920}

1) I'd like to end up with a ktable containing the reduced state of the manufacturers:

{"name": "nissan", "id": "key1", "founded": 1910},
{"name": "toyota", "id": "key2", "founded": 1920}

Q: What is the query syntax in ksql to produce that reduced state?

All of the docs were written prior to the pull/push query changes so I am not sure how I am supposed to build this.  Do I want a materialized view (which requires aggregates), or a ktable over a topic?  Do I need a CTaS?

1b) I've been thinking about this and it would probably be best if the topic stored just changes and not the whole record.  In that scenario I can just write events that will ultimately reduce into part of the state, instead of having to query the current record or trust the UI to pass back in the whole thing.

2) When I query this table I'd like two things to happen:

Give me the list of reduced state (the 2 records above)

If any updates happen (insert or update to the reduced list) send them over as they happen

Q: What query can I create to give both current and future values in a ktable?

emit changes seems to only go forward from that point in time.  Do I need two queries, or is there a way to do it in one?

Thanks for helping me fill in these gaps, it's appreciated.


问:
In-app updates not working. Unable to bind the service error
I am trying to setup the in-app updates dialog in Android but it's not working from the example provided in the docs

I have tried the examples available in the docs which ask you to do this.

```<code>appUpdateManager
    .getAppUpdateInfo()
    .addOnSuccessListener(
        new OnSuccessListener<AppUpdateInfo>() {
            @Override
            public void onSuccess(AppUpdateInfo appUpdateInfo) {
                if (appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
                    // If an in-app update is already running, resume the update.
                    try {
                        appUpdateManager.startUpdateFlowForResult(
                            appUpdateInfo,
                            IMMEDIATE,
                            MainActivity.this,
                            MY_REQUEST_CODE);
                    } catch (IntentSender.SendIntentException e) {
                        e.printStackTrace();
                    }
                }
            }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.e(TAG, "onFailure: onResume" + e.getMessage() );
        }
    });
</code>```

Expected a result that tells gives me some option where it tells me that an updates is actually available. But it directly gives me the error unable to bind to the service.

答: There seems to be an issue with Google Play Core library with Android Virtual Devices. please use the Real Device

Body:
I am trying to setup the in-app updates dialog in Android but it's not working from the example provided in the docs

I have tried the examples available in the docs which ask you to do this.

appUpdateManager
    .getAppUpdateInfo()
    .addOnSuccessListener(
        new OnSuccessListener<AppUpdateInfo>() {
            @Override
            public void onSuccess(AppUpdateInfo appUpdateInfo) {
                if (appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
                    // If an in-app update is already running, resume the update.
                    try {
                        appUpdateManager.startUpdateFlowForResult(
                            appUpdateInfo,
                            IMMEDIATE,
                            MainActivity.this,
                            MY_REQUEST_CODE);
                    } catch (IntentSender.SendIntentException e) {
                        e.printStackTrace();
                    }
                }
            }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.e(TAG, "onFailure: onResume" + e.getMessage() );
        }
    });

Expected a result that tells gives me some option where it tells me that an updates is actually available. But it directly gives me the error unable to bind to the service.


问:
difference between row and column normalization
i am working on data analysis and need to normalize the data. i have used following coomand for normalization
 z1<-data.Normalization(hfiltered,type = "n10",normalization = "row",na.rm=FALSE)

and z<-data.Normalization(hfiltered,type = "n1",normalization = "column",na.rm=FALSE).
But didn't understood that what is the difference between column normalization and row normalization.

答:
This is too ...long for a comment and hence providing it in answer,Not sure if it answers your problem but Let us break it in steps:

Normalizaton:

There a lot of ways one can normalize a data , one such way is min max normalization. (xi - min(x))/range(x), where x a feature and xi is the individual value for that feature. Normalization helps to keep everything between a scale of 0 to 1 (it can be different for different normalization). This helps in comparing features which is now on the same scale after normalization.

Column Normalization:

Well, column normalization deals with normalizing the features independently from each other. Column normalization is more prevalent and meaningful when we use PCA, kmeans or other algorithms, it sometimes also helps models to converge faster while used in deeplearning.

Row Normalization:

Now, row normalization is somewhat delicate and usually not that prevalent unless you have data like counts, in other words your features that are unit-less, although care must be taken in case you have different units for different features. Cases were features are having different units might not be suitable for row normalization. An example could be where let us say a data contains lot of samples where each sample represented in rows and let us assume that sample is distributed into further 5 features/groups, so in this case a row normalization will help to understand the feature/group proportion of a given sample.

Normalization within a column will hold the information intact but within a row sometimes it doesn't. For example in a given data, if a measure a customer age and Income as features,  Now if you normalize it on column the pattern where customer A is younger or older and/or more income or less income will hold after column normalization when compared with customer B, But this may not able to hold if you do a row normalization (which is kind of information loss).

This is well explained here


问:
fs with authentication on accessing shared directory
I am using fs in order to access images from another server, which is in the same local network (but it will soon be moved to different network so that later it will be connected via internet). The point is that to access the shared directory, I need to authenticate in the fs part. It asks for username and password when accessing manually but it does not ask anything when accessing by fs.accessSync(). It just gives me this error.

Error: UNKNOWN: unknown error, access {file path}

So, I am looking for a way to solve this problem. Be it give credentials upon accessing or any other ways.
I tried giving username and password when accessing manually and it will work for a while. After some time, the error will come back again because it needs authorization once more.

UPDATE1: for more information/clarification

It is Windows authentication. It requires username and password. I access it via a local network using file sharing system.

答: Right now, my workaround is to provide username and password manually once and make it always remember the credentials. The fs now works as expected without providing any credentials in the fs functions.</p>


问:
How to get rid of Incremental annotation processing requested warning?
I have just started using android development and trying to use Room library. Since yesterday I am facing this warning message

w: [kapt] Incremental annotation processing requested, but support is
  disabled because the following processors are not incremental:
  androidx.lifecycle.LifecycleProcessor (NON_INCREMENTAL),
  androidx.room.RoomProcessor (NON_INCREMENTAL).

I have tried to research and fix but unable to avoid this error here is my grale.build file. please suggest/advice what I am doing wrong.

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "ps.room.bookkeeper"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
            }
        }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // life cycle dependencies
    def lifecycle_version = "2.0.0"
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
    kapt "android.arch.lifecycle:compiler:$lifecycle_version"

    //Room dependencies
    //def room_version = "2.1.0"
    implementation 'android.arch.persistence.room:runtime:2.1.0'
    kapt 'android.arch.persistence.room:compiler:2.1.0'
    //annotationProcessor 'android.arch.persistence.room:compiler:2.1.0'

//    implementation "android.arch.lifecycle:extensions:$room_version"
//    kapt "android.arch.persistence.room:compiler:$room_version"
//    androidTestImplementation "android.arch.persistence.room:testing:$room_version"

    //implementation 'androidx.room:room-runtime:2.1.0'
    //annotationProcessor 'androidx.room:room-compiler:2.1.0'
}
</code>```

答:
Enable Kapt Incremental annotation processing requeste

Use Kotlin 1.3.31 or newer Kotlin 1.3.30 released

In your android kotlin project gradle.properties file

```<code># Enable Kapt Incremental annotation processing requeste
kapt.incremental.apt=true

# Enable android.databinding.annotationprocessor.ProcessDataBinding (DYNAMIC)
android.databinding.incremental=true

# Decrease gradle builds time
kapt.use.worker.api=true

# turn off AP discovery in compile path, and therefore turn on Compile Avoidance
kapt.include.compile.classpath=false

# Enable In Logcat to determine Kapt
kapt.verbose=true
</code>```

Body:
I have just started using android development and trying to use Room library. Since yesterday I am facing this warning message

w: [kapt] Incremental annotation processing requested, but support is
  disabled because the following processors are not incremental:
  androidx.lifecycle.LifecycleProcessor (NON_INCREMENTAL),
  androidx.room.RoomProcessor (NON_INCREMENTAL).

I have tried to research and fix but unable to avoid this error here is my grale.build file. please suggest/advice what I am doing wrong.

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "ps.room.bookkeeper"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
            }
        }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // life cycle dependencies
    def lifecycle_version = "2.0.0"
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
    kapt "android.arch.lifecycle:compiler:$lifecycle_version"

    //Room dependencies
    //def room_version = "2.1.0"
    implementation 'android.arch.persistence.room:runtime:2.1.0'
    kapt 'android.arch.persistence.room:compiler:2.1.0'
    //annotationProcessor 'android.arch.persistence.room:compiler:2.1.0'

//    implementation "android.arch.lifecycle:extensions:$room_version"
//    kapt "android.arch.persistence.room:compiler:$room_version"
//    androidTestImplementation "android.arch.persistence.room:testing:$room_version"

    //implementation 'androidx.room:room-runtime:2.1.0'
    //annotationProcessor 'androidx.room:room-compiler:2.1.0'
}

Body:
Enable Kapt Incremental annotation processing requeste

Use Kotlin 1.3.31 or newer Kotlin 1.3.30 released

In your android kotlin project gradle.properties file

# Enable Kapt Incremental annotation processing requeste
kapt.incremental.apt=true

# Enable android.databinding.annotationprocessor.ProcessDataBinding (DYNAMIC)
android.databinding.incremental=true

# Decrease gradle builds time
kapt.use.worker.api=true

# turn off AP discovery in compile path, and therefore turn on Compile Avoidance
kapt.include.compile.classpath=false

# Enable In Logcat to determine Kapt
kapt.verbose=true


问:
java.lang.NullPointerException on spring boot
i have created a simple java class in spring boot application. calling a method  ns.mesage(); from two different methods but one is executed and another one throw an null pointer exception.</p>

```<code>package TestPackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*
import TestPackage.MorningService;
import TestPackage.NightService;*/

@RestController
public class GenerateMessage {

    @Autowired
    public MorningService ms;

    @Autowired
    public NightService ns;

    @RequestMapping(path = "/test")
    public String starter(){
        GenerateMessage gm=new GenerateMessage();
        ns.mesage(); // this call working fine

        gm.mes();
        return "Mail scheduled.";
    }

public void mes(){
    try{
    System.out.println("starts2..............");
    ns.mesage(); // throwing an exception
    }catch(Exception e){
        e.printStackTrace();
    }
}
}
</code>```

答:
When you create an instance with keyword new, it doesn't go through the spring bean lifecycle. In a result post-processor, which response for processing @Autowired annotation doesn't work, and NightService not injected in new instance of GenerateMessage. You just create an instance of the class with null fields.

If you want to create real bean manually you should do it like this:

```<code>@RestController
public class GenerateMessage {

    @Autowired
    public MorningService ms;

    @Autowired
    public NightService ns;

    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping(path = "/test")
    public String starter(){
        GenerateMessage gm=applicationContext.getBean(GenerateMessage.class);
        ns.mesage(); // this call working fine

        gm.mes();
        return "Mail scheduled.";
    }

public void mes(){
    try{
    System.out.println("starts2..............");
    ns.mesage(); // throwing an exception
    }catch(Exception e){
        e.printStackTrace();
    }
}
}
</code>```

But I do not recommend you to work with the applicationcontext directly, cause it is a heavy object and may lead to decrease performance.

Body:
i have created a simple java class in spring boot application. calling a method  ns.mesage(); from two different methods but one is executed and another one throw an null pointer exception.

package TestPackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*
import TestPackage.MorningService;
import TestPackage.NightService;*/

@RestController
public class GenerateMessage {

    @Autowired
    public MorningService ms;

    @Autowired
    public NightService ns;

    @RequestMapping(path = "/test")
    public String starter(){
        GenerateMessage gm=new GenerateMessage();
        ns.mesage(); // this call working fine

        gm.mes();
        return "Mail scheduled.";
    }

public void mes(){
    try{
    System.out.println("starts2..............");
    ns.mesage(); // throwing an exception
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

Body:
When you create an instance with keyword new, it doesn't go through the spring bean lifecycle. In a result post-processor, which response for processing @Autowired annotation doesn't work, and NightService not injected in new instance of GenerateMessage. You just create an instance of the class with null fields.

If you want to create real bean manually you should do it like this:

@RestController
public class GenerateMessage {

    @Autowired
    public MorningService ms;

    @Autowired
    public NightService ns;

    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping(path = "/test")
    public String starter(){
        GenerateMessage gm=applicationContext.getBean(GenerateMessage.class);
        ns.mesage(); // this call working fine

        gm.mes();
        return "Mail scheduled.";
    }

public void mes(){
    try{
    System.out.println("starts2..............");
    ns.mesage(); // throwing an exception
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

But I do not recommend you to work with the applicationcontext directly, cause it is a heavy object and may lead to decrease performance.


问:
PowerBI_variables_error message "cannot convert value of type Text to type TRUE/FALSE"
In PowerBI I have a table like this:

I created a measure to calculate the total head count for selected groups and selected age:

```<code>head count_total =
VAR
  Category = FILTER(ALL('table'[group]), 'table'[group] = "apple" || "pear")
VAR
  includeage = FILTER(ALL('table'[age]), table[age]>=20)
RETURN
  CALCULATE(SUM('table'[head count]), Category, includeage)
</code>```

I get this error message:

Cannot convert value “pear” of type Text to type TRUE/FALSE

Can anyone help diagnose where went wrong in the coding? Many thanks!

答:
The expression 'table'[group] = "apple" || "pear" is not correct. It compares table value with "apple", and the boolean result from this operation is "or"-ed with "pear". In this context "pear" should be a boolean value, while it is a text. Thus the error message. The correct expression in this case is 'table'[group] = "apple" || 'table'[group] = "pear" or 'table'[group] in { "apple" , "pear" }, so the measure should be (adding quotes around one table reference):

```<code>head count_total =
VAR
  Category = FILTER(ALL('table'[group]), 'table'[group] = "apple" || 'table'[group] = "pear")
VAR
  includeage = FILTER(ALL('table'[age]), 'table'[age]>=20)
RETURN
  CALCULATE(SUM('table'[head count]), Category, includeage)
</code>```

Body:
In PowerBI I have a table like this:

I created a measure to calculate the total head count for selected groups and selected age:

head count_total =
VAR
  Category = FILTER(ALL('table'[group]), 'table'[group] = "apple" || "pear")
VAR
  includeage = FILTER(ALL('table'[age]), table[age]>=20)
RETURN
  CALCULATE(SUM('table'[head count]), Category, includeage)

I get this error message:

Cannot convert value “pear” of type Text to type TRUE/FALSE

Can anyone help diagnose where went wrong in the coding? Many thanks!

Body:
The expression 'table'[group] = "apple" || "pear" is not correct. It compares table value with "apple", and the boolean result from this operation is "or"-ed with "pear". In this context "pear" should be a boolean value, while it is a text. Thus the error message. The correct expression in this case is 'table'[group] = "apple" || 'table'[group] = "pear" or 'table'[group] in { "apple" , "pear" }, so the measure should be (adding quotes around one table reference):

head count_total =
VAR
  Category = FILTER(ALL('table'[group]), 'table'[group] = "apple" || 'table'[group] = "pear")
VAR
  includeage = FILTER(ALL('table'[age]), 'table'[age]>=20)
RETURN
  CALCULATE(SUM('table'[head count]), Category, includeage)


问:
How to return a class instance with an expression macro?
Driver code

```<code>//---------------- Main.hx ------------------------------------------------------------------
import core.reflection.ReflectionTools;
import core.SomeClass;
class Main{
   public static function main(){
      var s = new SomeClass();
      ReflectionTools.info(s);
   }
}
</code>```

The macro

```<code>//---------------- ReflectionTools.hx -----------------------------------------------------
class RelectionTools {
    public static macro function info(obj:Expr):Expr{
        var pos = Context.currentPos();
        var block = [];
        var result:Dynamic;
        var type:Type=Context.typeof(obj);
        result=(switch(type){
            case TInst(t, params):new RelectionClass(t, params);
            case TEnum(t, params):new ReflectionEnum(t, params);
            case TDynamic(t):new ReflectionDynamic(t);
            case TFun(args, ret):new ReflectionFunction(args, ret);
            case TMono(t):new ReflectionMonomorph(t);
            case TLazy(f):new ReflectionLazy(f);
            case TAbstract(t, params):new ReflectionAbstract(t, params);
            case TType(t, params):new ReflectionTypeDefinition(t, params);
            case TAnonymous(a):new ReflectionAnonymousStructure(a);
        });
        return $v{result};
    }
}
</code>```

Haxe Compiler:

Expected Expr but got core.reflection.RelectionClass (see dump/decoding_error.txt for details)

答:
Macro is a compile time feature, not runtime feature, you can't return class instance. Instead, you have to return expression which creates a new instance (I don't have your classes, so I use here my class)</p>

```<code>var type=Context.typeof(obj);
return (switch(type){
    case TInst(t, params):macro new MyClass();//RelectionClass(t, params);
    case TEnum(t, params):macro new MyClass();//ReflectionEnum(t, params);
    case TDynamic(t):macro new MyClass();//ReflectionDynamic(t);
    case TFun(args, ret):macro new MyClass();//ReflectionFunction(args, ret);
    case TMono(t):macro new MyClass();//ReflectionMonomorph(t);
    case TLazy(f):macro new MyClass();//ReflectionLazy(f);
    case TAbstract(t, params):macro new MyClass();//ReflectionAbstract(t, params);
    case TType(t, params):macro new MyClass();//ReflectionTypeDefinition(t, params);
    case TAnonymous(a):macro new MyClass();//ReflectionAnonymousStructure(a);
});
return macro null;
</code>```

Body:
Driver code

//---------------- Main.hx ------------------------------------------------------------------
import core.reflection.ReflectionTools;
import core.SomeClass;
class Main{
   public static function main(){
      var s = new SomeClass();
      ReflectionTools.info(s);
   }
}

The macro

//---------------- ReflectionTools.hx -----------------------------------------------------
class RelectionTools {
    public static macro function info(obj:Expr):Expr{
        var pos = Context.currentPos();
        var block = [];
        var result:Dynamic;
        var type:Type=Context.typeof(obj);
        result=(switch(type){
            case TInst(t, params):new RelectionClass(t, params);
            case TEnum(t, params):new ReflectionEnum(t, params);
            case TDynamic(t):new ReflectionDynamic(t);
            case TFun(args, ret):new ReflectionFunction(args, ret);
            case TMono(t):new ReflectionMonomorph(t);
            case TLazy(f):new ReflectionLazy(f);
            case TAbstract(t, params):new ReflectionAbstract(t, params);
            case TType(t, params):new ReflectionTypeDefinition(t, params);
            case TAnonymous(a):new ReflectionAnonymousStructure(a);
        });
        return $v{result};
    }
}

Haxe Compiler:

Expected Expr but got core.reflection.RelectionClass (see dump/decoding_error.txt for details)

Body:
Macro is a compile time feature, not runtime feature, you can't return class instance. Instead, you have to return expression which creates a new instance (I don't have your classes, so I use here my class)

var type=Context.typeof(obj);
return (switch(type){
    case TInst(t, params):macro new MyClass();//RelectionClass(t, params);
    case TEnum(t, params):macro new MyClass();//ReflectionEnum(t, params);
    case TDynamic(t):macro new MyClass();//ReflectionDynamic(t);
    case TFun(args, ret):macro new MyClass();//ReflectionFunction(args, ret);
    case TMono(t):macro new MyClass();//ReflectionMonomorph(t);
    case TLazy(f):macro new MyClass();//ReflectionLazy(f);
    case TAbstract(t, params):macro new MyClass();//ReflectionAbstract(t, params);
    case TType(t, params):macro new MyClass();//ReflectionTypeDefinition(t, params);
    case TAnonymous(a):macro new MyClass();//ReflectionAnonymousStructure(a);
});
return macro null;


问:
Access Website & Download files from a Server
I am trying to write a VBA macro to download files from our companies server. In order to download the files, I look for their number of our my excel list. E.G. the number is "250". Then I need to search for "250" on the website and then get the objectID of the file.
So the links of the download document looks like this :

```<code>https://plm.corp.int:10090/enovia/tvc-action/downloadMultipleFiles?objectId=***4706.39075.61185.44166***&object=250
</code>```

4706.39075.61185.44166 this number is what I need to find for every of my numbers from excel, in order to edit the download link and get the files.

in the image you can see how it looks in the source code of the website...
Now I have absolutely no idea how I can extract such data our of source code in VBA

答:
@Zwenn

enter image description here

the E2**** is the number out of excel, that i am searching for on the platform.
The 4706 number form my original question, is the unique ID of every E2***number.

Body:
I am trying to write a VBA macro to download files from our companies server. In order to download the files, I look for their number of our my excel list. E.G. the number is "250". Then I need to search for "250" on the website and then get the objectID of the file.
So the links of the download document looks like this :

https://plm.corp.int:10090/enovia/tvc-action/downloadMultipleFiles?objectId=***4706.39075.61185.44166***&object=250

4706.39075.61185.44166 this number is what I need to find for every of my numbers from excel, in order to edit the download link and get the files.

in the image you can see how it looks in the source code of the website...
Now I have absolutely no idea how I can extract such data our of source code in VBA


问:
Using debounceTime in angular
I want to use debounceTime for sending a request to the sever after 300 milisecond of pressing a key.

I use this code:

```<code>GetUsers(): void {
    let value = document.getElementById('search-box');
    this.cdRef.detectChanges();

    if (this.subscription) {
        this.subscription.unsubscribe();
    }

    value = this.searchValue.toString();

    const typeahead = fromEvent(value, 'input').pipe(
        map((e: KeyboardEvent) => (e.target as HTMLInputElement).value),
        filter(text => text.length > 2),
        debounceTime(10),
        distinctUntilChanged(),
        x => {
            if (value.startsWith('@')) {
                this.searchTitle = 'GENERAL.USER_NAME';
                const val = value.slice(1);
                if (val.length > 0) {

                    this.getWithUserName(val, this.page);

                }
            } else if (value.startsWith('+9')) {

                this.searchTitle = 'GENERAL.PHONE_NUMBER';
                this.GetWithPhoneNumber(this.searchValue, this.page);

            } else if (!value.startsWith('@') && !value.startsWith('+9')) {
                this.searchTitle = 'GENERAL.NAME';
                this.GetWithDisplayName(value, this.page);

            }
        }
    );
    this.cdRef.detectChanges();
}
</code>```

and this is code HttpClient for send request to server:

```<code>getWithUserName(value: string, page: number): void {
    this.loading = true;
    this.cdRef.detectChanges();
    this.subscription = this.userPublicService
        .getUserByUserName(value, page, this.appConfig.dropdownPageSize)
        .pipe(debounceTime(30000),
            distinctUntilChanged())
        .subscribe(data => {
            this.users = data['records'];
            this.totalCount = data['totalCount'];
            this.cdRef.detectChanges();
            this.loading = false;
            this.ValidateshowBtn();
        });
    if (this.userId > 0) {
        this.selectedUserById(this.userId);
    }
}
</code>```

But this code does not work for me.

What's the problem? How can I solve this problem?

it show me this error :

ERROR in src/app/shared/components/user-mutli-select-search/user-mutli-select-search.component.ts(117,4): error TS2345: Argument of type '(x: Observable) => void' is not assignable to parameter of type 'OperatorFunction'.
        Type 'void' is not assignable to type 'Observable<{}>'.

答: The function that starts with x => { should be inside tap() or in the subscribe().

Title: Using debounceTime in angular

Body:
I want to use debounceTime for sending a request to the sever after 300 milisecond of pressing a key.

I use this code:

GetUsers(): void {
    let value = document.getElementById('search-box');
    this.cdRef.detectChanges();

    if (this.subscription) {
        this.subscription.unsubscribe();
    }

    value = this.searchValue.toString();

    const typeahead = fromEvent(value, 'input').pipe(
        map((e: KeyboardEvent) => (e.target as HTMLInputElement).value),
        filter(text => text.length > 2),
        debounceTime(10),
        distinctUntilChanged(),
        x => {
            if (value.startsWith('@')) {
                this.searchTitle = 'GENERAL.USER_NAME';
                const val = value.slice(1);
                if (val.length > 0) {

                    this.getWithUserName(val, this.page);

                }
            } else if (value.startsWith('+9')) {

                this.searchTitle = 'GENERAL.PHONE_NUMBER';
                this.GetWithPhoneNumber(this.searchValue, this.page);

            } else if (!value.startsWith('@') && !value.startsWith('+9')) {
                this.searchTitle = 'GENERAL.NAME';
                this.GetWithDisplayName(value, this.page);

            }
        }
    );
    this.cdRef.detectChanges();
}

and this is code HttpClient for send request to server:

getWithUserName(value: string, page: number): void {
    this.loading = true;
    this.cdRef.detectChanges();
    this.subscription = this.userPublicService
        .getUserByUserName(value, page, this.appConfig.dropdownPageSize)
        .pipe(debounceTime(30000),
            distinctUntilChanged())
        .subscribe(data => {
            this.users = data['records'];
            this.totalCount = data['totalCount'];
            this.cdRef.detectChanges();
            this.loading = false;
            this.ValidateshowBtn();
        });
    if (this.userId > 0) {
        this.selectedUserById(this.userId);
    }
}

But this code does not work for me.

What's the problem? How can I solve this problem?

it show me this error :

ERROR in src/app/shared/components/user-mutli-select-search/user-mutli-select-search.component.ts(117,4): error TS2345: Argument of type '(x: Observable) => void' is not assignable to parameter of type 'OperatorFunction'.
        Type 'void' is not assignable to type 'Observable<{}>'.


问:
Can't use External JS in angular 8
I'm trying to integrate a html template in my angular project and everything is going fine except my JS plugins are not loading. I've given the path to the files in the index.html page. The styles are working fine.

index.html

```<code><html lang="en">
<head>
  <meta charset="utf-8">
  <title>Estate</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <!-- Google Font -->
  <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900&display=swap" rel="stylesheet">
  <!-- Css Styles -->
    <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/font-awesome.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/elegant-icons.css" type="text/css">
    <link rel="stylesheet" href="assets/css/themify-icons.css" type="text/css">
    <link rel="stylesheet" href="assets/css/nice-select.css" type="text/css">
    <link rel="stylesheet" href="assets/css/jquery-ui.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/owl.carousel.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/magnific-popup.css" type="text/css">
    <link rel="stylesheet" href="assets/css/slicknav.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/style.css" type="text/css">
</head>
<body>
  <app-root></app-root>

  <script src="assets/js/jquery-3.3.1.min.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>
  <script src="assets/js/jquery.magnific-popup.min.js"></script>
  <script src="assets/js/jquery.nice-select.min.js"></script>
  <script src="assets/js/jquery.slicknav.js"></script>
  <script src="assets/js/jquery-ui.min.js"></script>
  <script src="assets/js/owl.carousel.min.js"></script>
  <script src="assets/js/main.js"></script>

</body>
</html>
</code>```

答:
You can import your external JS files in Angular by mentioning them in angular.json file.

Inside angular.json you have to mention your files in scripts array. Make sure you are giving absolute path for the files that are present in the assets.

```<code>"scripts": [
              "../../../assets/jquery/dist/jquery.magnific-popup.min.js",
              "../../../assets/jquery/dist/jquery.min.js"
            ]
</code>```

Title: Can't use External JS in angular 8

Body:
I'm trying to integrate a html template in my angular project and everything is going fine except my JS plugins are not loading. I've given the path to the files in the index.html page. The styles are working fine.

index.html

  <meta charset="utf-8">
  <title>Estate</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/font-awesome.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/elegant-icons.css" type="text/css">
    <link rel="stylesheet" href="assets/css/themify-icons.css" type="text/css">
    <link rel="stylesheet" href="assets/css/nice-select.css" type="text/css">
    <link rel="stylesheet" href="assets/css/jquery-ui.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/owl.carousel.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/magnific-popup.css" type="text/css">
    <link rel="stylesheet" href="assets/css/slicknav.min.css" type="text/css">
    <link rel="stylesheet" href="assets/css/style.css" type="text/css">

  <app-root></app-root>

Body:
You can import your external JS files in Angular by mentioning them in angular.json file.

Inside angular.json you have to mention your files in scripts array. Make sure you are giving absolute path for the files that are present in the assets.

"scripts": [
              "../../../assets/jquery/dist/jquery.magnific-popup.min.js",
              "../../../assets/jquery/dist/jquery.min.js"
            ]