问:
Difference between two groups, data processing
I have this dataprocessing problem where I want to count the difference in goals between two teams in different matches. The data looks like this:

```<code>    matchId teamId   eventSec
1   2799331   6718  443.55984
2   2799331   6726 1152.62584
3   2799331   6718 2113.82370
4   2799331   6718 2066.28793
5   2799332   6710 1001.35775
6   2799332   6721 2469.32876
7   2799333   6734  744.35563
</code>```

So one of these lines represents a goal scored by a team, and matchId represents the match, teamId the teams in the match and eventSec the time of the goal. What i want to accomplish is a variable for each row that shows the difference in score, so the first row in this example data should have a goal difference of 1, row two should have goal difference by 0, row three a goal difference by 1, etc.

I want to apply this to a big dataset with alot of different match and teamIds, so I need a pretty general solution to solve this. I've tried different dplyr solutions but gotten stuck a million times and would really like some help.

Thanks alot in advance!

Body:
I have this dataprocessing problem where I want to count the difference in goals between two teams in different matches. The data looks like this:

    matchId teamId   eventSec
1   2799331   6718  443.55984
2   2799331   6726 1152.62584
3   2799331   6718 2113.82370
4   2799331   6718 2066.28793
5   2799332   6710 1001.35775
6   2799332   6721 2469.32876
7   2799333   6734  744.35563

So one of these lines represents a goal scored by a team, and matchId represents the match, teamId the teams in the match and eventSec the time of the goal. What i want to accomplish is a variable for each row that shows the difference in score, so the first row in this example data should have a goal difference of 1, row two should have goal difference by 0, row three a goal difference by 1, etc.

I want to apply this to a big dataset with alot of different match and teamIds, so I need a pretty general solution to solve this. I've tried different dplyr solutions but gotten stuck a million times and would really like some help.

Thanks alot in advance!

Body:
We can also do this with indexing

library(dplyr)
df1 %>%
  group_by(matchId) %>%
  mutate(goal_diff =cumsum(c(-1, 1)[(teamId == first(teamId)) + 1 ]))
# A tibble: 7 x 4
# Groups:   matchId [3]
#  matchId teamId eventSec goal_diff
#    <int>  <int>    <dbl>     <dbl>
#1 2799331   6718     444.         1
#2 2799331   6726    1153.         0
#3 2799331   6718    2114.         1
#4 2799331   6718    2066.         2
#5 2799332   6710    1001.         1
#6 2799332   6721    2469.         0
#7 2799333   6734     744.         1

data

df1 <- structure(list(matchId = c(2799331L, 2799331L, 2799331L, 2799331L,
2799332L, 2799332L, 2799333L), teamId = c(6718L, 6726L, 6718L,
6718L, 6710L, 6721L, 6734L), eventSec = c(443.55984, 1152.62584,
2113.8237, 2066.28793, 1001.35775, 2469.32876, 744.35563)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7"))


来源: stackexchange

问:
Calculated Column to DAX
i have a calculated column using this code:

```<code>SalesMember_Cal_Column =
VAR ContextID = Table1[Id]
RETURN
    CONCATENATEX (
        CALCULATETABLE (
            DISTINCT ( Table1[salesmember] ),
            FILTER ( Table1, Table1[Id] = Id )
        ),
        Table1[salesmember],
        ","
    )
</code>```

This works fine, but I would like to use it as a measure.

What can I change to use this as a measure?

Example:

I have data that looks like this:

```<code>Company CompnayID   SalesMember Role
Walmart   1            Ryan     Lead
Walmart   1           Vinnie    Lead2
Walmart   1             Danny   Lead3
Winco     2            Ryan     Lead
Winco     2           Vinnie    Lead2
Winco     2           Danny     Lead3
Fred Myer 3           Noelle    Lead
Kroger    4             Dennis  Lead
Albertsons 5            Nate    Lead
Safeway    6           Carol    Lead
</code>```

I want to create a measure called SalesMember_Cal_Column that will give me this result:

```<code>Company CompnayID   SalesMember Role    SalesMember_Cal_Column
Walmart   1           Ryan      Lead    Ryan, Vinnie, Danny
Walmart   1           Vinnie    Lead2   Ryan, Vinnie, Danny
Walmart   1           Danny     Lead3   Ryan, Vinnie, Danny
Winco     2           Ryan      Lead    Ryan, Vinnie, Danny
Winco     2           Vinnie    Lead2   Ryan, Vinnie, Danny
Winco     2           Danny     Lead3   Ryan, Vinnie, Danny
Fred Myers 3          Noelle    Lead    Noelle
Kroger     4          Dennis    Lead    Dennis
Albertsons 5           Nate     Lead    Nate
Safeway    6          Carol     Lead    Carol
</code>```

I want to make sure when I slice to a company then slice on sales member that only the associated sales member shows up in the new column.

For example, if I were to slice the above table to Walmart and sales member Ryan the result would look like this:

```<code>Company CompnayID   SalesMember Role    SalesMember_Cal_Column
Walmart     1          Ryan     Lead       Ryan
</code>```

答:
I think you should be able to simply replace

```<code>VAR ContextID = Table1[Id]
</code>```

with something like

```<code>VAR ContextID = SELECTEDVALUE ( Table1[Id] )
</code>```

This will return the Id value from the filter context (or return blank if there are multiple).

ContentLicense: CC BY-SA 4.0

Title: Calculated Column to DAX

Body:
i have a calculated column using this code:

SalesMember_Cal_Column =
VAR ContextID = Table1[Id]
RETURN
    CONCATENATEX (
        CALCULATETABLE (
            DISTINCT ( Table1[salesmember] ),
            FILTER ( Table1, Table1[Id] = Id )
        ),
        Table1[salesmember],
        ","
    )

This works fine, but I would like to use it as a measure.

What can I change to use this as a measure?

Example:

I have data that looks like this:

Company CompnayID   SalesMember Role
Walmart   1            Ryan     Lead
Walmart   1           Vinnie    Lead2
Walmart   1             Danny   Lead3
Winco     2            Ryan     Lead
Winco     2           Vinnie    Lead2
Winco     2           Danny     Lead3
Fred Myer 3           Noelle    Lead
Kroger    4             Dennis  Lead
Albertsons 5            Nate    Lead
Safeway    6           Carol    Lead

I want to create a measure called SalesMember_Cal_Column that will give me this result:

Company CompnayID   SalesMember Role    SalesMember_Cal_Column
Walmart   1           Ryan      Lead    Ryan, Vinnie, Danny
Walmart   1           Vinnie    Lead2   Ryan, Vinnie, Danny
Walmart   1           Danny     Lead3   Ryan, Vinnie, Danny
Winco     2           Ryan      Lead    Ryan, Vinnie, Danny
Winco     2           Vinnie    Lead2   Ryan, Vinnie, Danny
Winco     2           Danny     Lead3   Ryan, Vinnie, Danny
Fred Myers 3          Noelle    Lead    Noelle
Kroger     4          Dennis    Lead    Dennis
Albertsons 5           Nate     Lead    Nate
Safeway    6          Carol     Lead    Carol

I want to make sure when I slice to a company then slice on sales member that only the associated sales member shows up in the new column.

For example, if I were to slice the above table to Walmart and sales member Ryan the result would look like this:

Company CompnayID   SalesMember Role    SalesMember_Cal_Column
Walmart     1          Ryan     Lead       Ryan

Body:
I think you should be able to simply replace

VAR ContextID = Table1[Id]

with something like

VAR ContextID = SELECTEDVALUE ( Table1[Id] )

This will return the Id value from the filter context (or return blank if there are multiple).


问:
I'm trying to find a way to identify deleted user accounts from my system based on their email address without violating gdpr / privacy
My business recruits people for focus groups and one of our main selling points is that we ensure that recruits don't see the same researcher more than once.

Often we will be given customer lists from our clients where a condition of the job is that we delete the user records at the end of the project. Whilst we are able to keep the associated data that ties them to a project (for business stats etc.) we need to remove identifying & contact information -> Email address and phone numbers being how we identify a specific persons account.

My issue is:
What can i do to ensure that, if these deleted users show up in my system again, that I can identify their association with old projects / focus groups, so that we can prevent these deleted users from signing up again and being placed in a focus group with a researcher they have already seen.

My first thought was, upon "deletion", to hash their email address and remove the plaintext address, and check this hashed address against new accounts, to link their old db associations with this new account.

I am fairly new to security / privacy concepts, so I'm not sure whether this would be secure, or if being able to identify the link to the old account is a violation of privacy.

答:
You're on the right track here. Hashing the email address or phone number means that you've effectively put that data "beyond use". So long as you delete all the other data relating to it, it does not represent "personal data" in the GDPR sense.

Also consider the basis for processing – if you are legally obliged (either by statute or by the original contract with your users) to implement this suppression mechanism, then you would be permitted to do so even if it was personal data.

Note this email marketing industry body that recommends and promotes hash-based suppression lists, and this site suggesting the same.


问:
Performance issues using sql_variant to store data
I have a Key/Value table I'm using to store data that can be either text or numeric, but nothing else.

In preliminary testing, I am seeing horrendous performance when applying citeria to the sql_variant column, for example:

```<code>SELECT * FROM MY_DATA WHERE
MY_ENTITY_TYPE = 555
AND CAST(MY_SQL_VARIANT_COLUMN AS NUMERIC) = 2254
</code>```

So obviously there is going to be SOME hit with queries like this, but I am seeing queries well over 10 seconds, with only a few thousand rows in the table.

Considering I am only going to be storing numeric or text data, would it be more reasonable to use a varchar(255) column?  This way, select performance should be fast, and I would just have to do a post select CAST to get the data into the proper data type.

答:
Here are two methods to solve this performance issue:

CAST the criteria value rather than the column:
SELECT * FROM MY_DATA WHERE

MY_ENTITY_TYPE = 555
AND MY_SQL_VARIANT_COLUMN = CAST(2254 AS NUMERIC)

Add an index to a different column in the table and see if it magically fixes the problem.  For example, add an index to MY_ENTITY_TYPE, and despite not criteria being applied to this column, it cleared up the performance problem in my example.

Obviously, #1 is the better of the two.

ContentLicense: CC BY-SA 3.0

Body:
I have a Key/Value table I'm using to store data that can be either text or numeric, but nothing else.

In preliminary testing, I am seeing horrendous performance when applying citeria to the sql_variant column, for example:

SELECT * FROM MY_DATA WHERE
MY_ENTITY_TYPE = 555
AND CAST(MY_SQL_VARIANT_COLUMN AS NUMERIC) = 2254

So obviously there is going to be SOME hit with queries like this, but I am seeing queries well over 10 seconds, with only a few thousand rows in the table.

Considering I am only going to be storing numeric or text data, would it be more reasonable to use a varchar(255) column?  This way, select performance should be fast, and I would just have to do a post select CAST to get the data into the proper data type.


问:
Kotlin - Array of object (no null)
I'm coding in kotlin, and i have a problem with the Arrays

I would make a function that return an Array of Car (for example), but that array is build by data from file

Exemple :

```<code>fun buildAllCar(data:string) : Array<Car> {
    val array = arrayOfNulls<Location>(5) //In the real code, the size is retrieved by an other item

    for(i in array.indices){
        array[i] = buildACarByData(data); //Just so you could see a sample usage
    }

    return array.requireNoNulls()
}
</code>```

Without the requireNoNulls() , the type of object returned is Array of Car?
Use this method is the only way to get an Array of Car or there is a other way?

Thanks for your help

答:
Change the code and modify return type of Array because when you apply return type, Kotlin check the nullablity so "?" define with safe call and return list if if the array list objects are null.</p>

```<code>fun buildAllCar(data:string) : Array<Car?> {
    val array = arrayOfNulls<Location>(5) //In the real code, the size is retrieved by an other item

    for(i in array.indices){
        array[i] = buildACarByData(data); //Just so you could see a sample usage
    }

    return array
}
</code>```

Title: Kotlin - Array of object (no null)

Body:
I'm coding in kotlin, and i have a problem with the Arrays

I would make a function that return an Array of Car (for example), but that array is build by data from file

Exemple :

fun buildAllCar(data:string) : Array<Car> {
    val array = arrayOfNulls<Location>(5) //In the real code, the size is retrieved by an other item

    for(i in array.indices){
        array[i] = buildACarByData(data); //Just so you could see a sample usage
    }

    return array.requireNoNulls()
}

Without the requireNoNulls() , the type of object returned is Array of Car?
Use this method is the only way to get an Array of Car or there is a other way?

Thanks for your help

Body:
Change the code and modify return type of Array because when you apply return type, Kotlin check the nullablity so "?" define with safe call and return list if if the array list objects are null.

fun buildAllCar(data:string) : Array<Car?> {
    val array = arrayOfNulls<Location>(5) //In the real code, the size is retrieved by an other item

    for(i in array.indices){
        array[i] = buildACarByData(data); //Just so you could see a sample usage
    }

    return array
}


问:
How to install scp and ssh to Powershell?
I installed Posh-SSH with: Install-Module -Name Posh-SSH

When trying to execute scp or ssh, I am getting something like below. Why?

```<code>scp : The term 'scp' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ scp
+ ~~~
    + CategoryInfo          : ObjectNotFound: (scp:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

UPDATE
With the help of @tommymaynard, I can see all the available commands:

```<code>PS C:\WINDOWS\system32> $x = Find-Module -Name Posh-SSH
PS C:\WINDOWS\system32> $x.AdditionalMetadata.Functions -split ' '
Get-PoshSSHModVersion
Get-SFTPChildItem
Get-SFTPContent
Get-SFTPLocation
Get-SFTPPathAttribute
Get-SFTPSession
Get-SSHPortForward
Get-SSHSession
Get-SSHTrustedHost
Invoke-SSHCommand
Invoke-SSHCommandStream
Invoke-SSHStreamExpectAction
Invoke-SSHStreamExpectSecureAction
Invoke-SSHStreamShellCommand
Move-SFTPItem
New-SFTPFileStream
New-SFTPItem
New-SFTPSymlink
New-SSHDynamicPortForward
New-SSHLocalPortForward
New-SSHRemotePortForward
New-SSHShellStream
New-SSHTrustedHost
Remove-SFTPItem
Remove-SFTPSession
Remove-SSHSession
Remove-SSHTrustedHost
Rename-SFTPFile
Set-SFTPContent
Set-SFTPLocation
Set-SFTPPathAttribute
Start-SSHPortForward
Stop-SSHPortForward
Test-SFTPPath
PS C:\WINDOWS\system32> $x.AdditionalMetadata.Cmdlets -split ' '
Get-SCPFile
Get-SCPFolder
Get-SCPItem
Get-SFTPFile
Get-SFTPItem
New-SFTPSession
New-SSHSession
Set-SCPFile
Set-SCPFolder
Set-SCPItem
Set-SFTPFile
Set-SFTPFolder
Set-SFTPItem
</code>```

From there, which command would you use to replace the 'scp' and 'ssh' below (ref: https://code.visualstudio.com/docs/remote/troubleshooting#_configuring-key-based-authentication)?

```<code>$REMOTEHOST="your-user-name-on-host@host-fqdn-or-ip-goes-here"

scp "$env:USERPROFILE\.ssh\id_rsa.pub" "${REMOTEHOST}:~/tmp.pub"
ssh "$REMOTEHOST" "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat ~/tmp.pub >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && rm -f ~/tmp.pub"
</code>```

答:
The module you installed doesn't included a function/cmdlet named "scp." I didn't install the module, but did run the following commands to determine the names of the functions and cmdlets in the module.

```<code>$x = Find-Module -Name Posh-SSH
$x.AdditionalMetadata.Functions -split ' '
$x.AdditionalMetadata.Cmdlets -split ' '
</code>```

Edit: Did you read the help for the *scp* commands? I did. One of those is bound to do what you need. I went ahead an installed the module on my computer and ran the following to quickly obtain the synopsis for the *scp* commands in this module.

```<code>Install-Module -Name Posh-SSH
Get-Command -Module Posh-SSH -Name *scp* |
ForEach-Object {"$($_.Name): $((Get-Help -Name $_).Synopsis)"}

Get-SCPFile: Download a File from a SSH Server using SCP
Get-SCPFolder: Download a folder from a SSH Server using SCP.
Get-SCPItem: Download from a remote server via SCP a file or directory.
Set-SCPFile: Copies a file to a SSH server using SCP.
Set-SCPFolder: Copies a folder to a SSH server using SCP.
Set-SCPItem: Upload an item, either file or directory to a remote system via SCP.
</code>```

Body:
I installed Posh-SSH with: Install-Module -Name Posh-SSH

When trying to execute scp or ssh, I am getting something like below. Why?

scp : The term 'scp' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ scp
+ ~~~
    + CategoryInfo          : ObjectNotFound: (scp:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

UPDATE
With the help of @tommymaynard, I can see all the available commands:

PS C:\WINDOWS\system32> $x = Find-Module -Name Posh-SSH
PS C:\WINDOWS\system32> $x.AdditionalMetadata.Functions -split ' '
Get-PoshSSHModVersion
Get-SFTPChildItem
Get-SFTPContent
Get-SFTPLocation
Get-SFTPPathAttribute
Get-SFTPSession
Get-SSHPortForward
Get-SSHSession
Get-SSHTrustedHost
Invoke-SSHCommand
Invoke-SSHCommandStream
Invoke-SSHStreamExpectAction
Invoke-SSHStreamExpectSecureAction
Invoke-SSHStreamShellCommand
Move-SFTPItem
New-SFTPFileStream
New-SFTPItem
New-SFTPSymlink
New-SSHDynamicPortForward
New-SSHLocalPortForward
New-SSHRemotePortForward
New-SSHShellStream
New-SSHTrustedHost
Remove-SFTPItem
Remove-SFTPSession
Remove-SSHSession
Remove-SSHTrustedHost
Rename-SFTPFile
Set-SFTPContent
Set-SFTPLocation
Set-SFTPPathAttribute
Start-SSHPortForward
Stop-SSHPortForward
Test-SFTPPath
PS C:\WINDOWS\system32> $x.AdditionalMetadata.Cmdlets -split ' '
Get-SCPFile
Get-SCPFolder
Get-SCPItem
Get-SFTPFile
Get-SFTPItem
New-SFTPSession
New-SSHSession
Set-SCPFile
Set-SCPFolder
Set-SCPItem
Set-SFTPFile
Set-SFTPFolder
Set-SFTPItem

From there, which command would you use to replace the 'scp' and 'ssh' below (ref: https://code.visualstudio.com/docs/remote/troubleshooting#_configuring-key-based-authentication)?

$REMOTEHOST="your-user-name-on-host@host-fqdn-or-ip-goes-here"

scp "$env:USERPROFILE\.ssh\id_rsa.pub" "${REMOTEHOST}:~/tmp.pub"
ssh "$REMOTEHOST" "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat ~/tmp.pub >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && rm -f ~/tmp.pub"

Body:
The module you installed doesn't included a function/cmdlet named "scp." I didn't install the module, but did run the following commands to determine the names of the functions and cmdlets in the module.

$x = Find-Module -Name Posh-SSH
$x.AdditionalMetadata.Functions -split ' '
$x.AdditionalMetadata.Cmdlets -split ' '

Edit: Did you read the help for the *scp* commands? I did. One of those is bound to do what you need. I went ahead an installed the module on my computer and ran the following to quickly obtain the synopsis for the *scp* commands in this module.

Install-Module -Name Posh-SSH
Get-Command -Module Posh-SSH -Name *scp* |
ForEach-Object {"$($_.Name): $((Get-Help -Name $_).Synopsis)"}

Get-SCPFile: Download a File from a SSH Server using SCP
Get-SCPFolder: Download a folder from a SSH Server using SCP.
Get-SCPItem: Download from a remote server via SCP a file or directory.
Set-SCPFile: Copies a file to a SSH server using SCP.
Set-SCPFolder: Copies a folder to a SSH server using SCP.
Set-SCPItem: Upload an item, either file or directory to a remote system via SCP.


问:
Type 'Observable<any>' is not assignable to type 'Observable<any>' Ionic 4
I am currently working with Google API with Ionic 4, I am trying to implement a method that takes an address in entry and returns the latitude and longitude of this address(geocoding).
When thrying to implement that method, I had this issue:

Type 'Observable' is not assignable to type 'Observable':

The function code:

```<code>geocodeAddress(location: string): Observable<Location> {
  return this.waitForMapsToLoad().pipe(
  switchMap(() => {
    return new Observable(Location => {
      this.geocoder.geocode({address: location}, (results, status) => {
        if (status === google.maps.GeocoderStatus.OK) {
          observer.next({
            lat: results[0].geometry.location.lat(),
            lng: results[0].geometry.location.lng()
          });
        } else {
          console.log('Error - ', results, ' & Status - ', status);
          observer.next({ lat: 0, lng: 0 });
        }
        observer.complete();
      });
    });
  })
);
}`
</code>```

Location class:

```<code>export interface Location {
  lat: number;
  lng: number;
}
</code>```

Imports:

```<code>import { Injectable } from '@angular/core';
import { MapsAPILoader } from '@agm/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import { of } from 'rxjs/observable/of';
import { filter, catchError, tap, map, switchMap } from 'rxjs/operators';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Location } from './Position';
</code>```

Error generated:

```<code>TS2322: Type 'Observable<unknown>' is not assignable to type
'Observable<Location>'.
Type '{}' is missing the following properties from
type 'Location': lat, lng
</code>```

I saw people having this kind of problem but not the same one, could you please help me ?

答:
Most probably you are missing some type for some value, and the compiler cannot figure out the type of your observable.

Mention it explicitely using new Observable<Location>, which should point you further to another type mismatch error, or cast your observable using

```<code>return new Observable(Location => {
  this.geocoder.geocode({address: location}, (results, status) => {
    if (status === google.maps.GeocoderStatus.OK) {
      observer.next({
        lat: results[0].geometry.location.lat(),
        lng: results[0].geometry.location.lng()
      });
    } else {
      console.log('Error - ', results, ' & Status - ', status);
      observer.next({ lat: 0, lng: 0 });
    }
    observer.complete();
  });
}) as Observable<Location>;
</code>```

Using explicit typings, you can narrow down to the line posing problem, and apply your cast to this line only.

edit: By copy/pasting your code, I noticed you use Location as your lambda variable, I assume its an error you made while posting, and that it is correctly set to observer in your code.

Body:
I am currently working with Google API with Ionic 4, I am trying to implement a method that takes an address in entry and returns the latitude and longitude of this address(geocoding).
When thrying to implement that method, I had this issue:

Type 'Observable' is not assignable to type 'Observable':

The function code:

geocodeAddress(location: string): Observable<Location> {
  return this.waitForMapsToLoad().pipe(
  switchMap(() => {
    return new Observable(Location => {
      this.geocoder.geocode({address: location}, (results, status) => {
        if (status === google.maps.GeocoderStatus.OK) {
          observer.next({
            lat: results[0].geometry.location.lat(),
            lng: results[0].geometry.location.lng()
          });
        } else {
          console.log('Error - ', results, ' & Status - ', status);
          observer.next({ lat: 0, lng: 0 });
        }
        observer.complete();
      });
    });
  })
);
}`

Location class:

export interface Location {
  lat: number;
  lng: number;
}

Imports:

import { Injectable } from '@angular/core';
import { MapsAPILoader } from '@agm/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import { of } from 'rxjs/observable/of';
import { filter, catchError, tap, map, switchMap } from 'rxjs/operators';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Location } from './Position';

Error generated:

TS2322: Type 'Observable<unknown>' is not assignable to type
'Observable<Location>'.
Type '{}' is missing the following properties from
type 'Location': lat, lng

I saw people having this kind of problem but not the same one, could you please help me ?

Body:
Most probably you are missing some type for some value, and the compiler cannot figure out the type of your observable.

Mention it explicitely using new Observable<Location>, which should point you further to another type mismatch error, or cast your observable using

return new Observable(Location => {
  this.geocoder.geocode({address: location}, (results, status) => {
    if (status === google.maps.GeocoderStatus.OK) {
      observer.next({
        lat: results[0].geometry.location.lat(),
        lng: results[0].geometry.location.lng()
      });
    } else {
      console.log('Error - ', results, ' & Status - ', status);
      observer.next({ lat: 0, lng: 0 });
    }
    observer.complete();
  });
}) as Observable<Location>;

Using explicit typings, you can narrow down to the line posing problem, and apply your cast to this line only.

edit: By copy/pasting your code, I noticed you use Location as your lambda variable, I assume its an error you made while posting, and that it is correctly set to observer in your code.


问:
Reshaping a tensor with more than one uknown diemnsions
I need to be able to reshape a tensor only on its last axis:

```<code>(None, 4) --> (None, 2, 2),
</code>```

which at time of execution can have instances like these:

```<code>(128, 10, 4) --> (128, 10, 2, 2)
(128, 4) --> (128, 2, 2)
</code>```

Is there a straight forward solution or I need to iterate on the first axes (by excluding the last one), and considering the case that it can be None?

答:
You can do that like this:

my_tensor = ...
new_shape = tf.concat([tf.shape(my_tensor)[:-1], [2, 2]], axis=0)
my_tensor_reshaped = tf.reshape(my_tensor, new_shape)
```

Body:
I need to be able to reshape a tensor only on its last axis:

(None, 4) --> (None, 2, 2),

which at time of execution can have instances like these:

(128, 10, 4) --> (128, 10, 2, 2)
(128, 4) --> (128, 2, 2)

Is there a straight forward solution or I need to iterate on the first axes (by excluding the last one), and considering the case that it can be None?


问:
CoreData: annotation: Failed to load optimized model (React Native)
I can not start my react native application anymore. I updated XCode yesterday, maybe it has to do with it?</p>

```<code>$ react-native run-ios

Found Xcode workspace xyz.xcworkspace
CoreData: annotation:  Failed to load optimized model at path '/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/Frameworks/InstrumentsPackaging.framework/Versions/A/Resources
/XRPackageModel.momd/XRPackageModel 9.0.omo'
dyld: Symbol not found: _SimAudioHostUseSystemDefaultDeviceUID
Referenced from: /Applications/Xcode.app/Contents/Developer/usr/bin/../../Library/PrivateFrameworks/SimulatorKit.framework/Versions/A/SimulatorKit (which was built for Mac OS X 10.12)
Expected in: /Library/Developer/PrivateFrameworks/CoreSimulator.framework/Versions/A/CoreSimulator
in /Applications/Xcode.app/Contents/Developer/usr/bin/../../Library/PrivateFrameworks/SimulatorKit.framework/Versions/A/SimulatorKit
</code>```

答: Couldn't figure it out, but I realized that running from Xcode directly works.</p>

Body:
I can not start my react native application anymore. I updated XCode yesterday, maybe it has to do with it?

$ react-native run-ios

Found Xcode workspace xyz.xcworkspace
CoreData: annotation:  Failed to load optimized model at path '/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/Frameworks/InstrumentsPackaging.framework/Versions/A/Resources
/XRPackageModel.momd/XRPackageModel 9.0.omo'
dyld: Symbol not found: _SimAudioHostUseSystemDefaultDeviceUID
Referenced from: /Applications/Xcode.app/Contents/Developer/usr/bin/../../Library/PrivateFrameworks/SimulatorKit.framework/Versions/A/SimulatorKit (which was built for Mac OS X 10.12)
Expected in: /Library/Developer/PrivateFrameworks/CoreSimulator.framework/Versions/A/CoreSimulator
in /Applications/Xcode.app/Contents/Developer/usr/bin/../../Library/PrivateFrameworks/SimulatorKit.framework/Versions/A/SimulatorKit


问:
Merge strings of an array list based on certain elements HOW
I'd like to perform a function on a a list of data in at text file but I'm not sure how to go about it. My understanding of how to manipulate arrays and strings is weak, that is why I'm doing this project.

My text file looks like:

```<code>0, 0. 50 0.5 66;
1, 0. 69 2. 70;
2, 0.5 48 0.5 71;
3, 1. 47 1. 75;
4, 2. 52 1. 74;
5, 2. 71 1. 80;
6, 3. 65 1. 61;
7, 4. 62 1. 68;
</code>```

I'm looking for a result like this:

0, 0. 50 0.5 66 0. 69 2. 70;

1, 0.5 48 0.5 71;

2, 1. 47 1. 75;

3, 2. 52 1. 74 2. 71 1. 80;

4, 3. 65 1. 61;

5, 4. 62 1. 68;

The second elements of the first two entries is the same (0.)and I'd like to combine these entries onto the same line. The same for lines 4 and 5.

As I understand I must read my file into an array list, but I don't know how to query the array list to find all entries that have the same value for the second element, and then merge the entire entry with another entry.

I have no code to show because I don't know where to begin.

I appreciate any input.

答:
I wouldn't use a list, i would use a map.  A Map has a method

```<code>put(key, value)
</code>```

So, if you are interested in the second column of a given line, I would do something like (pseudocode)

```<code>Map<String, String> lookup = new HashMap<String, String>();

for (...) {  // loop over the lines in the file

    String key = getSecondFieldFromLine(line); // implement this
    String val = lookup.get(key);

    if (val != null ) {
        merge(val, line);  // implement this according to whatever merge means
    }

    lookup.put(key, val);
}
</code>```

You might have to tweak this (for example, store the result of the merge to put in the lookup), what you are doing here is leveraging the fact that for a Map, put and get operations are really fast (a HashMap uses the hashCode method that is on every object).  So you can easily determine if you already have a line with the field you are looking for, since you use the field of interest as the key, to look up the like that the field is in.

Body:
I'd like to perform a function on a a list of data in at text file but I'm not sure how to go about it. My understanding of how to manipulate arrays and strings is weak, that is why I'm doing this project.

My text file looks like:

0, 0. 50 0.5 66;
1, 0. 69 2. 70;
2, 0.5 48 0.5 71;
3, 1. 47 1. 75;
4, 2. 52 1. 74;
5, 2. 71 1. 80;
6, 3. 65 1. 61;
7, 4. 62 1. 68;

I'm looking for a result like this:

0, 0. 50 0.5 66 0. 69 2. 70;

1, 0.5 48 0.5 71;

2, 1. 47 1. 75;

3, 2. 52 1. 74 2. 71 1. 80;

4, 3. 65 1. 61;

5, 4. 62 1. 68;

The second elements of the first two entries is the same (0.)and I'd like to combine these entries onto the same line. The same for lines 4 and 5.

As I understand I must read my file into an array list, but I don't know how to query the array list to find all entries that have the same value for the second element, and then merge the entire entry with another entry.

I have no code to show because I don't know where to begin.

I appreciate any input.

Body:
I wouldn't use a list, i would use a map.  A Map has a method

put(key, value)

So, if you are interested in the second column of a given line, I would do something like (pseudocode)

Map<String, String> lookup = new HashMap<String, String>();

for (...) {  // loop over the lines in the file

    String key = getSecondFieldFromLine(line); // implement this
    String val = lookup.get(key);

    if (val != null ) {
        merge(val, line);  // implement this according to whatever merge means
    }

    lookup.put(key, val);
}

You might have to tweak this (for example, store the result of the merge to put in the lookup), what you are doing here is leveraging the fact that for a Map, put and get operations are really fast (a HashMap uses the hashCode method that is on every object).  So you can easily determine if you already have a line with the field you are looking for, since you use the field of interest as the key, to look up the like that the field is in.


问:
How to make "Touch to return to call" with Flutter?
I am using agora.io to create a calling app. It's possible to talk when the app starts, but once you close the app the call will end. With Facebook Messenger, Skype, and whatsAPPp, you can use other apps while keeping a call. What should I use to keep the app running in the background like this?

答: It's because,the ios terminates process of the app.you can call with app in background you have to change some settings</p>


问:
How can I update this state without mutating the array?
I want to know how to not mutate state in the following scenario:

I'm using React Hooks. I have a TodoList that lists TodoItems. TodoItems can be clicked to run a function called toggle which toggles their completed property.

```<code>import React, { useState } from "react";
import TodoItem from "./TodoItem";

export default function TodoList() {
  const [todos, setTodos] = useState([
    { text: "Example", completed: false }
  ]);

  const toggle = index => {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed; // Mutating state?
    setTodos(newTodos);
  };

  return (
    <>
      {todos.map((item, index) => (
        <TodoItem key={index} index={index} todo={item} toggle={toggle} />
      ))}
    </>
  );
}
</code>```

I was told that this was mutating state:

You create a copy of the todos array, but you still mutate an item inside the array:

newTodos[index].completed = !newTodos[index].completed;
```

  <p>Spreading the array only creates a shallow copy of the array, but the original todo object is not copied and thus mutated.</p>
</blockquote>

<p>So, what is the correct way to handle this without mutating state? I've tried passing in a <code>prevTodos</code> param, but then the state doesn't update:</p>

```const toggle = index => {
  setTodos(prevTodos => {
    prevTodos[index].completed = !prevTodos[index].completed;
    return prevTodos;
  });
};
```

<p><strong>Update:</strong> I've taken a look at the posts you've all recommended. This is a solution, although I'm wondering if there's a cleaner way to express it:</p>

```const toggle = index => {
  setTodos(
    todos.map((todo, i) =>
      i === index ? { ...todo, completed: !todo.completed } : todo
    )
  );
};
```

Update 2: Thanks everyone. I posted the solution below. StackOverflow won't let me accept it for 2 days, but I'll do it then. The accepted answer on the suggested post suggests the use of a third-party library, and it doesn't use React Hooks, so I don't consider this question a duplicate.

答:
That's right, the simplest way to avoid this problem is to avoid mutating data.

One way to do this is using a functional approach, specifically with a a non mutating array method like .map:

function TodoList() {
  const [todos, setTodos] = React.useState([{
    text: "Example",
    completed: true
  }]);

  const toggle = index => {
    const updatedTodos = todos.map((todo, i) => {
      if (i === index) {
        todo.completed = !todo.completed;
      }
      return todo;
    });
    setTodos(updatedTodos);
  };

  return (
    <React.Fragment >
      {todos.map((item, index) => (

 toggle(index)}
          className={item.completed ? "completed" : ""}
        >
          {item.text}

       ))}
    </React.Fragment>
  );
}

ReactDOM.render( < TodoList / > , document.getElementById('root'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.completed {
  text-decoration: line-through;
}</code>```

```

Body:
I want to know how to not mutate state in the following scenario:

I'm using React Hooks. I have a TodoList that lists TodoItems. TodoItems can be clicked to run a function called toggle which toggles their completed property.

import React, { useState } from "react";
import TodoItem from "./TodoItem";

export default function TodoList() {
  const [todos, setTodos] = useState([
    { text: "Example", completed: false }
  ]);

  const toggle = index => {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed; // Mutating state?
    setTodos(newTodos);
  };

  return (
    <>
      {todos.map((item, index) => (
        <TodoItem key={index} index={index} todo={item} toggle={toggle} />
      ))}
    </>
  );
}

I was told that this was mutating state:

You create a copy of the todos array, but you still mutate an item inside the array:

newTodos[index].completed = !newTodos[index].completed;

Spreading the array only creates a shallow copy of the array, but the original todo object is not copied and thus mutated.

So, what is the correct way to handle this without mutating state? I've tried passing in a prevTodos param, but then the state doesn't update:

const toggle = index => {
  setTodos(prevTodos => {
    prevTodos[index].completed = !prevTodos[index].completed;
    return prevTodos;
  });
};

Update: I've taken a look at the posts you've all recommended. This is a solution, although I'm wondering if there's a cleaner way to express it:

const toggle = index => {
  setTodos(
    todos.map((todo, i) =>
      i === index ? { ...todo, completed: !todo.completed } : todo
    )
  );
};

Update 2: Thanks everyone. I posted the solution below. StackOverflow won't let me accept it for 2 days, but I'll do it then. The accepted answer on the suggested post suggests the use of a third-party library, and it doesn't use React Hooks, so I don't consider this question a duplicate.

Body:
That's right, the simplest way to avoid this problem is to avoid mutating data.

One way to do this is using a functional approach, specifically with a a non mutating array method like .map:

function TodoList() {
  const [todos, setTodos] = React.useState([{
    text: "Example",
    completed: true
  }]);

  const toggle = index => {
    const updatedTodos = todos.map((todo, i) => {
      if (i === index) {
        todo.completed = !todo.completed;
      }
      return todo;
    });
    setTodos(updatedTodos);
  };

  return (
    <React.Fragment >
      {todos.map((item, index) => (
        <p
          key={item.text}
          onClick={() => toggle(index)}
          className={item.completed ? "completed" : ""}
        >
          {item.text}
        </p>
       ))}
    </React.Fragment>
  );
}

ReactDOM.render( < TodoList / > , document.getElementById('root'))

.completed {
  text-decoration: line-through;
}

<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root"></div>


问:
How to Pass data from PHP to PHP file
I have a File named 1.php and I have another file named index.php

I use

```<code>include('index.php');
</code>```

for including index data. Is there a way i can pass data to index.php file?

答:
if index.php is inside 1.php , you can do that:

1.php:

```<code><?php $variable = "hello";
      include('index.php');
?>
</code>```

index.php

```<code><?php
echo $variable; //this will output hello.
?>
</code>```

Title: How to Pass data from PHP to PHP file

Body:
I have a File named 1.php and I have another file named index.php

I use

include('index.php');

for including index data. Is there a way i can pass data to index.php file?

Body:
if index.php is inside 1.php , you can do that:

1.php:

<?php $variable = "hello";
      include('index.php');
?>

index.php

<?php
echo $variable; //this will output hello.
?>


问:
Visual Studio 2008 not loading symbols when debugging a .DMP
I'm trying to debug a C# application from a .DMP file and I have the executable, the DLLs and the PDBs all in a folder called "MyFolder." I set the directory containing the source code to C:\MyFolder\ but when I try to debug it tells me that:

"No symbols are loaded for any call stack frame. The source code cannot be displayed."

When I open the Symbol Load Information it states that the following PDBs could not be found:

C:\Windows\System32\kernel32.pdb: Cannot find or open the PDB file.

C:\MyFolder\kernel32.pdb: Cannot find or open the PDB file.

C:\MyFolder\symbols\dll\kernel32.pdb: Cannot find or open the PDB file.

C:\MyFolder\dll\kernel32.pdb: Cannot find or open the PDB file.

C:\MyFolder\kernel32.pdb: Cannot find or open the PDB file.

C:\Windows\symbols\dll\kernel32.pdb: Cannot find or open the PDB file.

C:\Windows\dll\kernel32.pdb: Cannot find or open the PDB file.

C:\Windows\kernel32.pdb: Cannot find or open the PDB file.

My PDBs are in the correct folder and they're timestamped with the exact same time and date. Does anybody know what's going on here? What's the proper way to load the symbols?

 How do I verify my application's symbols are actually loaded (to eliminate them as the problem)?
I checked the Modules and it looks like all of the DLLs and the executable of my project are unable to load the symbols, specifically the symbol status is "No native symbols in symbol file"... when I right click on the item and I select "Load Symbols From -> Symbol Path" and I select the PDB C:\MyFolder\MyApplication.pdb then it tells me that "The symbol file for MyApplication.pdb does not match the module."

答:
It sounds like the dump file is a native-code minidump, not a managed-code minidump, since the symbols for all those DLLs are usually not critical for managed debugging unless you debugging a mixed-mode app, debugging into Win32 calls or debugging across managed/unmanaged boundaries.

It depends on how the minidump was created.  If it was on a different machine on a different operating system or service pack, then you may need the symbol path set up to get the exact PDBs of the system DLLs from the other machine, not your application assmeblies and symbols.  Your managed debugging experience will improve if these unmanaged symbols are correct.
To further complicate things you have .NET "micro-versions" and native images to contend with to get the stack traces working.


问:
Excel 2010 CTRL+SHIFT+L. Not working
I apologize if asked/answered - but I truly did search....

In excel CTRL+Shift+L is not working;  when I press the key sequence and the cursor spins and comes back without having accomplished turning on the filters or anything visible to me.  This is the only shortcut that is not working so I did not know if I redefined it - but could not tell what it was currently defined as,  I had the IT guys repair the install - All with no luck...

I would love to debug what CTRL+Shift+L does when I hit it - but could not figure out if that was possible...

Totally at wits end - - any help would be greatly appreciated.

答: Another possibility... If you have two tabs selected at the bottom of the page it will not let you use that shortcut.  You will not even let you use the sort/filter button at the top of the toolbar. You will be able to tell if you have two tabs selected by looking at the bottom of the window at the tabs.  Click one of them or off of them to go back to only having one selected.</p>

Title: Excel 2010 CTRL+SHIFT+L. Not working


问:
Reversing a string operation
So I was fiddling with my encryption algorithms when this problem caught my attention:

Suppose you have a string operation given by the following pseudocode:

```<code>string go_wacky(string input, int reps)
{
    string result = input;
    foreach (0..reps)
    {
        result = insert_substring_at(result, input, random_from_to(0, length(result));
    }
    return result;
}
</code>```

Or, in point-and-click terminology, copy the string, then reps times do the following: move the cursor to a random position within the string and hit paste.

Given the output string and reps, how to extract the input string (other than "reverse brute force" based on reconstructing the character list of the original string using reps and output length)?

答:
just some random thoughts:

the input appears completely at least once in the output.

this problem may resolve to the "longest substring".

Title: Reversing a string operation

Body:
So I was fiddling with my encryption algorithms when this problem caught my attention:

Suppose you have a string operation given by the following pseudocode:

string go_wacky(string input, int reps)
{
    string result = input;
    foreach (0..reps)
    {
        result = insert_substring_at(result, input, random_from_to(0, length(result));
    }
    return result;
}

Or, in point-and-click terminology, copy the string, then reps times do the following: move the cursor to a random position within the string and hit paste.

Given the output string and reps, how to extract the input string (other than "reverse brute force" based on reconstructing the character list of the original string using reps and output length)?


问:
How to compile google-fhir proto files
Looking at the readme for google-fhir it says to run bazel build, which works, however none of the protocol files have been compiled.

Running protoc --proto_path=. --java_out=. proto/stu3/resources.proto returns a bunch of error about other protos not being found. This goes backwards until 'descriptor.proto' which is not a proto in the folder. None of the protocol files in that directory will manually compile into java files.

*On another note, I was able to take other example protos from other sources and compile those successfully.

UPDATE

Running the command protoc --proto_path=proto/stu3/ --java_out=target proto/stu3/resources.proto from the google-fhir base directory returns the following output:

```<code>~/fhir-master$ protoc --proto_path=proto/stu3/ --java_out=target proto/stu3/resources.proto
proto/stu3/annotations.proto: File not found.
proto/stu3/codes.proto: File not found.
proto/stu3/datatypes.proto: File not found.
resources.proto: Import "proto/stu3/annotations.proto" was not found or had errors.
resources.proto: Import "proto/stu3/codes.proto" was not found or had errors.
resources.proto: Import "proto/stu3/datatypes.proto" was not found or had errors.
resources.proto:84:5: "String" is not defined.
resources.proto:87:14: "Extension" is not defined.
resources.proto:90:14: "Extension" is not defined.
resources.proto:94:5: "Reference" is not defined.
resources.proto:97:5: "PositiveInt" is not defined.
...
...
</code>```

Those files are definitely located in the same proto directory.

UPDATE 2

Well, this definitely doesn't work right out of the box. Moving the files around, I was able to generate the target folder with a bunch of Java files. However, trying to compile them, I get errors for files that don't exist:

```<code>  symbol:   class CodeableConcept
  location: package com.google.fhir.stu3.proto
./PlanDefinition.java:30950: error: cannot find symbol
  public com.google.fhir.stu3.proto.CodeableConceptOrBuilder getJurisdictionOrBuilder(
                               ^
  symbol:   class CodeableConceptOrBuilder
  location: package com.google.fhir.stu3.proto
./PlanDefinition.java:30956: error: cannot find symbol
  private java.util.List<com.google.fhir.stu3.proto.CodeableConcept> topic_;
                                               ^
  symbol:   class CodeableConcept
  location: package com.google.fhir.stu3.proto
./PlanDefinition.java:30964: error: cannot find symbol
  public java.util.List<com.google.fhir.stu3.proto.CodeableConcept> getTopicList() {
                                              ^
  symbol:   class CodeableConcept
  location: package com.google.fhir.stu3.proto
./PlanDefinition.java:30974: error: cannot find symbol
  public java.util.List<? extends com.google.fhir.stu3.proto.CodeableConceptOrBuilder>

  ....                                                         ^
  100 errors.
</code>```

! Also, I don't see these file here: https://github.com/google/protobuf/tree/master/java/core/src/main/java/com/google/protobuf

答:
I got it to work by not specifying a real path to the --proto_path= at all.

How I did it

My folder structure looks like this: D:\dev\OpenSourceProjects\ is my base folder.

Within that folder, I have google-fhir which is my clone of the github repo and protoc-3.11.3-win64 which is the unzip of the protoc binaries

So for example, to build resources.proto run the following in cmd:

cd D:\dev\OpenSourceProjects\google-fhir

D:\dev\OpenSourceProjects\protoc-3.11.3-win64\bin\protoc.exe --proto_path= --java_out=./proto/output .\proto\stu3\resources.proto

Note that --proto_path= is there, but empty and all other paths are relative

Title: How to compile google-fhir proto files

Body:
Looking at the readme for google-fhir it says to run bazel build, which works, however none of the protocol files have been compiled.

Running protoc --proto_path=. --java_out=. proto/stu3/resources.proto returns a bunch of error about other protos not being found. This goes backwards until 'descriptor.proto' which is not a proto in the folder. None of the protocol files in that directory will manually compile into java files.

*On another note, I was able to take other example protos from other sources and compile those successfully.

UPDATE

Running the command protoc --proto_path=proto/stu3/ --java_out=target proto/stu3/resources.proto from the google-fhir base directory returns the following output:

~/fhir-master$ protoc --proto_path=proto/stu3/ --java_out=target proto/stu3/resources.proto
proto/stu3/annotations.proto: File not found.
proto/stu3/codes.proto: File not found.
proto/stu3/datatypes.proto: File not found.
resources.proto: Import "proto/stu3/annotations.proto" was not found or had errors.
resources.proto: Import "proto/stu3/codes.proto" was not found or had errors.
resources.proto: Import "proto/stu3/datatypes.proto" was not found or had errors.
resources.proto:84:5: "String" is not defined.
resources.proto:87:14: "Extension" is not defined.
resources.proto:90:14: "Extension" is not defined.
resources.proto:94:5: "Reference" is not defined.
resources.proto:97:5: "PositiveInt" is not defined.
...
...

Those files are definitely located in the same proto directory.

UPDATE 2

Well, this definitely doesn't work right out of the box. Moving the files around, I was able to generate the target folder with a bunch of Java files. However, trying to compile them, I get errors for files that don't exist:

  symbol:   class CodeableConcept
  location: package com.google.fhir.stu3.proto
./PlanDefinition.java:30950: error: cannot find symbol
  public com.google.fhir.stu3.proto.CodeableConceptOrBuilder getJurisdictionOrBuilder(
                               ^
  symbol:   class CodeableConceptOrBuilder
  location: package com.google.fhir.stu3.proto
./PlanDefinition.java:30956: error: cannot find symbol
  private java.util.List<com.google.fhir.stu3.proto.CodeableConcept> topic_;
                                               ^
  symbol:   class CodeableConcept
  location: package com.google.fhir.stu3.proto
./PlanDefinition.java:30964: error: cannot find symbol
  public java.util.List<com.google.fhir.stu3.proto.CodeableConcept> getTopicList() {
                                              ^
  symbol:   class CodeableConcept
  location: package com.google.fhir.stu3.proto
./PlanDefinition.java:30974: error: cannot find symbol
  public java.util.List<? extends com.google.fhir.stu3.proto.CodeableConceptOrBuilder>

  ....                                                         ^
  100 errors.

! Also, I don't see these file here: https://github.com/google/protobuf/tree/master/java/core/src/main/java/com/google/protobuf


问:
Count over 2 dimensions
I am using excel 365.

I want to get aggregated for each product how often it is used by the departments.

I tried =COUNTIFS($B$2:$E$18;$I$2) on the times, however I do not know how to get the products?

Any suggestions?

答:
It is truly complicated. My solution made it even more complicated, since it accounts for the number of departments (assuming that's the only data in the entirety of row 1) and products (assuming that's the only data in the entirety of column A) and any number of data introduced, also assuming the fixed placement of your calculations as shown in the example picture. Here's the formula you need in I3:

```<code>=COUNTIF(INDIRECT("R"&MATCH($H3,$A:$A,0)&"C2",0):INDIRECT("R"&LOOKUP(2,1/($A$2:INDIRECT("A"&COUNTA($A:$A)+1)=$H3),SEQUENCE(COUNTA($A:$A),1,2))&"C"&COUNTA($1:$1)+1,0),I$2)
</code>```

You need to drag it all over the calculation area. I wanted to do a single cell spill array formula, but I don't think it's even possible right now due to its limitations (it generates the array first, and spills afterwards, making it static).

Title: Count over 2 dimensions

Body:
It is truly complicated. My solution made it even more complicated, since it accounts for the number of departments (assuming that's the only data in the entirety of row 1) and products (assuming that's the only data in the entirety of column A) and any number of data introduced, also assuming the fixed placement of your calculations as shown in the example picture. Here's the formula you need in I3:

=COUNTIF(INDIRECT("R"&MATCH($H3,$A:$A,0)&"C2",0):INDIRECT("R"&LOOKUP(2,1/($A$2:INDIRECT("A"&COUNTA($A:$A)+1)=$H3),SEQUENCE(COUNTA($A:$A),1,2))&"C"&COUNTA($1:$1)+1,0),I$2)

You need to drag it all over the calculation area. I wanted to do a single cell spill array formula, but I don't think it's even possible right now due to its limitations (it generates the array first, and spills afterwards, making it static).


问:
Set Animation speed - ChartJS?
I am trying to set the animation speed of a pie chart in chartJS.

I've tried the following:

numSteps: Number

animationSteps: Number

Chart.defaults.global.animationSteps = Number

None of these have changed the speed. Any advice?

```<code> var myNewChart;
    var data = [
        {
        value: 30,
        label: "hello",
        color: "#F7464A"
      }, {
        value: 50,
        color: "#E2EAE9"
      }, {
        value: 100,
        color: "#D4CCC5"
      }, {
        value: 40,
        color: "#949FB1"
      }, {
        value: 100,
        color: "#4D5360"
      },

    ];

    var options = {
      animation: true,
      animationEasing: 'easeInOutQuart',
      animationSteps: 80,
      multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"

    };

    var ctx = document.getElementById("myChart")
                                        .getContext("2d");

    myNewChart = new Chart(ctx).Doughnut(data, options);
</code>```

答:
Use the animation object

```<code>options: {
        animation: {
            duration: 2000,
        },
</code>```

I haven't see this documented anywhere, but it's incredibly helpful to not have to set the speed globally for every chart.

Title: Set Animation speed - ChartJS?

Body:
I am trying to set the animation speed of a pie chart in chartJS.

I've tried the following:

numSteps: Number

animationSteps: Number

Chart.defaults.global.animationSteps = Number

None of these have changed the speed. Any advice?

 var myNewChart;
    var data = [
        {
        value: 30,
        label: "hello",
        color: "#F7464A"
      }, {
        value: 50,
        color: "#E2EAE9"
      }, {
        value: 100,
        color: "#D4CCC5"
      }, {
        value: 40,
        color: "#949FB1"
      }, {
        value: 100,
        color: "#4D5360"
      },

    ];

    var options = {
      animation: true,
      animationEasing: 'easeInOutQuart',
      animationSteps: 80,
      multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"

    };

    var ctx = document.getElementById("myChart")
                                        .getContext("2d");

    myNewChart = new Chart(ctx).Doughnut(data, options);

Body:
Use the animation object

options: {
        animation: {
            duration: 2000,
        },

I haven't see this documented anywhere, but it's incredibly helpful to not have to set the speed globally for every chart.


问:
How to stop a function
For example:

```<code>def main():
    if something == True:
        player()
    elif something_else == True:
        computer()

def player():
    # do something here
    check_winner()  # check something
    computer()  # let the computer do something

def check_winner():
    check something
    if someone wins:
        end()

def computer():
    # do something here
    check_winner() # check something
    player() # go back to player function

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        # the player doesn't want to play again:
        # stop the program

    # whatever i do here won't matter because it will go back to player() or computer()

main()  # start the program
</code>```

My problem is that if a certain condition becomes true (in the function check_winner) and function end() executes it will go back to computer() or player() because there's no line that tells the computer to stop executing player() or computer(). How do you stop functions in Python?

答:
This will end the function, and you can even customize the "Error" message: </p>

```<code>import sys

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        sys.exit("The player doesn't want to play again") #Right here
</code>```

Title: How to stop a function

Body:
For example:

def main():
    if something == True:
        player()
    elif something_else == True:
        computer()

def player():
    # do something here
    check_winner()  # check something
    computer()  # let the computer do something

def check_winner():
    check something
    if someone wins:
        end()

def computer():
    # do something here
    check_winner() # check something
    player() # go back to player function

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        # the player doesn't want to play again:
        # stop the program

    # whatever i do here won't matter because it will go back to player() or computer()

main()  # start the program

My problem is that if a certain condition becomes true (in the function check_winner) and function end() executes it will go back to computer() or player() because there's no line that tells the computer to stop executing player() or computer(). How do you stop functions in Python?

Body:
This will end the function, and you can even customize the "Error" message:

import sys

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        sys.exit("The player doesn't want to play again") #Right here


问:
is there anyway to get Hyperlink content from resource file in WPF
Is there anyway to get hyperlink content from resource file in xaml. I know there is way on back hand code. I have tried using Name="{x:Static Properties:Resources.stringname}" but it throws error

Or if there is any work around?

I have tried Name but it gives an error:Not able to bind to Uid or Name property in XAML

答:
How about:</p>

```<code><Hyperlink NavigateUri="{x:Static Properties:Resources.SomeUrl}">
    <Run Text="{x:Static Properties:Resources.SomeUrl_Description}"/>
</Hyperlink>
</code>```

Body:
How about:

<Hyperlink NavigateUri="{x:Static Properties:Resources.SomeUrl}">
    <Run Text="{x:Static Properties:Resources.SomeUrl_Description}"/>
</Hyperlink>


问:
How to convert subquery objects into ResultProxy class when joined in SqlAlchemy?
I have an ORM class and a subquery. I created a join between the two and I want to access the subquery fields as an class may be a dummy ResultProxy object.

Code example:

```<code>session.query(ORM_Class,subqyery).\
       join(subqyery,ORM_Class.id==subqyery.id).all()
</code>```

It would result me in a tupled resultset which has first object of ORM_CLass which makes sense but the rest id field would be just pure values of the subquery.

Output

```<code>[(orm.my_orm.ORM_Class Object , 1)]
</code>```

1 is the Id coming from the subquery part. I want to access id as ResultProxy.id or any other form similar.

Can we explicitly type cast into some other form?

答:
As mentioned by @ilja-everilä in the comments, each record of your query is a KeyedTuple, which is like a namedtuple in Python, which means each field in it has a position in the tuple but also an attribute name.

You can get a list of strings containing the attribute names of one of these records with the .keys() method, or if you actually have a column called keys that would blot out the .keys() method, you can also use the ._fields attribute. E.g.:

```<code>>>> myquery.all()[0].keys()
['ORM_Class', 'something_id']
</code>```

or

```<code>>>> myquery.all()[0]._fields
['ORM_Class', 'something_id']
</code>```

The above tells me I could access the second field using the something_id attribute:

```<code>>>> myquery.all()[0].something_id
235
</code>```

You can also get a dictionary mapping all entity names of a record to their values using the ._asdict() method:

```<code>>>> myquery.all()[0]._asdict()
{'ORM_Class': <orm.my_orm.ORM_Class object at 0xdeadbeefc0ff>,
 'something_id': 235}
</code>```

Body:
I have an ORM class and a subquery. I created a join between the two and I want to access the subquery fields as an class may be a dummy ResultProxy object.

Code example:

session.query(ORM_Class,subqyery).\
       join(subqyery,ORM_Class.id==subqyery.id).all()

It would result me in a tupled resultset which has first object of ORM_CLass which makes sense but the rest id field would be just pure values of the subquery.

Output

[(orm.my_orm.ORM_Class Object , 1)]

1 is the Id coming from the subquery part. I want to access id as ResultProxy.id or any other form similar.

Can we explicitly type cast into some other form?

Body:
As mentioned by @ilja-everilä in the comments, each record of your query is a KeyedTuple, which is like a namedtuple in Python, which means each field in it has a position in the tuple but also an attribute name.

You can get a list of strings containing the attribute names of one of these records with the .keys() method, or if you actually have a column called keys that would blot out the .keys() method, you can also use the ._fields attribute. E.g.:

>>> myquery.all()[0].keys()
['ORM_Class', 'something_id']

or

>>> myquery.all()[0]._fields
['ORM_Class', 'something_id']

The above tells me I could access the second field using the something_id attribute:

>>> myquery.all()[0].something_id
235

You can also get a dictionary mapping all entity names of a record to their values using the ._asdict() method:

>>> myquery.all()[0]._asdict()
{'ORM_Class': <orm.my_orm.ORM_Class object at 0xdeadbeefc0ff>,
 'something_id': 235}


问:
Is it possible to use iscsiadm from the same iSCSI server?
I have sparse knowledge of iSCSI and hence I fear I'm missing the obvious.

I have set up a ZFS unit and I would like to export some LUNs.

The SCST daemon is listening properly on port 3260 and the scstadmin says the config is OK.
Whenever I try to run iscsiadm to check what the server show to the world iscsiadm doesn't send out anything

```<code>root@brunas:/# iscsiadm --mode discovery --type sendtargets --portal a.b.c.d --discover
iscsiadm: Login response timeout. Waited 30 seconds and did not get reponse PDU.

iscsiadm: discovery login to a.b.c.d failed, giving up 2
iscsiadm: Could not perform SendTargets discovery: encountered non-retryable iSCSI login failure
</code>```

I took captures with tcpdump and iscsiadm is not sending out any single packet.

The only thing is that I'm sourcing the queries from the same host that runs the server, I do use an IP of an ethernet interface. Does the iscsiadm have to be run from a different host than the iSCSI server (I would be surprised) ?

Is there anyone who may give me a clue please?

Alex

答: Sorry, the problem disappeared by itself and I wouldn't know what was the root cause. For sure now I know that even from the iSCSI server I can login onto the target.</p>

Body:
I have sparse knowledge of iSCSI and hence I fear I'm missing the obvious.

I have set up a ZFS unit and I would like to export some LUNs.

The SCST daemon is listening properly on port 3260 and the scstadmin says the config is OK.
Whenever I try to run iscsiadm to check what the server show to the world iscsiadm doesn't send out anything

root@brunas:/# iscsiadm --mode discovery --type sendtargets --portal a.b.c.d --discover
iscsiadm: Login response timeout. Waited 30 seconds and did not get reponse PDU.

iscsiadm: discovery login to a.b.c.d failed, giving up 2
iscsiadm: Could not perform SendTargets discovery: encountered non-retryable iSCSI login failure

I took captures with tcpdump and iscsiadm is not sending out any single packet.

The only thing is that I'm sourcing the queries from the same host that runs the server, I do use an IP of an ethernet interface. Does the iscsiadm have to be run from a different host than the iSCSI server (I would be surprised) ?

Is there anyone who may give me a clue please?

Alex


问:
How to set active with multiple buttons
I have three buttons that are generated in a div using v-for. When a button is clicked I want that specific button to get the active class and the one that was previously active to drop that class. I know how to do it with v-bind with one button. But I'm just not sure of the logic with three.

I thought about having three IsActiveButton1, IsActiveButton2 and IsActiveButton3. Then trying to bind the class to those. But since I'm using v-for I don't know how to tell it which IsActive to bind to. I also feel like there is a more efficient way.

I have played aroung with the radio buttons toggle for vuejs however it very much lacks the styling abilities I need on the buttons.

```<code><template>
    <div id="basemap_container">
        <button v-for="option in options"
            :key="option.value"
            :class="option.class"
            @click="UpdateBaseMap(option.value)"
        >{{option.text}}
        </button>
        <button
            id="collapse_basemap"
            class="btn_group_basemap"
            @click="CollapseBaseMap()"
            >»
        </button>
    </div>

</template>

<script>

export default {
    name:"BaseMapToggle",
    data(){
        return{
         current_basemap: "streets",
         basemap_changer_active: true,
        options:[
                {text: "satellite", value:"satellite",class: "btn_group_basemap"},
                {text: "topo", value:"topo",class: "btn_group_basemap"},
                {text: "streets", value:"streets",class: "btn_group_basemap active"}
            ]
        }
    },
    methods:{
        UpdateBaseMap(value)
        {
            this.current_basemap = value;
            this.$store.commit('UpdateBaseMap',this.current_basemap);
        },

        CollapseBaseMap()
        {
            this.basemap_changer_active = !this.basemap_changer_active;
            const changer = document.querySelector("#collapse_basemap");
        }
    }
}
</script>
</code>```

答:
You could use your current_basemap variable to do it:

```<code><button v-for="option in options"
  :key="option.value"
  :class="option.class + `${option.value === current_basemap ? ' active ' : ''}`"
  @click="UpdateBaseMap(option.value)">
  {{option.text}}
</button>
</code>```

Title: How to set active with multiple buttons

Body:
I have three buttons that are generated in a div using v-for. When a button is clicked I want that specific button to get the active class and the one that was previously active to drop that class. I know how to do it with v-bind with one button. But I'm just not sure of the logic with three.

I thought about having three IsActiveButton1, IsActiveButton2 and IsActiveButton3. Then trying to bind the class to those. But since I'm using v-for I don't know how to tell it which IsActive to bind to. I also feel like there is a more efficient way.

I have played aroung with the radio buttons toggle for vuejs however it very much lacks the styling abilities I need on the buttons.

<template>

        <button v-for="option in options"
            :key="option.value"
            :class="option.class"
            @click="UpdateBaseMap(option.value)"
        >{{option.text}}
        </button>
        <button
            id="collapse_basemap"
            class="btn_group_basemap"
            @click="CollapseBaseMap()"
            >»
        </button>

</template>

Body:
You could use your current_basemap variable to do it:

<button v-for="option in options"
  :key="option.value"
  :class="option.class + `${option.value === current_basemap ? ' active ' : ''}`"
  @click="UpdateBaseMap(option.value)">
  {{option.text}}
</button>


问:
How to get confidence interval of high standard deviation time-based data?
I'm working with an analysis of some latencies (in seconds). My idea is to find my confidence interval where 95% of my results fit, so I can have some idea of the PDF.

By sight, the more common latencies I get are under 30 seconds, but eventually there are some problems in the system which can give me up to 25 minutes. This doesn't concern me, since the cadency in which the system works is around 1h per cycle.

My point is that, working with times that have that much difference, my confidence interval seems "not fair". Here is an example of a confidence interval I got using standard deviation:

My idea is to find the best fit PDF, get its parameters and then use this alone to find my confidence interval. I tested a few diferent distributions and actually got JohnsonSU and the best fit for this data. Here it is:

Is it possible for me to use the parameters of JohnsonSU alone, without using my data, so I can find an acceptable confidence interval?

答:
You can get and interval of confidence by the expression:

(mean-(std/sqrt(n)),mean+(std/sqrt(n))). If your distribution is standad and you know the population std.

Othewrwise you'll need to check a specific expression that suits your distribution.


问:
Powershell -Select String (SLS) spliting one line into multiples
I've been looking for a way to perform basic grep with Powershell.

I have an input text file but want to extract only some of them
For instance,

```<code>2020-02-04 05:42:12,132 INFO UselessLog   8=FIX4.4|35=D|49=sender1|56=recipient|....
2020-02-04 05:42:12,134 INFO UselessLog2  8=FIX5.0|35=AB|49=sender2|56=recipient2|....
2020-02-04 05:42:12,136 INFO UselessLog2  8=FIX5.0|35=AB|49=sender3|56=recipient2|....
</code>```

I'm trying to parse the file with

```<code>sls "8=FIX" fixlogs -ca | select -exp line |sls "=sender1" > parseFix
</code>```

However, when I open the parseFix file, sls just transformed one line into multiple ones; e.g., the following two lines represent a single match:

```<code>2020-02-04 05:42:12,132 INFO UselessLog
8=FIX4.4|35=D|49=sender1|56=recipient|...
</code>```

I'm fairly certain there's a config in Powershell to advise not to split but I've investigated and failed to find the one.

I have no access to Unix/Linux server to do a grep magic also I have checked within StackOverFlow but didn't find anything matching my Question.

答:
There's a lot going on here.  Select-string is outputting a object with a custom format view.  ">" is the same as "| out-file", which adds extra formatting, like wrapping the line if it thinks it's too long.  You didn't show the whole lines of the log but they look pretty long.  By the way, out-file defaults to utf16 encoding (PS 5).  Set-content seems to work ok and convert the object to a string:

```<code>sls 8=FIX fixlogs -ca | select -exp line | sls =sender1 | set-content parsefix
</code>```

Also, you can make that one regex pattern if the whole thing can be case sensitive or case insensitive.

```<code>sls 8=FIX.*=sender1 fixlogs

fixlogs:1:2020-02-04 05:42:12,132 INFO UselessLog   8=FIX4.4|35=D|49=sender1|56=recipient|....
</code>```

Or just skip the select:

```<code>sls 8=FIX fixlogs -ca | sls =sender1
</code>```

Body:
I've been looking for a way to perform basic grep with Powershell.

I have an input text file but want to extract only some of them
For instance,

2020-02-04 05:42:12,132 INFO UselessLog   8=FIX4.4|35=D|49=sender1|56=recipient|....
2020-02-04 05:42:12,134 INFO UselessLog2  8=FIX5.0|35=AB|49=sender2|56=recipient2|....
2020-02-04 05:42:12,136 INFO UselessLog2  8=FIX5.0|35=AB|49=sender3|56=recipient2|....

I'm trying to parse the file with

sls "8=FIX" fixlogs -ca | select -exp line |sls "=sender1" > parseFix

However, when I open the parseFix file, sls just transformed one line into multiple ones; e.g., the following two lines represent a single match:

2020-02-04 05:42:12,132 INFO UselessLog
8=FIX4.4|35=D|49=sender1|56=recipient|...

I'm fairly certain there's a config in Powershell to advise not to split but I've investigated and failed to find the one.

I have no access to Unix/Linux server to do a grep magic also I have checked within StackOverFlow but didn't find anything matching my Question.

Body:
There's a lot going on here.  Select-string is outputting a object with a custom format view.  ">" is the same as "| out-file", which adds extra formatting, like wrapping the line if it thinks it's too long.  You didn't show the whole lines of the log but they look pretty long.  By the way, out-file defaults to utf16 encoding (PS 5).  Set-content seems to work ok and convert the object to a string:

sls 8=FIX fixlogs -ca | select -exp line | sls =sender1 | set-content parsefix

Also, you can make that one regex pattern if the whole thing can be case sensitive or case insensitive.

sls 8=FIX.*=sender1 fixlogs

fixlogs:1:2020-02-04 05:42:12,132 INFO UselessLog   8=FIX4.4|35=D|49=sender1|56=recipient|....

Or just skip the select:

sls 8=FIX fixlogs -ca | sls =sender1


问:
I need to change the colour of a button in an android widget
I have a widget with a button that users must press within a given interval. The button works fine and resets the interval but I want the button to change colour green -> amber -> red depending on time left. I have no problem changing the text on the button using remote views with code like this:

```<code>RemoteViews views =new RemoteViews(context.getPackageName(), R.layout.example_widget);
views.setCharSequence(R.id.example_widget_button, "setText", buttonText);
</code>```

But I can not make any sort of code change the button colour. I've tried several things along the lines of:

```<code>views.setCharSequence(R.id.example_widget_button, "setBackgroundTint", "#039be5");
</code>```

I have also tried using a drawable background and changing that. I'm missing something really obvious -it must be possible- I just can't find an example that works in my context.

Can anyone point me?

答:
You can do this:

```<code>views.setInt(R.id.example_widget_button, "setBackgroundColor", android.graphics.Color.BLACK)`;
</code>```

and you change the color to be what you want at that time.

Body:
I have a widget with a button that users must press within a given interval. The button works fine and resets the interval but I want the button to change colour green -> amber -> red depending on time left. I have no problem changing the text on the button using remote views with code like this:

RemoteViews views =new RemoteViews(context.getPackageName(), R.layout.example_widget);
views.setCharSequence(R.id.example_widget_button, "setText", buttonText);

But I can not make any sort of code change the button colour. I've tried several things along the lines of:

views.setCharSequence(R.id.example_widget_button, "setBackgroundTint", "#039be5");

I have also tried using a drawable background and changing that. I'm missing something really obvious -it must be possible- I just can't find an example that works in my context.

Can anyone point me?

Body:
You can do this:

views.setInt(R.id.example_widget_button, "setBackgroundColor", android.graphics.Color.BLACK)`;

and you change the color to be what you want at that time.


问:
Dynamic minDate for datepicker
I'm trying to cause my Datepicker to set its minimum date dynamically based on value chosen from List of Values. To be specific I have a club that has a date of creation. Based on that I want to create a member of that club, but after choosing to which club I want to add that member I want the minDate value of the Datepicker to be set as the day of creation of that specific club (for example I choose a club that was created 31/08/99 so the datepicker's minDate should be that date). Will be grateful for any help.
(I've tried getting the date and assinging it to a hidden item in order to reference it but the only thing I achieved is all dates being blocked. Don't know if that's an issue with the solution or maybe with the return value of sql query that returns the date. I also could't find any documentation regarding Datepicker to understand what can be typed in the Minimum/Maximum Date attribute-fields)</p>

答:
You can reference a page item for minimum date.
Getting the date and writing it to an hidden item was the correct first step.
You can utilize a dynamic action on change of your Select List (LoV) which sets the clubs creation date for the hidden item (make sure to utilize correct Dateformat here, this needs to be the same as your datepickers)

Make sure to add the hidden item to "Items to return" so its value is saved.

Add a 2nd true action which refreshed your datepicker item

Title: Dynamic minDate for datepicker


问:
Swift Codable - How to encode custom array
That's my JSON case

{
    "image_id" : 11101,
    "image_source_id" : 9,
    "image_author" : "",
    "image_copyright" : "",
    "image_format_list" : [
        {
            "image_format" : {
                "image_url" : "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_2.jpg",
                "image_format_id" : 2,
                "width" : 150,
                "height" : 150
            }
        },
        {
            "image_format" : {
                "image_url" : "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_16.jpg",
                "image_format_id" : 16,
                "width" : 451,
                "height" : 500
            }
        }
    ]
}
```
<p>I correctly decode my custom object in two different classes: MXMImage & MXMImageFormat.
But I can't figure out how to re-encode my object to rebuild the same JSON</p>
<p>That's my code:</p>
<pre class="lang-swift prettyprint-override"><code>struct MXMImage : Codable, Equatable {
    let imageId: Int
    let imageSourceId: Int
    let imageAuthor: String?
    let imageCopyright: String?
    let imageFormatList: [MXMImageFormat]?

    enum CodingKeys: String, Swift.CodingKey {
        case imageId
        case imageSourceId
        case imageAuthor
        case imageCopyright
        case imageFormatList

        enum ImageFormatListKey: String, CodingKey {
            case imageFormat
        }
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        imageId = try (container.decodeIfPresent(Int.self, forKey: .imageId) ?? 0)
        imageSourceId = try (container.decodeIfPresent(Int.self, forKey: .imageSourceId) ?? 0)
        imageAuthor = try? container.decodeIfPresent(String.self, forKey: .imageAuthor)
        imageCopyright = try? container.decodeIfPresent(String.self, forKey: .imageCopyright)

        var imagesFormatListContainer = try container.nestedUnkeyedContainer(forKey: .imageFormatList)
        var imagesList:[MXMImageFormat] = []
        while !imagesFormatListContainer.isAtEnd {
            let imageFormatContainer = try imagesFormatListContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
            let imageFormat = try? imageFormatContainer.decode(MXMImageFormat.self, forKey: .imageFormat)
            if let imageFormat = imageFormat {
                imagesList.append(imageFormat)
            }
        }
        self.imageFormatList = imagesList
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encodeIfPresent(imageId, forKey: .imageId)
        try container.encodeIfPresent(imageSourceId, forKey: .imageSourceId)
        try container.encodeIfPresent(imageAuthor, forKey: .imageAuthor)
        try container.encodeIfPresent(imageCopyright, forKey: .imageCopyright)

        var imageContainer = container.nestedUnkeyedContainer(forKey: .imageFormatList)
        try imageFormatList?.forEach { imgFormat in
            var nested = imageContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
            let data = try imgFormat.encoded()
            try nested.encode(data, forKey: .imageFormat)

        }
    }
}
</code>```

In particular, I don't know how to re-indent my MXMImageFormat objects inside the key image_format and then encode the custom array. Is it possible to do that? Thanks in advance

答:
Assuming MXMImageFormat is like this:

```<code>struct MXMImageFormat : Codable {
    let imageUrl: String
    let imageFormatId: Int
    let width: Int
    let height: Int
}
</code>```

I think you are overthinking this. You can just do:

```<code>try imageFormatList?.forEach { imgFormat in
    var nested = imageContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
    try nested.encode(imgFormat, forKey: .imageFormat)
}
</code>```

Since encode accepts any Encodable, including imgFormat. You don't actually need to convert to a Data first (at least that's why you seem to be attempting to do).

Some test code:

```<code>let json = """
{
   "image_id": 11101,
   "image_source_id": 9,
   "image_author": "",
   "image_copyright": "",
   "image_format_list": [{
           "image_format": {
               "image_url": "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_2.jpg",
               "image_format_id": 2,
               "width": 150,
               "height": 150
           }
       },
       {
           "image_format": {
               "image_url": "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_16.jpg",
               "image_format_id": 16,
               "width": 451,
               "height": 500
           }
       }
   ]
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let model = try! decoder.decode(MXMImage.self, from: json)
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let string = String(data: try! encoder.encode(model), encoding: .utf8)!
print(string) // this should be the same JSON as the one in the string literal
</code>```

Also note that in encode, you don't have to use try? here:

```<code>while !imagesFormatListContainer.isAtEnd {
    let imageFormatContainer = try imagesFormatListContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
    // here vvvvvvv
    let imageFormat = try? imageFormatContainer.decode(MXMImageFormat.self, forKey: .imageFormat)
    if let imageFormat = imageFormat {
        imagesList.append(imageFormat)
    }
}
</code>```

Body:
That's my JSON case

{
    "image_id" : 11101,
    "image_source_id" : 9,
    "image_author" : "",
    "image_copyright" : "",
    "image_format_list" : [
        {
            "image_format" : {
                "image_url" : "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_2.jpg",
                "image_format_id" : 2,
                "width" : 150,
                "height" : 150
            }
        },
        {
            "image_format" : {
                "image_url" : "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_16.jpg",
                "image_format_id" : 16,
                "width" : 451,
                "height" : 500
            }
        }
    ]
}

I correctly decode my custom object in two different classes: MXMImage & MXMImageFormat.
But I can't figure out how to re-encode my object to rebuild the same JSON

That's my code:

struct MXMImage : Codable, Equatable {
    let imageId: Int
    let imageSourceId: Int
    let imageAuthor: String?
    let imageCopyright: String?
    let imageFormatList: [MXMImageFormat]?

    enum CodingKeys: String, Swift.CodingKey {
        case imageId
        case imageSourceId
        case imageAuthor
        case imageCopyright
        case imageFormatList

        enum ImageFormatListKey: String, CodingKey {
            case imageFormat
        }
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        imageId = try (container.decodeIfPresent(Int.self, forKey: .imageId) ?? 0)
        imageSourceId = try (container.decodeIfPresent(Int.self, forKey: .imageSourceId) ?? 0)
        imageAuthor = try? container.decodeIfPresent(String.self, forKey: .imageAuthor)
        imageCopyright = try? container.decodeIfPresent(String.self, forKey: .imageCopyright)

        var imagesFormatListContainer = try container.nestedUnkeyedContainer(forKey: .imageFormatList)
        var imagesList:[MXMImageFormat] = []
        while !imagesFormatListContainer.isAtEnd {
            let imageFormatContainer = try imagesFormatListContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
            let imageFormat = try? imageFormatContainer.decode(MXMImageFormat.self, forKey: .imageFormat)
            if let imageFormat = imageFormat {
                imagesList.append(imageFormat)
            }
        }
        self.imageFormatList = imagesList
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encodeIfPresent(imageId, forKey: .imageId)
        try container.encodeIfPresent(imageSourceId, forKey: .imageSourceId)
        try container.encodeIfPresent(imageAuthor, forKey: .imageAuthor)
        try container.encodeIfPresent(imageCopyright, forKey: .imageCopyright)

        var imageContainer = container.nestedUnkeyedContainer(forKey: .imageFormatList)
        try imageFormatList?.forEach { imgFormat in
            var nested = imageContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
            let data = try imgFormat.encoded()
            try nested.encode(data, forKey: .imageFormat)

        }
    }
}

In particular, I don't know how to re-indent my MXMImageFormat objects inside the key image_format and then encode the custom array. Is it possible to do that? Thanks in advance

Body:
Assuming MXMImageFormat is like this:

struct MXMImageFormat : Codable {
    let imageUrl: String
    let imageFormatId: Int
    let width: Int
    let height: Int
}

I think you are overthinking this. You can just do:

try imageFormatList?.forEach { imgFormat in
    var nested = imageContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
    try nested.encode(imgFormat, forKey: .imageFormat)
}

Since encode accepts any Encodable, including imgFormat. You don't actually need to convert to a Data first (at least that's why you seem to be attempting to do).

Some test code:

let json = """
{
   "image_id": 11101,
   "image_source_id": 9,
   "image_author": "",
   "image_copyright": "",
   "image_format_list": [{
           "image_format": {
               "image_url": "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_2.jpg",
               "image_format_id": 2,
               "width": 150,
               "height": 150
           }
       },
       {
           "image_format": {
               "image_url": "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_16.jpg",
               "image_format_id": 16,
               "width": 451,
               "height": 500
           }
       }
   ]
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let model = try! decoder.decode(MXMImage.self, from: json)
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let string = String(data: try! encoder.encode(model), encoding: .utf8)!
print(string) // this should be the same JSON as the one in the string literal

Also note that in encode, you don't have to use try? here:

while !imagesFormatListContainer.isAtEnd {
    let imageFormatContainer = try imagesFormatListContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
    // here vvvvvvv
    let imageFormat = try? imageFormatContainer.decode(MXMImageFormat.self, forKey: .imageFormat)
    if let imageFormat = imageFormat {
        imagesList.append(imageFormat)
    }
}


问:
Group by each unique id and then find number of purchases for each brand
I have customer purchase data for the last 3 years. A sample below:

```<code> customer_id|date      |sales_amount|product_type
 479485     |20190120  | 500        | bags
 479485     |20180320  | 200        | clothes
 479485     |20180321  | 200        | clothes
 472848     |20191020  | 100        | clothes
</code>```

I want to find for each unique customer id, number of transactions they had over the three years for the different product type. Ideally a value count on product type for each unique customer id. So for customer_id = 479485 the output :

```<code> customer_id
 479485     |bags      | 1
            |clothes   | 2
</code>```

I have tried doing a pivot table but it is not giving me my ideal result:

pd.pivot_table(clusters, index=['customer_id', 'product_type'], aggfunc='sum')

bonus: If I wanted to do the same thing but look at it but separate it by year is that possible?

答:
Assuming the input data is like this:

```<code>df=pd.DataFrame({'cust_id':[479485,479485,479485,472848],
                 'date':['20190120','20180320','20180321','20191020'],
                 'sales_amount':[500,200,200,100],
                 'product_type':['bags','clothes','clothes','clothes']})
</code>```

I would do something like this:

```<code>df.groupby(['cust_id','product_type'])['sales_amount'].count()
</code>```

Grouping by year is of course possible. There are several options but you have to look at the datetime library to convert the date column into a datetime object and then work on that.

Body:
I have customer purchase data for the last 3 years. A sample below:

 customer_id|date      |sales_amount|product_type
 479485     |20190120  | 500        | bags
 479485     |20180320  | 200        | clothes
 479485     |20180321  | 200        | clothes
 472848     |20191020  | 100        | clothes

I want to find for each unique customer id, number of transactions they had over the three years for the different product type. Ideally a value count on product type for each unique customer id. So for customer_id = 479485 the output :

 customer_id
 479485     |bags      | 1
            |clothes   | 2

I have tried doing a pivot table but it is not giving me my ideal result:

pd.pivot_table(clusters, index=['customer_id', 'product_type'], aggfunc='sum')

bonus: If I wanted to do the same thing but look at it but separate it by year is that possible?

Body:
Assuming the input data is like this:

df=pd.DataFrame({'cust_id':[479485,479485,479485,472848],
                 'date':['20190120','20180320','20180321','20191020'],
                 'sales_amount':[500,200,200,100],
                 'product_type':['bags','clothes','clothes','clothes']})

I would do something like this:

df.groupby(['cust_id','product_type'])['sales_amount'].count()

Grouping by year is of course possible. There are several options but you have to look at the datetime library to convert the date column into a datetime object and then work on that.


问:
Sorting arraylist in alphabetical order(Persian)
I have a list of items in Persian and I want to sort them in alphabetical order.

As I understood java does not support sorting in Persian alphabetical correctly.

My code:

```<code>List<String> items = new ArrayList<>();
items.add("آب");
items.add("بابا");
items.add("تار");
items.add("پارک");
items.add("توت");

Collections.sort(items);
</code>```

When I print this list the result will be:

```<code>آب
بابا
تار
توت
پارک
</code>```

But it must be like this:

```<code>آب
بابا
پارک
تار
توت
</code>```

The problem is with these letters گ چ پ ژ

How can I fix it?

答:
if you have an arrayList of objects you can use this method

first create a collator:

```<code>val collator: Collator = Collator.getInstance(Locale("fa", "IR"))
collator.strength = Collator.PRIMARY
</code>```

then your list via sortedBy like this:

```<code>val sortList = items.sortedWith(compareBy (collator){ it.name})
</code>```

that items is your arrayList of objects and it.name is your comparator

Body:
I have a list of items in Persian and I want to sort them in alphabetical order.

As I understood java does not support sorting in Persian alphabetical correctly.

My code:

List<String> items = new ArrayList<>();
items.add("آب");
items.add("بابا");
items.add("تار");
items.add("پارک");
items.add("توت");

Collections.sort(items);

When I print this list the result will be:

آب
بابا
تار
توت
پارک

But it must be like this:

آب
بابا
پارک
تار
توت

The problem is with these letters گ چ پ ژ

How can I fix it?

Body:
if you have an arrayList of objects you can use this method

first create a collator:

val collator: Collator = Collator.getInstance(Locale("fa", "IR"))
collator.strength = Collator.PRIMARY

then your list via sortedBy like this:

val sortList = items.sortedWith(compareBy (collator){ it.name})

that items is your arrayList of objects and it.name is your comparator