问:
How do I check if something is an elem of a qw?
According to the documentation b c d e> and qw|a b c d e| are similar, and furthermore they both make lists, which means they should be equivalent to ('a', 'b', 'c', 'd', 'e').

Why then am I not able to do this: '2' (elem) <1 2 3 4 5>?

2 (elem) <1 2 3 4 5> doesn't work either, but 'a' (elem) b c d e> DOES.

What's going on? Shouldn't I be able to check the existence of the number like anything else?

答:
check if something is an element

The only coercion that (elem) applies is the minimum necessary to enable its right hand side argument to accept a set operation. It does not coerce at the element level and instead does strict comparison of values. So you must apply your own explicit coercion, for example:

```<code>'2' (elem) qw<1 2 3>                   ; # True
'2' (elem) ~«<1 2 3>                   ; # True
'2' (elem)   <1 2 3>».Str              ; # True
'2' (elem)   <1 2 3> .map: *.Str       ; # True

2   (elem) +«<1 2 3>                   ; # True
2   (elem)   <1 2 3>».Int              ; # True
2   (elem)   <1 2 3> .map: *.Int       ; # True

'2' (elem)   <a 2> .duckmap: *.Int     ; # False
2   (elem)   <a 2> .duckmap: *.Int     ; # True
'a' (elem)   <a 2> .duckmap: *.Int     ; # False

'2' (elem)   <a 2> .duckmap: *.Str     ; # True
2   (elem)   <a 2> .duckmap: *.Str     ; # False
'a' (elem)   <a 2> .duckmap: *.Str     ; # True
</code>```

«/» distribute an operation to the leaves of their tree or list argument(s). For example, +« distributes a prefix +, which coerces its argument to a number.

duckmap is somewhat similar to «/»; one major difference is that it just continues if an operation doesn't apply. That is to say, a trial bind (function call) is attempted for each element; if the type signature matches, the function is called and its return value(s) replace that element, otherwise the element is just retained in the result as is.

Body:
According to the documentation  and qw|a b c d e| are similar, and furthermore they both make lists, which means they should be equivalent to ('a', 'b', 'c', 'd', 'e').

Why then am I not able to do this: '2' (elem) <1 2 3 4 5>?

2 (elem) <1 2 3 4 5> doesn't work either, but 'a' (elem)  DOES.

What's going on? Shouldn't I be able to check the existence of the number like anything else?

Body:
check if something is an element

The only coercion that (elem) applies is the minimum necessary to enable its right hand side argument to accept a set operation. It does not coerce at the element level and instead does strict comparison of values. So you must apply your own explicit coercion, for example:

'2' (elem) qw<1 2 3>                   ; # True
'2' (elem) ~«<1 2 3>                   ; # True
'2' (elem)   <1 2 3>».Str              ; # True
'2' (elem)   <1 2 3> .map: *.Str       ; # True

2   (elem) +«<1 2 3>                   ; # True
2   (elem)   <1 2 3>».Int              ; # True
2   (elem)   <1 2 3> .map: *.Int       ; # True

'2' (elem)   <a 2> .duckmap: *.Int     ; # False
2   (elem)   <a 2> .duckmap: *.Int     ; # True
'a' (elem)   <a 2> .duckmap: *.Int     ; # False

'2' (elem)   <a 2> .duckmap: *.Str     ; # True
2   (elem)   <a 2> .duckmap: *.Str     ; # False
'a' (elem)   <a 2> .duckmap: *.Str     ; # True

«/» distribute an operation to the leaves of their tree or list argument(s). For example, +« distributes a prefix +, which coerces its argument to a number.

duckmap is somewhat similar to «/»; one major difference is that it just continues if an operation doesn't apply. That is to say, a trial bind (function call) is attempted for each element; if the type signature matches, the function is called and its return value(s) replace that element, otherwise the element is just retained in the result as is.


来源: stackexchange

问:
Calculate percentage aggregating counts in SQL
I have a SQL Server table called AccessLog that is inserted into every time a user clicks "Log In" on my website. The important fields are UserID, BrowserName and Date. The intent is to get an idea of which browsers are used the most to access the site.

Here is a sample data set:

```<code>| UserID | BrowserName | Date  |
|--------|-------------|-------|
| 1      | Chrome      | 05/28 |
| 1      | Chrome      | 05/29 |
| 2      | Firefox     | 05/29 |
| 1      | Chrome      | 05/30 |
| 3      | Firefox     | 05/31 |

</code>```

This is the SQL code I use (found here):

SELECT BrowserName
    ,(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER ()) pct
    ,COUNT(*) ct
FROM AccessLog
GROUP BY BrowserName

```

<p>These are the results I get with that query:</p>

```| BrowserName | pct  | ct |
|-------------|------|----|
| Chrome      | 60.0 | 3  |
| Firefox     | 40.0 | 2  |
```

<p>But these are the results I want:</p>

```| BrowserName | pct  | ct |
|-------------|------|----|
| Chrome      | 33.3 | 1  |
| Firefox     | 66.6 | 2  |
```

How can I modify my query to count each distinct UserID and BrowserName pair once, to not artificially inflate the counts?

答:
You want to use count(distinct).  But that is not possible as a window function -- directly -- in SQL Server.  So use the dense_rank() trick:

```<code>SELECT BrowserName,
       (COUNT(DISTINCT UserId) * 100.0 /
        (DENSE_RANK() OVER (ORDER BY UserId ASC) +
         DENSE_RANK() OVER (ORDER BY UserId DESC)
        )
       ) as pct,
      COUNT(DISTINCT UserId) as ct
FROM AccessLog
GROUP BY BrowserName
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a SQL Server table called AccessLog that is inserted into every time a user clicks "Log In" on my website. The important fields are UserID, BrowserName and Date. The intent is to get an idea of which browsers are used the most to access the site.

Here is a sample data set:

| UserID | BrowserName | Date  |
|--------|-------------|-------|
| 1      | Chrome      | 05/28 |
| 1      | Chrome      | 05/29 |
| 2      | Firefox     | 05/29 |
| 1      | Chrome      | 05/30 |
| 3      | Firefox     | 05/31 |

This is the SQL code I use (found here):

SELECT BrowserName
    ,(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER ()) pct
    ,COUNT(*) ct
FROM AccessLog
GROUP BY BrowserName

These are the results I get with that query:

| BrowserName | pct  | ct |
|-------------|------|----|
| Chrome      | 60.0 | 3  |
| Firefox     | 40.0 | 2  |

But these are the results I want:

| BrowserName | pct  | ct |
|-------------|------|----|
| Chrome      | 33.3 | 1  |
| Firefox     | 66.6 | 2  |

How can I modify my query to count each distinct UserID and BrowserName pair once, to not artificially inflate the counts?

Body:
You want to use count(distinct).  But that is not possible as a window function -- directly -- in SQL Server.  So use the dense_rank() trick:

SELECT BrowserName,
       (COUNT(DISTINCT UserId) * 100.0 /
        (DENSE_RANK() OVER (ORDER BY UserId ASC) +
         DENSE_RANK() OVER (ORDER BY UserId DESC)
        )
       ) as pct,
      COUNT(DISTINCT UserId) as ct
FROM AccessLog
GROUP BY BrowserName


问:
Calling fetch() on multiple URLs using Promise.all
I am attempting to fetch JSON data on multiple URLs. The URL is a single fixed string with unique keys concatenated at the end. These keys are supplied as an array which I'm iterating over using map(). The resulting data is passed into Promise.all(), but undefined is returned. I can't for the life of me figure out why?

```<code>export const fetchApiEvents = async eventIds => {
    try {
        const events = await Promise.all(eventIds.map(id => {
            fetch('http://api_url/events/' + id)
                .then(res => res.json())
        }))
        return events
    } catch (e) {
        console.log('An error occured fetching the events: ', e)
    }
}
</code>```

Then I'm calling this function as an effect:

```<code>    useEffect(() => {
        fetchApiEvents(eventIds)
            .then(response => setEvents(response))
    }, [eventIds])
</code>```

Am I doing something really stupid?

答:
return is missing in line 4:

```<code>export const fetchApiEvents = async eventIds => {
    try {
        const events = await Promise.all(eventIds.map(id => {
            return fetch('http://api_url/events/' + id)
                .then(res => res.json())
        }))
        return events
    } catch (e) {
        console.log('An error occured fetching the events: ', e)
    }
}
</code>```

Body:
I am attempting to fetch JSON data on multiple URLs. The URL is a single fixed string with unique keys concatenated at the end. These keys are supplied as an array which I'm iterating over using map(). The resulting data is passed into Promise.all(), but undefined is returned. I can't for the life of me figure out why?

export const fetchApiEvents = async eventIds => {
    try {
        const events = await Promise.all(eventIds.map(id => {
            fetch('http://api_url/events/' + id)
                .then(res => res.json())
        }))
        return events
    } catch (e) {
        console.log('An error occured fetching the events: ', e)
    }
}

Then I'm calling this function as an effect:

    useEffect(() => {
        fetchApiEvents(eventIds)
            .then(response => setEvents(response))
    }, [eventIds])

Am I doing something really stupid?

Body:
return is missing in line 4:

export const fetchApiEvents = async eventIds => {
    try {
        const events = await Promise.all(eventIds.map(id => {
            return fetch('http://api_url/events/' + id)
                .then(res => res.json())
        }))
        return events
    } catch (e) {
        console.log('An error occured fetching the events: ', e)
    }
}


问:
Python import error: "encondings" on debian 10
So I'm running debian 10, and using python 3.7 (which I built from source). For some reason I can no longer use the CLI interpreter, and whenever I try to execute anything that relies on Python, it returns the following error:

```<code>Fatal Python error: initfsencoding: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f41b0784740 (most recent call first):
Aborted
</code>```

However, when I run the exact same command (either for the interpreter or when running a different python application) using sudo, it works perfectly fine. It feels like the supporting python 3.7 modules are not accessible  by the current user. But I'm not sure how to proceed in order to fix it.

答:
You need to setup locale

For standard UTF-8 en_US you can do:

```<code>echo 'LC_ALL="en_US.UTF-8"' >> /etc/environment
echo 'export LANGUAGE="en_US.UTF-8"' >> /etc/environment
echo 'export LC_CTYPE="en_US.UTF-8"' >> /etc/environment
echo 'export LANG="en_US.UTF-8"' >> /etc/environment
source /etc/environment
</code>```

Body:
So I'm running debian 10, and using python 3.7 (which I built from source). For some reason I can no longer use the CLI interpreter, and whenever I try to execute anything that relies on Python, it returns the following error:

Fatal Python error: initfsencoding: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f41b0784740 (most recent call first):
Aborted

However, when I run the exact same command (either for the interpreter or when running a different python application) using sudo, it works perfectly fine. It feels like the supporting python 3.7 modules are not accessible  by the current user. But I'm not sure how to proceed in order to fix it.

Body:
You need to setup locale

For standard UTF-8 en_US you can do:

echo 'LC_ALL="en_US.UTF-8"' >> /etc/environment
echo 'export LANGUAGE="en_US.UTF-8"' >> /etc/environment
echo 'export LC_CTYPE="en_US.UTF-8"' >> /etc/environment
echo 'export LANG="en_US.UTF-8"' >> /etc/environment
source /etc/environment


问:
How to escape double quotes in JSON
I'm trying to show double quotes but it shows one of the backslashes:

```<code>"maingame": {
    "day1": {
        "text1": "Tag 1",
        "text2": "Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
    }
}
</code>```

When rendering in the html it shows as \"Example text\". What is the correct way?

答:
For those who would like to use developer powershell. Here are the lines to add to your settings.json:</p>

```<code>"terminal.integrated.automationShell.windows": "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe",
"terminal.integrated.shellArgs.windows": [
    "-noe",
    "-c",
    " &{Import-Module 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\Common7\\Tools\\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell b7c50c8d} ",
    ],
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to escape double quotes in JSON

Body:
I'm trying to show double quotes but it shows one of the backslashes:

"maingame": {
    "day1": {
        "text1": "Tag 1",
        "text2": "Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir. "
    }
}

When rendering in the html it shows as \"Example text\". What is the correct way?

Body:
For those who would like to use developer powershell. Here are the lines to add to your settings.json:

"terminal.integrated.automationShell.windows": "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe",
"terminal.integrated.shellArgs.windows": [
    "-noe",
    "-c",
    " &{Import-Module 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\Common7\\Tools\\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell b7c50c8d} ",
    ],


问:
Is there a way to read datavalues from a sheet into an array at index 1 rather than 0?
I know this sounds trivial, but I am mapping data from one sheet to another, and it would make the human side MUCH easier if the index numbers matched the column numbers in the sheet.  The column mapping gets confusing enough without having to decrement indices by 1. Thx.</p>

答:
Try this:</p>

```<code>function useColumnNumberForIndexingArray() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName("name");
  const vs=sh.getDataRange().getValues();//if first row is headers
  let hA=vs.shift();
  let colname=[];
  hA.forEach(function(h,i)(colname[h]=i
  let col={};
  for(var i=0;i<sh.getLastColumn();i++) {
    col[i+1]=i;
  }
  vs.forEach(function(r,i){
    var valueofcolumn1=r[col[1]];//or colname['columnA Name']
    var valueofcolumn2=r[col[2]];//or colname['columnB Name']
  });
}
</code>```

Body:
Try this:

function useColumnNumberForIndexingArray() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName("name");
  const vs=sh.getDataRange().getValues();//if first row is headers
  let hA=vs.shift();
  let colname=[];
  hA.forEach(function(h,i)(colname[h]=i
  let col={};
  for(var i=0;i<sh.getLastColumn();i++) {
    col[i+1]=i;
  }
  vs.forEach(function(r,i){
    var valueofcolumn1=r[col[1]];//or colname['columnA Name']
    var valueofcolumn2=r[col[2]];//or colname['columnB Name']
  });
}


问:
Set different variables to the same Variable result [Discord.py, Google Sheet API]
What i am trying to do it's cell_find to look for specific member's logged bans in my Google sheet API and after that, It'll display it in an Discord Embed, but the problem basically is when the bot send the embed it only shows one result instead of the 3 ones that should display

```<code>cell_find = sheet.findall('Banned')
var = 0
for cell in cell_find:
    var += 1
    sheet_username = sheet.cell(cell.row,3).value
    sheet_reason = sheet.cell(cell.row,7).value
    if var == 4:
        break
</code>```

The embed i'd like to try would be something like

```<code>embed = discord.Embed(title=f'{sheet_username}'s Incidents')
embed.addfield(name="Incident#1", value=f'{sheet_reason}')
embed.addfield(name="Incident#2", value=f'{sheet_reason}')
embed.addfield(name="Incident#3", value=f'{sheet_reason}')
await ctx.send(embed = embed)
</code>```

答:
You could try iterating over it in a for loop:

sheet_username = sheet.cell(cell.row,3).value
embed = discord.Embed(title=f"{sheet_username}'s Incidents")

for count, cell in enumerate(cell_find, 1):
    sheet_reason = sheet.cell(cell.row,7).value
    embed.add_field(name=f"Incident#{count}", value=f"{sheet_reason}")

await ctx.send(embed=embed)
```

Without knowing how your google sheet is laid out, I'm not able to help on the columns, but you could use the count variable to add to the column perhaps? Something like 3 + count?

But I think as far as logic goes, this is the way to go about adding fields.

References:

Enumerating in Python

Body:
What i am trying to do it's cell_find to look for specific member's logged bans in my Google sheet API and after that, It'll display it in an Discord Embed, but the problem basically is when the bot send the embed it only shows one result instead of the 3 ones that should display

cell_find = sheet.findall('Banned')
var = 0
for cell in cell_find:
    var += 1
    sheet_username = sheet.cell(cell.row,3).value
    sheet_reason = sheet.cell(cell.row,7).value
    if var == 4:
        break

The embed i'd like to try would be something like

embed = discord.Embed(title=f'{sheet_username}'s Incidents')
embed.addfield(name="Incident#1", value=f'{sheet_reason}')
embed.addfield(name="Incident#2", value=f'{sheet_reason}')
embed.addfield(name="Incident#3", value=f'{sheet_reason}')
await ctx.send(embed = embed)

Body:
You could try iterating over it in a for loop:

sheet_username = sheet.cell(cell.row,3).value
embed = discord.Embed(title=f"{sheet_username}'s Incidents")

for count, cell in enumerate(cell_find, 1):
    sheet_reason = sheet.cell(cell.row,7).value
    embed.add_field(name=f"Incident#{count}", value=f"{sheet_reason}")

await ctx.send(embed=embed)

Without knowing how your google sheet is laid out, I'm not able to help on the columns, but you could use the count variable to add to the column perhaps? Something like 3 + count?

But I think as far as logic goes, this is the way to go about adding fields.

References:

Enumerating in Python


问:
Return generated HTML from controller and bind it to template
I have a table that can display different content in tds depending on some input. For instance, I could have a button, div, img, custom component, etc. Since there is a lot of different data that can be inside the td, I created a method that would generate the proper HTML and return it. However, I cannot seem to find a way to bind it to my template.

Here is my HTML generating method:

```<code>getComponentForType(type: string): any {
    return this._sanitizer.sanitize(SecurityContext.HTML,`<span> hello world</span>`);
}
</code>```

This method would return more complex HTML, but I am just testing with a simple span for the moment.

Here is my template:

```<code><table>
    <tbody>
        <tr *ngFor="let row of data; let rowIndex = index">
            <td *ngFor="let column of columns; let colIndex = index" [attr.safeHtml]="getComponentForType(columns[colIndex].type)">
            </td>
        </tr>
    </tbody>
</table>

</code>```

Now, I tried many things to set the HTML. I tried using the safeHTML, innerHTML, ng-bind-html directives and many more, yet my HTML never seems to render. This is what Chrome renders this as:

How can I manage to add a nested HTML element inside the td from my method that generates HTML?

答:
You didn't post your data so I wrote some dummy tags as the columns of the HTML elements.

Edit:
return this._sanitizer.sanitize(SecurityContext.HTML, type); will clear styles from the element, remove buttons tags and functionality until the value is safe to use if this is the case just replace [attr.safeHtml]="getComponentForType(columns[colIndex].type)" with  [innerHTML]="getComponentForType(column)".

if you do want buttons with click events and\or inline styles then you should use:

this._sanitizer.bypassSecurityTrustHtml(type) and [innerHTML]="getComponentForType(column)", check out the docs for this topic in https://angular.io/api/platform-browser/DomSanitizer#bypasssecuritytrusthtml.

Warning: If this section in your system will be written to the database by one user and will be rendered to another user then you need to avoid the use of this solution and consider changing your requirements for this part of your system.

From the docs:

WARNING: calling this method with untrusted user data exposes your
  application to XSS security risks!

```<code>import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
    selector: 'app-dangerous-table',
    templateUrl: './dangerous-table.component.html',
    styleUrls: ['./dangerous-table.component.css']
})
export class DangerousTableComponent implements OnInit {

    data = ['row1', 'row2', 'row3'];

    columns = [
        '<span style="color: red;"> Hello XSS </span>',
        '<button onclick="alert(document.domain)">click me</button>',
        '<img src onerror="console.log(JSON.stringify(localStorage))"/>'
    ]

    constructor(private _sanitizer: DomSanitizer) { }

    ngOnInit() {
    }

    getComponentForType(type: string): any {
        return this._sanitizer.bypassSecurityTrustHtml(type);
    }
}
</code>```

and your view:

```<code><table>
    <tbody>
        <tr *ngFor="let row of data">
            <td
                *ngFor="let column of columns"
                [innerHTML]="getComponentForType(column)"
            >
            </td>
        </tr>
    </tbody>
</table>
</code>```

Body:
I have a table that can display different content in tds depending on some input. For instance, I could have a button, div, img, custom component, etc. Since there is a lot of different data that can be inside the td, I created a method that would generate the proper HTML and return it. However, I cannot seem to find a way to bind it to my template.

Here is my HTML generating method:

getComponentForType(type: string): any {
    return this._sanitizer.sanitize(SecurityContext.HTML,`<span> hello world</span>`);
}

This method would return more complex HTML, but I am just testing with a simple span for the moment.

Here is my template:

Now, I tried many things to set the HTML. I tried using the safeHTML, innerHTML, ng-bind-html directives and many more, yet my HTML never seems to render. This is what Chrome renders this as:

How can I manage to add a nested HTML element inside the td from my method that generates HTML?

Body:
You didn't post your data so I wrote some dummy tags as the columns of the HTML elements.

Edit:
return this._sanitizer.sanitize(SecurityContext.HTML, type); will clear styles from the element, remove buttons tags and functionality until the value is safe to use if this is the case just replace [attr.safeHtml]="getComponentForType(columns[colIndex].type)" with  [innerHTML]="getComponentForType(column)".

if you do want buttons with click events and\or inline styles then you should use:

this._sanitizer.bypassSecurityTrustHtml(type) and [innerHTML]="getComponentForType(column)", check out the docs for this topic in https://angular.io/api/platform-browser/DomSanitizer#bypasssecuritytrusthtml.

Warning: If this section in your system will be written to the database by one user and will be rendered to another user then you need to avoid the use of this solution and consider changing your requirements for this part of your system.

From the docs:

WARNING: calling this method with untrusted user data exposes your
  application to XSS security risks!

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
    selector: 'app-dangerous-table',
    templateUrl: './dangerous-table.component.html',
    styleUrls: ['./dangerous-table.component.css']
})
export class DangerousTableComponent implements OnInit {

    data = ['row1', 'row2', 'row3'];

    columns = [
        '<span style="color: red;"> Hello XSS </span>',
        '<button onclick="alert(document.domain)">click me</button>',
        '<img src onerror="console.log(JSON.stringify(localStorage))"/>'
    ]

    constructor(private _sanitizer: DomSanitizer) { }

    ngOnInit() {
    }

    getComponentForType(type: string): any {
        return this._sanitizer.bypassSecurityTrustHtml(type);
    }
}

and your view:

<table>
    <tbody>
        <tr *ngFor="let row of data">
            <td
                *ngFor="let column of columns"
                [innerHTML]="getComponentForType(column)"
            >
            </td>
        </tr>
    </tbody>
</table>


问:
How to get NSDate day, month and year in integer format?
I want to get the day, month and year components of NSDate in integer form i.e. if the date is 1/2/1988 then I should get 1, 2 and 1988 separately as an integer. How can I do this in iOS? I found the similar question but the method descriptionWithCalendarFormat: gives a warning and seems to be deprecated by now.

答:
You can use NSDateComponents to get this,</p>

```<code>NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currDate = [NSDate date];
NSDateComponents *dComp = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
                                      fromDate:currDate];

int day = [dComp day];
int month = [dComp month];
int year = [dComp year];
</code>```

Body:
You can use NSDateComponents to get this,

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currDate = [NSDate date];
NSDateComponents *dComp = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
                                      fromDate:currDate];

int day = [dComp day];
int month = [dComp month];
int year = [dComp year];


问:
Why does JsonConvert treat default constructors and parameterized constructors differently?
I was trying out Json.net's ability to serialize and deserialize dictionaries, and thanks to this post I was able to find a good solution to serializing dictionaries in a simple way.

It was working great, but in a certain circumstance it broke in a (to me) nonsensical way such that I couldn't help but spend the next three hours debugging.

Here is the problem. When serializing this class

```<code>public class ReferenceTesting
{
    public List<Scenario> scenarios = new List<Scenario>();
    private Dictionary<Scenario, float> _Dict = new Dictionary<Scenario, float>();
    [JsonProperty]
    public List<KeyValuePair<Scenario, float>> SerializedDict
    {
        get { return _Dict.ToList(); }
        set { _Dict = value.ToDictionary(x => x.Key, x => x.Value); }
    }
    public ReferenceTesting(int number = 0)
    {
        for (int i = 0; i < number; i++)
        {
            Scenario s1 = new Scenario();
            scenarios.Add(s1);
            _Dict.Add(s1, i);
        }
    }
    public override string ToString()
    {
        string s = "";
        for (int i = 0; i < scenarios.Count(); i++)
        {
            Scenario scenario = scenarios[i];
            s += $"scenario{i} \n";
        }
        foreach (KeyValuePair<Scenario, float> scenario in SerializedDict)
        {
            s += $"Key: {scenario.Key}, Value: {scenario.Value} \n";
        }
        return s;
    }
}
</code>```

Everything works as expected, meaning when I instantiate

```<code>new Reference(3);
</code>```

and then serialize and deserialize, I end up with an object with as expected 3 items in the list, and 3 items in the dictionary.

Output:

```<code>scenario0
scenario1
scenario2
Key: Scenario, Value: 0
Key: Scenario, Value: 1
Key: Scenario, Value: 2
</code>```

However, by adding the default constructor

```<code>public ReferenceTesting() { }
</code>```

the serialization works, writing out 3 items in list and dictionary, but deserialization does not work with the property. Meaning I end up with

```<code>scenario0
scenario1
scenario2
</code>```

as output.

The big surprise with this is that the two constructors do the exact same thing - which is nothing when number = 0 (which it is when Json.net creates it, I doublechecked). So this means that the serializer has to be doing something under the hood to treat the property differently if there is or is not a default constructor.

答:
How does Json.NET deserialize an object differently when it has a parameterized constructor vs. when it has a default constructor?

Json.NET is a streaming deserializer.  Whenever possible it deserializes as it streams through the JSON rather than preloading the complete JSON into an intermediate representation before final deserialization.

Thus, when deserializing a JSON object with a default constructor, it first constructs the corresponding .Net object.  It then recursively populates the object's .Net members by streaming through the key/value pairs in the JSON until the end of the JSON object.  For each pair encountered, it finds the corresponding .Net member.  If the value is a primitive type, it deserializes the primitive and sets the value.  But if the value is a complex type (JSON object or array) it constructs the child object if necessary, sets the value back in the parent, and then populates it recursively as it continues to stream.

However, when deserializing an object with a parameterized constructor, Json.NET cannot use this streaming algorithm and instead must first fully deserialize the JSON object to an intermediate table of deserialized .Net name/value pairs, matching each JSON value to its corresponding .Net constructor argument or property by name and then deserializing to the type declared in .Net.  Only then can the object be constructed by passing the deserialized constructor parameters into the constructor, and setting the remainder as property values.

For details on this process, see

JSON.net: how to deserialize without using the default constructor?

How does JSON deserialization in C# work.

(There is a third algorithm for ISerializable objects which does not apply in your case.)

Why is my surrogate public List<KeyValuePair<Scenario, float>> SerializedDict property not deserialized correctly when deserializing via a default constructor?

The reason is explained in this answer to Why are all the collections in my POCO are null when deserializing some valid json with the .NET Newtonsoft.Json component, and arises about of the specifics of Json.NET's Populate() algorithm:

It calls the getter in the parent class to get the current value of the property being deserialized.

If null, and unless a custom constructor is being used, it allocates an instance of the property's returned type (using the JsonContract.DefaultCreator method for the type).

It calls the setter in the parent to set the allocated instance back into the parent.

It proceeds to populate the instance of the type.

It does not set the instance back a second time, after it has been populated.

Thus the setter for SerializedDict is not called after the list is populated.

But when the parent class has a parameterized constructor, the property value SerializedDict is fully deserialized before its parent is constructed, so the setter is called with a fully populated surrogate list.

How can I create a surrogate collection property that works in both scenarios?

You can use an array instead of a list.  Since an array cannot be resized, it must be fully deserialized and populated before it can be set back in the parent object:

```<code>public class ReferenceTesting
{
    public KeyValuePair<Scenario, float> [] SerializedDict
    {
        get { return _Dict.ToArray(); }
        set { _Dict = value.ToDictionary(x => x.Key, x => x.Value);  }
    }
    // Remainder unchanged
</code>```

You could make the array property be private if you want, by marking it with [JsonProperty].

By the way, your current deserialization creates duplicate Scenario objects in the scenarios and _Dict collections as shown by demo fiddle #1 here.

One way to fix this would be to serialize just _Dict (assuming that all scenarios are in the dictionary).  Another would be to use PreserveReferencesHandling, e.g. by adding [JsonObject(IsReference = true)] to Scenario:

```<code>[JsonObject(IsReference = true)]
public class Scenario
{
    // Remainder unchanged
}
</code>```

Notes:

There is no standard for serialization of references in JSON.  Json.NET's implementation may not match that of other serializers.

PreserveReferencesHandling doesn't work for objects with parameterized constructors (see here for details), so make sure Scenario doesn't have one.

Demo fiddle #2 here showing everything working correctly with a default constructor, and #3 here with a parameterized constructor.

Body:
I was trying out Json.net's ability to serialize and deserialize dictionaries, and thanks to this post I was able to find a good solution to serializing dictionaries in a simple way.

It was working great, but in a certain circumstance it broke in a (to me) nonsensical way such that I couldn't help but spend the next three hours debugging.

Here is the problem. When serializing this class

public class ReferenceTesting
{
    public List<Scenario> scenarios = new List<Scenario>();
    private Dictionary<Scenario, float> _Dict = new Dictionary<Scenario, float>();
    [JsonProperty]
    public List<KeyValuePair<Scenario, float>> SerializedDict
    {
        get { return _Dict.ToList(); }
        set { _Dict = value.ToDictionary(x => x.Key, x => x.Value); }
    }
    public ReferenceTesting(int number = 0)
    {
        for (int i = 0; i < number; i++)
        {
            Scenario s1 = new Scenario();
            scenarios.Add(s1);
            _Dict.Add(s1, i);
        }
    }
    public override string ToString()
    {
        string s = "";
        for (int i = 0; i < scenarios.Count(); i++)
        {
            Scenario scenario = scenarios[i];
            s += $"scenario{i} \n";
        }
        foreach (KeyValuePair<Scenario, float> scenario in SerializedDict)
        {
            s += $"Key: {scenario.Key}, Value: {scenario.Value} \n";
        }
        return s;
    }
}

Everything works as expected, meaning when I instantiate

new Reference(3);

and then serialize and deserialize, I end up with an object with as expected 3 items in the list, and 3 items in the dictionary.

Output:

scenario0
scenario1
scenario2
Key: Scenario, Value: 0
Key: Scenario, Value: 1
Key: Scenario, Value: 2

However, by adding the default constructor

public ReferenceTesting() { }

the serialization works, writing out 3 items in list and dictionary, but deserialization does not work with the property. Meaning I end up with

scenario0
scenario1
scenario2

as output.

The big surprise with this is that the two constructors do the exact same thing - which is nothing when number = 0 (which it is when Json.net creates it, I doublechecked). So this means that the serializer has to be doing something under the hood to treat the property differently if there is or is not a default constructor.

Body:
How does Json.NET deserialize an object differently when it has a parameterized constructor vs. when it has a default constructor?

Json.NET is a streaming deserializer.  Whenever possible it deserializes as it streams through the JSON rather than preloading the complete JSON into an intermediate representation before final deserialization.

Thus, when deserializing a JSON object with a default constructor, it first constructs the corresponding .Net object.  It then recursively populates the object's .Net members by streaming through the key/value pairs in the JSON until the end of the JSON object.  For each pair encountered, it finds the corresponding .Net member.  If the value is a primitive type, it deserializes the primitive and sets the value.  But if the value is a complex type (JSON object or array) it constructs the child object if necessary, sets the value back in the parent, and then populates it recursively as it continues to stream.

However, when deserializing an object with a parameterized constructor, Json.NET cannot use this streaming algorithm and instead must first fully deserialize the JSON object to an intermediate table of deserialized .Net name/value pairs, matching each JSON value to its corresponding .Net constructor argument or property by name and then deserializing to the type declared in .Net.  Only then can the object be constructed by passing the deserialized constructor parameters into the constructor, and setting the remainder as property values.

For details on this process, see

JSON.net: how to deserialize without using the default constructor?

How does JSON deserialization in C# work.

(There is a third algorithm for ISerializable objects which does not apply in your case.)

Why is my surrogate public List<KeyValuePair<Scenario, float>> SerializedDict property not deserialized correctly when deserializing via a default constructor?

The reason is explained in this answer to Why are all the collections in my POCO are null when deserializing some valid json with the .NET Newtonsoft.Json component, and arises about of the specifics of Json.NET's Populate() algorithm:

It calls the getter in the parent class to get the current value of the property being deserialized.

If null, and unless a custom constructor is being used, it allocates an instance of the property's returned type (using the JsonContract.DefaultCreator method for the type).

It calls the setter in the parent to set the allocated instance back into the parent.

It proceeds to populate the instance of the type.

It does not set the instance back a second time, after it has been populated.

Thus the setter for SerializedDict is not called after the list is populated.

But when the parent class has a parameterized constructor, the property value SerializedDict is fully deserialized before its parent is constructed, so the setter is called with a fully populated surrogate list.

How can I create a surrogate collection property that works in both scenarios?

You can use an array instead of a list.  Since an array cannot be resized, it must be fully deserialized and populated before it can be set back in the parent object:

public class ReferenceTesting
{
    public KeyValuePair<Scenario, float> [] SerializedDict
    {
        get { return _Dict.ToArray(); }
        set { _Dict = value.ToDictionary(x => x.Key, x => x.Value);  }
    }
    // Remainder unchanged

You could make the array property be private if you want, by marking it with [JsonProperty].

By the way, your current deserialization creates duplicate Scenario objects in the scenarios and _Dict collections as shown by demo fiddle #1 here.

One way to fix this would be to serialize just _Dict (assuming that all scenarios are in the dictionary).  Another would be to use PreserveReferencesHandling, e.g. by adding [JsonObject(IsReference = true)] to Scenario:

[JsonObject(IsReference = true)]
public class Scenario
{
    // Remainder unchanged
}

Notes:

There is no standard for serialization of references in JSON.  Json.NET's implementation may not match that of other serializers.

PreserveReferencesHandling doesn't work for objects with parameterized constructors (see here for details), so make sure Scenario doesn't have one.

Demo fiddle #2 here showing everything working correctly with a default constructor, and #3 here with a parameterized constructor.


问:
Retrieve nested object into array in es6 or lodash
I am trying to extract nested objects of same keys into an array from array of objects.

Example:

There is an array as shown below:

```<code>[
 {
  id:1,
  model:'car',
  manufacturer:{
   id:1,
   name:'benz',
   year:2010
  }
 },
 {
  id:1,
  model:'car',
  manufacturer:{
   id:2,
   name:'benz',
   year:2012
  }
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]
</code>```

I need the result as shown below:

```<code>[
 {
   id:1,
   model:'car',
   manufacturer:[
    {
     id:1,
     name:'benz',
     year:2010
    },
    {
     id:2,
     name:'benz',
     year:2012
    }
   ]
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]
</code>```

How to achieve this? I tried all the possible ways using lodash but unable to get desired result. Please help me. Thank you.

答:
You can do with simple for loops</p>

```<code>for(let i=0;i<arr.length;i++)) {
// check required key matching
// append to new array
}
</code>```

Body:
I am trying to extract nested objects of same keys into an array from array of objects.

Example:

There is an array as shown below:

[
 {
  id:1,
  model:'car',
  manufacturer:{
   id:1,
   name:'benz',
   year:2010
  }
 },
 {
  id:1,
  model:'car',
  manufacturer:{
   id:2,
   name:'benz',
   year:2012
  }
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]

I need the result as shown below:

[
 {
   id:1,
   model:'car',
   manufacturer:[
    {
     id:1,
     name:'benz',
     year:2010
    },
    {
     id:2,
     name:'benz',
     year:2012
    }
   ]
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]

How to achieve this? I tried all the possible ways using lodash but unable to get desired result. Please help me. Thank you.

Body:
You can do with simple for loops

for(let i=0;i<arr.length;i++)) {
// check required key matching
// append to new array
}


问:
How to insert values into a table depending of the XML file attribute with xQuery in SQL Server?
I want to insert the first attributes of the XML always in the same table, but depending of the value of last the XML attributes I have to insert to another table.

I have in mind to something like this. But obviously it is wrong.

```<code>CREATE OR ALTER PROCEDURE [dbo].[spCargarDatosCC]
AS
BEGIN
SET NOCOUNT ON;

-- VARIABLES --
DECLARE @CCobro xml

BEGIN TRY
    SELECT @CCobro = CC
    FROM OPENROWSET (Bulk 'D:\Base de datos\FacturacionMunicipal_BD\Base de Datos\XML\Concepto_de_Cobro.xml', Single_BLOB) AS CCobro(CC)

    INSERT INTO CCobro (ID, Nombre, TasaInteresMoratorio, DiaEmisionRecibo, QDiasVencimiento, EsImpuesto, EsRecurrente, EsFijo, TipoCC, Activo)
    SELECT c.value('@id','INT') AS ID
        , c.value('@Nombre','VARCHAR(100)') AS Nombre
        , c.value('@TasaInteresMoratoria','DECIMAL(10,2)') AS TasaInteresMoratorio
        , c.value('@DiaCobro','TINYINT') AS DiaEmisionRecibo
        , c.value('@QDiasVencimiento','TINYINT') AS QDiasVencimiento
        , c.value('@EsImpuesto','VARCHAR(10)') AS EsImpuesto
        , c.value('@EsRecurrente','VARCHAR(10)') AS EsRecurrente
        , c.value('@EsFijo','VARCHAR(10)') AS EsFijo
        , c.value('@TipoCC','VARCHAR(10)') AS TipoCC
        , 1 AS Activo

        -- the code from above to here works as I want

        -- THIS PART IS WHAT I WANT TO INSERT CONDITIONALLY

        if(c.value('@Monto', 'MONEY') != NULL) then
            insert into CCobro_MontoFijo (ID, MontoFijo) --CCobro_MontoFijo is a table that references CCobro
            SELECT c.value('@id', 'INT') AS ID
            , c.value('@Monto', 'MONEY') AS MontoFijo
        if(c.value('@ValorM3', 'MONEY') != NULL) then
            insert into CCobro_ConsumoAgua(ID, ConsumoM3)  --CCobro_ConsumoAgua is a table that references CCobro
            SELECT c.value('@id', 'INT') AS ID
            , c.value('@ValorM3', 'MONEY') AS ConsumoM3
        if(c.value('@ValorPorcentaje', 'REAL') != NULL) then
            insert into CCobro_InteresMoratorio(ID, Valor_Porcentual) --CCobro_InteresMoratorio is a table that references CCobro
            SELECT c.value('@id', 'INT') AS ID
            , c.value('@ValorPorcentaje', 'REAL') AS Valor_Porcentual

    FROM @CCobro.nodes('/Conceptos_de_Cobro/conceptocobro') AS t(c);

END TRY

BEGIN CATCH
    return @@ERROR * -1
END CATCH

END
</code>```

XML File that I want to read. Notice that the last attributes sometimes are NULL, because they depends on TipoCC atributte.

```<code><Conceptos_de_Cobro>
    <conceptocobro id="1" Nombre="Agua" DiaCobro="25" QDiasVencimiento="4" EsImpuesto="No" EsRecurrente="Si" EsFijo="No" TasaInteresMoratoria="5.2" TipoCC="CC Consumo" Monto="" ValorM3="500" ValorPorcentaje="" />
    <conceptocobro id="2" Nombre="Patente Licores" DiaCobro="8" QDiasVencimiento="12" EsImpuesto="Si" EsRecurrente="No" EsFijo="No" TasaInteresMoratoria="2.6" TipoCC="CC Fijo" Monto="50000" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="3" Nombre="impuesto Propiedad" DiaCobro="8" QDiasVencimiento="12" EsImpuesto="Si" EsRecurrente="No" EsFijo="Si" TasaInteresMoratoria="1.5" TipoCC="CC Porcentual" Monto="" ValorM3="" ValorPorcentaje="0.25" />
    <conceptocobro id="4" Nombre="Recolectar Basura" DiaCobro="4" QDiasVencimiento="5" EsImpuesto="No" EsRecurrente="Si" EsFijo="Si" TasaInteresMoratoria="2.2" TipoCC="CC Fijo" Monto="3000" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="5" Nombre="Mantenimiento de Parques" DiaCobro="3" QDiasVencimiento="7" EsImpuesto="Si" EsRecurrente="Si" EsFijo="Si" TasaInteresMoratoria="0.87" TipoCC="CC Fijo" Monto="970" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="6" Nombre="Reconexion de Agua" DiaCobro="15" QDiasVencimiento="10" EsImpuesto="No" EsRecurrente="No" EsFijo="Si" TasaInteresMoratoria="3.8" TipoCC="CC Fijo" Monto="780" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="7" Nombre="Impuesto a la Renta" DiaCobro="5" QDiasVencimiento="15" EsImpuesto="Si" EsRecurrente="Si" EsFijo="No" TasaInteresMoratoria="12.6" TipoCC="CC Porcentual" Monto="" ValorM3="" ValorPorcentaje="0.15" />
    <conceptocobro id="8" Nombre="Mantenimiento de Parques" DiaCobro="7" QDiasVencimiento="6" EsImpuesto="No" EsRecurrente="Si" EsFijo="Si" TasaInteresMoratoria="0.32" TipoCC="CC Fijo" Monto="7850" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="9" Nombre="Aseo de sitios Publico" DiaCobro="1" QDiasVencimiento="10" EsImpuesto="No" EsRecurrente="Si" EsFijo="Si" TasaInteresMoratoria="7.8" TipoCC="CC Fijo" Monto="580" ValorM3="" ValorPorcentaje="" />
</Conceptos_de_Cobro>
</code>```

答:
Each INSERT statement into a different table should be SQL statement on its own.

For each if ... then statement you need to use the following approach.

The WHERE clause will take care of missing values after the conversion into MONEY data type inside the CTE.

SQL

```<code>;WITH rs AS
(
    SELECT c.value('@id','INT') AS ID
        , c.value('@Monto','MONEY') AS MontoFijo
    FROM @CCobro.nodes('/Conceptos_de_Cobro/conceptocobro') AS t(c)
)
INSERT INTO CCobro_MontoFijo (ID, MontoFijo)
SELECT ID, MontoFijo FROM rs
WHERE rs.Monto > 0;
</code>```

Body:
I want to insert the first attributes of the XML always in the same table, but depending of the value of last the XML attributes I have to insert to another table.

I have in mind to something like this. But obviously it is wrong.

CREATE OR ALTER PROCEDURE [dbo].[spCargarDatosCC]
AS
BEGIN
SET NOCOUNT ON;

-- VARIABLES --
DECLARE @CCobro xml

BEGIN TRY
    SELECT @CCobro = CC
    FROM OPENROWSET (Bulk 'D:\Base de datos\FacturacionMunicipal_BD\Base de Datos\XML\Concepto_de_Cobro.xml', Single_BLOB) AS CCobro(CC)

    INSERT INTO CCobro (ID, Nombre, TasaInteresMoratorio, DiaEmisionRecibo, QDiasVencimiento, EsImpuesto, EsRecurrente, EsFijo, TipoCC, Activo)
    SELECT c.value('@id','INT') AS ID
        , c.value('@Nombre','VARCHAR(100)') AS Nombre
        , c.value('@TasaInteresMoratoria','DECIMAL(10,2)') AS TasaInteresMoratorio
        , c.value('@DiaCobro','TINYINT') AS DiaEmisionRecibo
        , c.value('@QDiasVencimiento','TINYINT') AS QDiasVencimiento
        , c.value('@EsImpuesto','VARCHAR(10)') AS EsImpuesto
        , c.value('@EsRecurrente','VARCHAR(10)') AS EsRecurrente
        , c.value('@EsFijo','VARCHAR(10)') AS EsFijo
        , c.value('@TipoCC','VARCHAR(10)') AS TipoCC
        , 1 AS Activo

        -- the code from above to here works as I want

        -- THIS PART IS WHAT I WANT TO INSERT CONDITIONALLY

        if(c.value('@Monto', 'MONEY') != NULL) then
            insert into CCobro_MontoFijo (ID, MontoFijo) --CCobro_MontoFijo is a table that references CCobro
            SELECT c.value('@id', 'INT') AS ID
            , c.value('@Monto', 'MONEY') AS MontoFijo
        if(c.value('@ValorM3', 'MONEY') != NULL) then
            insert into CCobro_ConsumoAgua(ID, ConsumoM3)  --CCobro_ConsumoAgua is a table that references CCobro
            SELECT c.value('@id', 'INT') AS ID
            , c.value('@ValorM3', 'MONEY') AS ConsumoM3
        if(c.value('@ValorPorcentaje', 'REAL') != NULL) then
            insert into CCobro_InteresMoratorio(ID, Valor_Porcentual) --CCobro_InteresMoratorio is a table that references CCobro
            SELECT c.value('@id', 'INT') AS ID
            , c.value('@ValorPorcentaje', 'REAL') AS Valor_Porcentual

    FROM @CCobro.nodes('/Conceptos_de_Cobro/conceptocobro') AS t(c);

END TRY

BEGIN CATCH
    return @@ERROR * -1
END CATCH

END

XML File that I want to read. Notice that the last attributes sometimes are NULL, because they depends on TipoCC atributte.

<Conceptos_de_Cobro>
    <conceptocobro id="1" Nombre="Agua" DiaCobro="25" QDiasVencimiento="4" EsImpuesto="No" EsRecurrente="Si" EsFijo="No" TasaInteresMoratoria="5.2" TipoCC="CC Consumo" Monto="" ValorM3="500" ValorPorcentaje="" />
    <conceptocobro id="2" Nombre="Patente Licores" DiaCobro="8" QDiasVencimiento="12" EsImpuesto="Si" EsRecurrente="No" EsFijo="No" TasaInteresMoratoria="2.6" TipoCC="CC Fijo" Monto="50000" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="3" Nombre="impuesto Propiedad" DiaCobro="8" QDiasVencimiento="12" EsImpuesto="Si" EsRecurrente="No" EsFijo="Si" TasaInteresMoratoria="1.5" TipoCC="CC Porcentual" Monto="" ValorM3="" ValorPorcentaje="0.25" />
    <conceptocobro id="4" Nombre="Recolectar Basura" DiaCobro="4" QDiasVencimiento="5" EsImpuesto="No" EsRecurrente="Si" EsFijo="Si" TasaInteresMoratoria="2.2" TipoCC="CC Fijo" Monto="3000" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="5" Nombre="Mantenimiento de Parques" DiaCobro="3" QDiasVencimiento="7" EsImpuesto="Si" EsRecurrente="Si" EsFijo="Si" TasaInteresMoratoria="0.87" TipoCC="CC Fijo" Monto="970" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="6" Nombre="Reconexion de Agua" DiaCobro="15" QDiasVencimiento="10" EsImpuesto="No" EsRecurrente="No" EsFijo="Si" TasaInteresMoratoria="3.8" TipoCC="CC Fijo" Monto="780" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="7" Nombre="Impuesto a la Renta" DiaCobro="5" QDiasVencimiento="15" EsImpuesto="Si" EsRecurrente="Si" EsFijo="No" TasaInteresMoratoria="12.6" TipoCC="CC Porcentual" Monto="" ValorM3="" ValorPorcentaje="0.15" />
    <conceptocobro id="8" Nombre="Mantenimiento de Parques" DiaCobro="7" QDiasVencimiento="6" EsImpuesto="No" EsRecurrente="Si" EsFijo="Si" TasaInteresMoratoria="0.32" TipoCC="CC Fijo" Monto="7850" ValorM3="" ValorPorcentaje="" />
    <conceptocobro id="9" Nombre="Aseo de sitios Publico" DiaCobro="1" QDiasVencimiento="10" EsImpuesto="No" EsRecurrente="Si" EsFijo="Si" TasaInteresMoratoria="7.8" TipoCC="CC Fijo" Monto="580" ValorM3="" ValorPorcentaje="" />
</Conceptos_de_Cobro>

Body:
Each INSERT statement into a different table should be SQL statement on its own.

For each if ... then statement you need to use the following approach.

The WHERE clause will take care of missing values after the conversion into MONEY data type inside the CTE.

SQL

;WITH rs AS
(
    SELECT c.value('@id','INT') AS ID
        , c.value('@Monto','MONEY') AS MontoFijo
    FROM @CCobro.nodes('/Conceptos_de_Cobro/conceptocobro') AS t(c)
)
INSERT INTO CCobro_MontoFijo (ID, MontoFijo)
SELECT ID, MontoFijo FROM rs
WHERE rs.Monto > 0;


问:
Fiona accessing coordinates of multiple polygons in a shapefile
I am working on a shapefile that contains 4 polygons where I need to extract their coordinates in a tuple or numpy array for later manipulation. While fiona identifies the 4 polygons, using shapely to get the area only gives me the value for the first polygon.

I would like to pick the xy coordinate for all polygons and put them separately into arrays and tuples for processing. Any help would be appreciated.

```<code>import fiona
import pprint
from shapely.geometry import shape, Polygon

c = fiona.open("myShapeFile.shp", 'r')
pprint.pprint(len(c))
poly = Polygon(next(iter(c))["geometry"]["coordinates"][:])
print('Area  :: ',poly.area)
</code>```

The execution gives me the following:

4

Area     ::  483.6379565269977

Body:
I am working on a shapefile that contains 4 polygons where I need to extract their coordinates in a tuple or numpy array for later manipulation. While fiona identifies the 4 polygons, using shapely to get the area only gives me the value for the first polygon.

I would like to pick the xy coordinate for all polygons and put them separately into arrays and tuples for processing. Any help would be appreciated.

import fiona
import pprint
from shapely.geometry import shape, Polygon

c = fiona.open("myShapeFile.shp", 'r')
pprint.pprint(len(c))
poly = Polygon(next(iter(c))["geometry"]["coordinates"][:])
print('Area  :: ',poly.area)

The execution gives me the following:

4

Area     ::  483.6379565269977

Body:
Try this:

import fiona
import numpy as np

c = fiona.open('myShapeFile.shp')
coords = [np.array(poly['geometry']['coordinates'])
          for poly in c.values()]

coords is a 4 item list holding numpy arrays built from the coordinates of the polygons from the shapefile:

[array([[ 3.67739738e+05,  6.35697708e+06, -1.50000000e+03],
       [ 3.67709140e+05,  6.35875947e+06, -1.50000000e+03],
       [ 3.55633222e+05,  6.35932405e+06, -1.50000000e+03],
       [ 3.55340980e+05,  6.35724482e+06, -1.50000000e+03],
       [ 3.54012992e+05,  6.35713924e+06, -1.50000000e+03],
       [ 3.53169984e+05,  6.33306237e+06, -1.50000000e+03],
       [ 3.72936914e+05,  6.33219322e+06, -1.50000000e+03],
       [ 3.73638262e+05,  6.34799928e+06, -1.50000000e+03],
       [ 3.70536492e+05,  6.34865912e+06, -1.50000000e+03],
       [ 3.71030683e+05,  6.35672004e+06, -1.50000000e+03],
       [ 3.67739738e+05,  6.35697708e+06, -1.50000000e+03]]),
 array([[ 3.60619254e+05,  6.35486104e+06, -1.50000000e+03],
       [ 3.61702258e+05,  6.35460318e+06, -1.50000000e+03],
       [ 3.62578977e+05,  6.35362332e+06, -1.50000000e+03],
       [ 3.61805402e+05,  6.35192145e+06, -1.50000000e+03],
       [ 3.60412965e+05,  6.35114787e+06, -1.50000000e+03],
       [ 3.59072102e+05,  6.35171516e+06, -1.50000000e+03],
       [ 3.59020527e+05,  6.35279817e+06, -1.50000000e+03],
       [ 3.60309824e+05,  6.35295288e+06, -1.50000000e+03],
       [ 3.60000391e+05,  6.35408746e+06, -1.50000000e+03],
       [ 3.60619254e+05,  6.35486104e+06, -1.50000000e+03]]),
 array([[ 3.59072102e+05,  6.34439198e+06, -1.50000000e+03],
       [ 3.60928684e+05,  6.34537184e+06, -1.50000000e+03],
       [ 3.62424262e+05,  6.34480455e+06, -1.50000000e+03],
       [ 3.63868270e+05,  6.34361841e+06, -1.50000000e+03],
       [ 3.63146266e+05,  6.34155554e+06, -1.50000000e+03],
       [ 3.61341258e+05,  6.34036939e+06, -1.50000000e+03],
       [ 3.60258250e+05,  6.34109139e+06, -1.50000000e+03],
       [ 3.61650688e+05,  6.34227754e+06, -1.50000000e+03],
       [ 3.61289688e+05,  6.34356684e+06, -1.50000000e+03],
       [ 3.59897250e+05,  6.34294798e+06, -1.50000000e+03],
       [ 3.57989094e+05,  6.34346370e+06, -1.50000000e+03],
       [ 3.59072102e+05,  6.34439198e+06, -1.50000000e+03]]),
 array([[ 3.69489590e+05,  6.34294798e+06, -1.50000000e+03],
       [ 3.71397742e+05,  6.34103982e+06, -1.50000000e+03],
       [ 3.69438016e+05,  6.33928638e+06, -1.50000000e+03],
       [ 3.67581438e+05,  6.34052411e+06, -1.50000000e+03],
       [ 3.67787723e+05,  6.34222597e+06, -1.50000000e+03],
       [ 3.69489590e+05,  6.34294798e+06, -1.50000000e+03]])]


问:
Intellisense for PHP in Coda
I was wondering if there is a plugin or feature in Coda to have intellisense for you own-defined php functions, while coding?</p>

答: I don't think there is one that will highlight custom functions -- in any language. It doesn't have the capabilities that Dreamweaver does with regards to code prediction. Maybe that's a version 2.0 feature. If there is a plugin, I've never seen it but that's not saying much!  :)</p>

Title: Intellisense for PHP in Coda


问:
How to dismiss pushed ViewController after logout?
I spent so many hours with this issue, so I can't find any solution.

I open SettingsViewController from my TopBar on tap in avatar with pushViewController method (here is problem) and from menu (not modal).

I want to dismiss this pushed ViewController when I tap on logout button.

Below is a function that I use in some VC's and works very well.

```<code>func goToSettingsView() {
    let vc = SettingsViewController(nibName: "SettingsViewController", bundle: nil)
    vc.modalPresentationStyle = .fullScreen
    self.navigationController!.pushViewController(vc, animated: true)
    for constraint in vc.view.constraints {
        if constraint.identifier == "alignTopHeader" {
           constraint.constant = 0
        }
    }
}
</code>```

When I clicked logout button isn't working and when I login from (LoginViewController) this SettingsViewController is still showing, but I would go to Main Screen without any modals.

I did some ideas but not good working yet.

First idea was:

Below is my logout IBaction in my SettingsViewController:

```<code>- (void)logout {
    [self dismissViewControllerAnimated:YES completion:nil];
    [[UserManager shared] logoutUserWithSuccessBlock:^{
        [self presentLoginViewController];
    }];
}
</code>```

LoginViewController is dismiss, but self is targeted for SettingsViewController?

Second idea:

I added a function declared in AppDelegate "backToRoot" in LoginViewController and call from viewWillDisappear.

```<code>[appDelegate backToRoot];
</code>```

function in AppDelegate.m file

```<code>-(void)backToRoot {
   [self.navigationController dismissViewControllerAnimated:YES completion:nil];
   PresentationsPickerViewController *mainvc = [[PresentationsPickerViewController alloc] init];
   [self setCenterPanelWithViewController:mainvc];
}
</code>```

But still not working with modal, it's work fine when SettingsViewController isn't modal.

Do you have any ideas how to hide/dismiss pushed SettingsViewController in logout action?

答:
I want to dismiss this pushed ViewController when I tap on logout button.

Now you don't dismiss a pushed UIViewController. Push is a navigation style associated with a UINavigationController. When you push a UIViewController you need to pop it.

When we talk about dismiss, we usually mean closing a UIViewController that is presented modally. This method means that a new UIViewController is added on top of your previously shown UIViewController or any class inheriting from it. This does not get added onto the navigation stack. You can only dismiss a UIViewController if it was presented.

Now your first code block shows you pushing the SettingsViewController and your first solution tries to dismiss it. This will not work. You need to pop it from the UINavigationController to close it.

Next,

LoginViewController is dismiss, but self is targeted for SettingsViewController?

The method [self dismiss]... will close the screen that is the latest presented screen on top. If you present LoginViewController from settings, then LoginViewController screen gets dismissed.

Also,

But still not working with modal, it's work fine when SettingsViewController isn't modal. Do you have any ideas how to hide/dismiss pushed SettingsViewController in logout action?

If your SettingsViewController is presented then you need to dismiss it and if it is pushed, you need to pop it.

If there are situations when both the actions can occur, then on your close button action, you can check how the screen was displayed. Use this link to figure out the checks for that.

If all you want to do is go to your LoginViewController on logging out, you can just change the root window of your application.

```<code>let window = (UIApplication.shared.delegate as? AppDelegate)?.window
window?.rootViewController = viewController //this will be your loginViewController
window?.makeKeyAndVisible()
</code>```

For iOS 13:

```<code>UIApplication.shared.windows.first?.rootViewController = LoginViewController
UIApplication.shared.windows.first?.makeKeyAndVisible()
</code>```

Body:
I spent so many hours with this issue, so I can't find any solution.

I open SettingsViewController from my TopBar on tap in avatar with pushViewController method (here is problem) and from menu (not modal).

I want to dismiss this pushed ViewController when I tap on logout button.

Below is a function that I use in some VC's and works very well.

func goToSettingsView() {
    let vc = SettingsViewController(nibName: "SettingsViewController", bundle: nil)
    vc.modalPresentationStyle = .fullScreen
    self.navigationController!.pushViewController(vc, animated: true)
    for constraint in vc.view.constraints {
        if constraint.identifier == "alignTopHeader" {
           constraint.constant = 0
        }
    }
}

When I clicked logout button isn't working and when I login from (LoginViewController) this SettingsViewController is still showing, but I would go to Main Screen without any modals.

I did some ideas but not good working yet.

First idea was:

Below is my logout IBaction in my SettingsViewController:

- (void)logout {
    [self dismissViewControllerAnimated:YES completion:nil];
    [[UserManager shared] logoutUserWithSuccessBlock:^{
        [self presentLoginViewController];
    }];
}

LoginViewController is dismiss, but self is targeted for SettingsViewController?

Second idea:

I added a function declared in AppDelegate "backToRoot" in LoginViewController and call from viewWillDisappear.

[appDelegate backToRoot];

function in AppDelegate.m file

-(void)backToRoot {
   [self.navigationController dismissViewControllerAnimated:YES completion:nil];
   PresentationsPickerViewController *mainvc = [[PresentationsPickerViewController alloc] init];
   [self setCenterPanelWithViewController:mainvc];
}

But still not working with modal, it's work fine when SettingsViewController isn't modal.

Do you have any ideas how to hide/dismiss pushed SettingsViewController in logout action?

Body:
I want to dismiss this pushed ViewController when I tap on logout button.

Now you don't dismiss a pushed UIViewController. Push is a navigation style associated with a UINavigationController. When you push a UIViewController you need to pop it.

When we talk about dismiss, we usually mean closing a UIViewController that is presented modally. This method means that a new UIViewController is added on top of your previously shown UIViewController or any class inheriting from it. This does not get added onto the navigation stack. You can only dismiss a UIViewController if it was presented.

Now your first code block shows you pushing the SettingsViewController and your first solution tries to dismiss it. This will not work. You need to pop it from the UINavigationController to close it.

Next,

LoginViewController is dismiss, but self is targeted for SettingsViewController?

The method [self dismiss]... will close the screen that is the latest presented screen on top. If you present LoginViewController from settings, then LoginViewController screen gets dismissed.

Also,

But still not working with modal, it's work fine when SettingsViewController isn't modal. Do you have any ideas how to hide/dismiss pushed SettingsViewController in logout action?

If your SettingsViewController is presented then you need to dismiss it and if it is pushed, you need to pop it.

If there are situations when both the actions can occur, then on your close button action, you can check how the screen was displayed. Use this link to figure out the checks for that.

If all you want to do is go to your LoginViewController on logging out, you can just change the root window of your application.

let window = (UIApplication.shared.delegate as? AppDelegate)?.window
window?.rootViewController = viewController //this will be your loginViewController
window?.makeKeyAndVisible()

For iOS 13:

UIApplication.shared.windows.first?.rootViewController = LoginViewController
UIApplication.shared.windows.first?.makeKeyAndVisible()


问:
Jest - Mocking ES6 classes doesn't work for me
I'm following the documentation almost in detail (with some simple file and directory structure changes). Using the example offered by Jest to make 'manual mocks' in 'Es6 Class Mocks', I have the following files structure:

```<code>MyProjectExampleDirectory
│   sound-player-consumer.js
│
├───libs
│       sound-player.js
│
├───__mocks__
│       sound-player.js
│
└───__tests__
        sound-player-consumer.test.js
</code>```

My script to test is as follows:

// sound-player-consumer.js
import SoundPlayer from './libs/sound-player';

export default class SoundPlayerConsumer {
  constructor() {
    this.soundPlayer = new SoundPlayer();
  }

  playSomethingCool() {
    const coolSoundFileName = 'song.mp3';
    this.soundPlayer.playSoundFile(coolSoundFileName);
  }
}

```

<p>I am mocking the following way:</p>

<pre class="lang-js prettyprint-override"><code>// __mocks__/sound-player.js
export const mockPlaySoundFile = jest.fn();

const mock = jest.fn().mockImplementation(() => {
  return { playSoundFile: mockPlaySoundFile };
});

export default mock;

</code>```

and my test is the following:

// __tests__/sound-player-consumer.test.js
import SoundPlayer, { mockPlaySoundFile } from '../libs/sound-player';
import SoundPlayerConsumer from './../sound-player-consumer';

jest.mock('../libs/sound-player');

beforeEach(() => {
  // Clear all instances and calls to constructor and all methods:
  SoundPlayer.mockClear();
  mockPlaySoundFile.mockClear();
});

it('We can check if the consumer called the class constructor', () => {
  const soundPlayerConsumer = new SoundPlayerConsumer();
  expect(SoundPlayer).toHaveBeenCalledTimes(1);
});

```

I'm getting de following error:

What am I doing wrong?

答:
I have managed to resolve the issue, however I am unable to get it to work in the __mocks__ directory:

const mockPlaySoundFile = jest.fn();
jest.mock('../libs/sound-player', () => {
  return jest.fn().mockImplementation(() => {
    return { playSoundFile: mockPlaySoundFile };
  });
});
```

The code above must be placed before any other code structure, after imports

Body:
I'm following the documentation almost in detail (with some simple file and directory structure changes). Using the example offered by Jest to make 'manual mocks' in 'Es6 Class Mocks', I have the following files structure:

MyProjectExampleDirectory
│   sound-player-consumer.js
│
├───libs
│       sound-player.js
│
├───__mocks__
│       sound-player.js
│
└───__tests__
        sound-player-consumer.test.js

My script to test is as follows:

// sound-player-consumer.js
import SoundPlayer from './libs/sound-player';

export default class SoundPlayerConsumer {
  constructor() {
    this.soundPlayer = new SoundPlayer();
  }

  playSomethingCool() {
    const coolSoundFileName = 'song.mp3';
    this.soundPlayer.playSoundFile(coolSoundFileName);
  }
}

I am mocking the following way:

// __mocks__/sound-player.js
export const mockPlaySoundFile = jest.fn();

const mock = jest.fn().mockImplementation(() => {
  return { playSoundFile: mockPlaySoundFile };
});

export default mock;

and my test is the following:

// __tests__/sound-player-consumer.test.js
import SoundPlayer, { mockPlaySoundFile } from '../libs/sound-player';
import SoundPlayerConsumer from './../sound-player-consumer';

jest.mock('../libs/sound-player');

beforeEach(() => {
  // Clear all instances and calls to constructor and all methods:
  SoundPlayer.mockClear();
  mockPlaySoundFile.mockClear();
});

it('We can check if the consumer called the class constructor', () => {
  const soundPlayerConsumer = new SoundPlayerConsumer();
  expect(SoundPlayer).toHaveBeenCalledTimes(1);
});

I'm getting de following error:

What am I doing wrong?

Body:
I have managed to resolve the issue, however I am unable to get it to work in the __mocks__ directory:

const mockPlaySoundFile = jest.fn();
jest.mock('../libs/sound-player', () => {
  return jest.fn().mockImplementation(() => {
    return { playSoundFile: mockPlaySoundFile };
  });
});

The code above must be placed before any other code structure, after imports


问:
How to print with getch() in one line?
I have a problem in python3 .I want to print the "#" in only one line when I push "a" button in keyboard ,but with this code when I push for example 10 times the "a" ,doesn't appear the "#" ,but when I push the "q" button ,all "#" appears.
Why is this happening?
Also,in print function it shows me wrong the -> end=" "
Code:</p>

```<code>import getch

while True:
    char = getch.getch()
    if(char == 'a'):
        print('#', end=" ")
    elif(char == "q"):
        break
</code>```

答:
For Python 3, print can take an optional flush argument where the stream is forcibly flushed.</p>

```<code> print('#', sep=' ', end='', flush=True)
</code>```

Title: How to print with getch() in one line?

Body:
I have a problem in python3 .I want to print the "#" in only one line when I push "a" button in keyboard ,but with this code when I push for example 10 times the "a" ,doesn't appear the "#" ,but when I push the "q" button ,all "#" appears.
Why is this happening?
Also,in print function it shows me wrong the -> end=" "
Code:

import getch

while True:
    char = getch.getch()
    if(char == 'a'):
        print('#', end=" ")
    elif(char == "q"):
        break

Body:
For Python 3, print can take an optional flush argument where the stream is forcibly flushed.

 print('#', sep=' ', end='', flush=True)


问:
.NET Core 3.1 Not available in as Target Framework in VS2019 v16.6
I have downloaded and installed VS2019 Community v16.6.0
I have downloaded and installed .NET Core 3.1 (v3.1.4) with SDK version v3.1.300

.NET Core 3.1 is not available as an option for a target framework in Visual Studio. Am I missing something here?

I've followed several suggestions in other similar questions of enabling preview SDKs (which shouldn't apply, because 3.1 is not in preview) with no success.

Images Attached

答: v16.6.1 of VS2019 just dropped today. Fixed the issue.</p>


问:
Handle French Characters in Java
I Have a Page where I search for a term and it is displaying perfect. Whatever character type it is.

Now when I have few checkboxes in JSP and I check it and submit. In these checkboxes I have one box name like ABC Farmacéutica Corporation.

When I click on submit button, I am calling a function and will set all parameters to a form and will submit that form. (I tested putting alert for the special character display before submit and it is displaying good).

Now, coming to the Java end, I use Springs Frame work. When I print the term in controller, then it is displayed like ABC FarmacÃ©utica Corporation.

Please help...
Thanks in advance.

EDIT :

Please try this sample Example

```<code>import java.net.*;
class sample{
    public static void main(String[] args){
        try{
            String aaa = "ABC Farmacéutica Corporation";
            String bbb = "ABC FarmacÃ©utica Corporation";

            aaa = URLEncoder.encode(aaa, "UTF-8");
            bbb = URLDecoder.decode(bbb, "UTF-8");

            System.out.println("aaa   "+aaa);
            System.out.println("bbb   "+bbb);

        }catch(Exception e){
            System.out.println(e);
        }
    }
}
</code>```

I am getting output as,

```<code>aaa   PiSA+Farmac%C3%A9utica+Mexicana+Corporativo
bbb   PiSA Farmac├⌐utica Mexicana Corporativo
</code>```

Try to print the string aaa as it is.

答:
As I understand it, the text is hardcoded in controller code like this:

```<code>    ModelAndView mav = new ModelAndView("hello");
    mav.addObject("message", "ABC Farmacéutica Corporation");
    return mav;
</code>```

I expect this would work:

```<code>    ModelAndView mav = new ModelAndView("hello");
    mav.addObject("message", "ABC Farmac\u00e9utica Corporation");
    return mav;
</code>```

If so, the problem is due to a mismatch between the character encoding your Java editor is using and the encoding your compiler uses to read the source code.

For example, if your editor saves the Java file as UTF-8 and you compile on a system where UTF-8 is not the default encoding, then you would need to tell your compiler to use that encoding:

```<code>javac -cp foo.jar -encoding UTF-8 Bar.java
</code>```

Your build scripts and IDE settings need to be consistent when handling character data.

If your text editor saved your file as UTF-8 then, in a hex editor, é would be the byte sequence C3 A9; in many other encodings, it would have the value E9. ISO-8859-1 and  windows-1252 would encode Ã© as C3 A9. You can read about character encoding in Java source files here.

Title: Handle French Characters in Java

Body:
I Have a Page where I search for a term and it is displaying perfect. Whatever character type it is.

Now when I have few checkboxes in JSP and I check it and submit. In these checkboxes I have one box name like ABC Farmacéutica Corporation.

When I click on submit button, I am calling a function and will set all parameters to a form and will submit that form. (I tested putting alert for the special character display before submit and it is displaying good).

Now, coming to the Java end, I use Springs Frame work. When I print the term in controller, then it is displayed like ABC FarmacÃ©utica Corporation.

Please help...
Thanks in advance.

EDIT :

Please try this sample Example

import java.net.*;
class sample{
    public static void main(String[] args){
        try{
            String aaa = "ABC Farmacéutica Corporation";
            String bbb = "ABC FarmacÃ©utica Corporation";

            aaa = URLEncoder.encode(aaa, "UTF-8");
            bbb = URLDecoder.decode(bbb, "UTF-8");

            System.out.println("aaa   "+aaa);
            System.out.println("bbb   "+bbb);

        }catch(Exception e){
            System.out.println(e);
        }
    }
}

I am getting output as,

aaa   PiSA+Farmac%C3%A9utica+Mexicana+Corporativo
bbb   PiSA Farmac├⌐utica Mexicana Corporativo

Try to print the string aaa as it is.

Body:
As I understand it, the text is hardcoded in controller code like this:

    ModelAndView mav = new ModelAndView("hello");
    mav.addObject("message", "ABC Farmacéutica Corporation");
    return mav;

I expect this would work:

    ModelAndView mav = new ModelAndView("hello");
    mav.addObject("message", "ABC Farmac\u00e9utica Corporation");
    return mav;

If so, the problem is due to a mismatch between the character encoding your Java editor is using and the encoding your compiler uses to read the source code.

For example, if your editor saves the Java file as UTF-8 and you compile on a system where UTF-8 is not the default encoding, then you would need to tell your compiler to use that encoding:

javac -cp foo.jar -encoding UTF-8 Bar.java

Your build scripts and IDE settings need to be consistent when handling character data.

If your text editor saved your file as UTF-8 then, in a hex editor, é would be the byte sequence C3 A9; in many other encodings, it would have the value E9. ISO-8859-1 and  windows-1252 would encode Ã© as C3 A9. You can read about character encoding in Java source files here.


问:
Better way to write the following code in Kotlin?
I've this following function, which maps ids to a list of Strings

```<code>private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String>>  {
    var id = 4

    return resourcesList.map { resource ->
        id++
        id to resource
    }
}
</code>```

The id starts from 5 as you can see here. I can make this code look cleaner if id started from 0. Just like this

```<code>private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String> = resourcesList.mapIndexed { index, resource ->
    index to resource
}
</code>```

Is there some Kotlin function to achieve the first result without the use of var id. Maybe some function whose index starts at 5?

答:
You can use zip function and int-range:</p>

```<code>    private fun doIdMapping(resourcesList: List<String>, startIndex: Int = 5)
         = (startIndex..startIndex + resourcesList.size).zip(resourcesList)
</code>```

Body:
I've this following function, which maps ids to a list of Strings

private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String>>  {
    var id = 4

    return resourcesList.map { resource ->
        id++
        id to resource
    }
}

The id starts from 5 as you can see here. I can make this code look cleaner if id started from 0. Just like this

private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String> = resourcesList.mapIndexed { index, resource ->
    index to resource
}

Is there some Kotlin function to achieve the first result without the use of var id. Maybe some function whose index starts at 5?

Body:
You can use zip function and int-range:

    private fun doIdMapping(resourcesList: List<String>, startIndex: Int = 5)
         = (startIndex..startIndex + resourcesList.size).zip(resourcesList)


问:
Canceling Google Sign In cause an exception in Flutter
I am trying to implement Google Sign In in my android flutter app, but I have this problem:

When user cancel Google sign in (tap on back button) this exception is throw.

PlatformException (PlatformException(sign_in_canceled, com.google.android.gms.common.api.ApiException: 12501: , null))

I found that from some newer version this should be fixed and it should return null instead of an exception. Currently I am using google_sign_in: ^4.1.1

I tried to wrap my code inside try-catch block or using .catchError() on the method, but nothing help.

My code looks like this:

```<code>  Future googleSign(BuildContext context) async {
    final GoogleSignInAccount googleSignInAccount =
        await googleSignIn.signIn().catchError((onError) => print(onError));

    final GoogleSignInAuthentication googleSignInAuthentication =
        await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );

    final AuthResult authResult = await _auth.signInWithCredential(credential);

    return authResult.user.uid;
  }
</code>```

Do you have any idea, how to handle this exception?
Thanks.

答:
The issue seems to be caused by an inability of the Dart VM to correctly detect exceptions that are caught with catchError() as explained in this StackOverflow question

There doesn't seem to be a perfect fix to this bug. However, I came across a somewhat good workaround on Github.

It requires you to edit package:flutter/src/services/platform_channel.dart.

You would have to wrap this

```<code>final Map<dynamic, dynamic> result = await invokeMethod<Map<dynamic, dynamic>>(method, arguments);
return result?.cast<K, V>();
</code>```

with a try/catch block as follows  (found at the beginning of invokeMapMethod)

```<code>try {
    final Map<dynamic, dynamic> result = await invokeMethod<Map<dynamic, dynamic>>(method, arguments);
    return result?.cast<K, V>();
} on PlatformException catch (err) { // Checks for type PlatformException
    if (err.code == 'sign_in_canceled') { // Checks for sign_in_canceled exception
        print(err.toString());
    } else {
        throw err; // Throws PlatformException again because it wasn't the one we wanted
    }
}
</code>```

You might also want to check if googleSignInAccount is null in which case, you should return return null to prevent further exceptions like NoSuchMethodError: The getter 'authentication' was called on null

So, your code can be re-written as

...

```<code>final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn().catchError((onError) => print(onError));

// Return null to prevent further exceptions if googleSignInAccount is null
if (googleSignInAccount == null) return null;

final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
</code>```

...

I hope this is easy to follow and it actually works for you.

Body:
I am trying to implement Google Sign In in my android flutter app, but I have this problem:

When user cancel Google sign in (tap on back button) this exception is throw.

PlatformException (PlatformException(sign_in_canceled, com.google.android.gms.common.api.ApiException: 12501: , null))

I found that from some newer version this should be fixed and it should return null instead of an exception. Currently I am using google_sign_in: ^4.1.1

I tried to wrap my code inside try-catch block or using .catchError() on the method, but nothing help.

My code looks like this:

  Future googleSign(BuildContext context) async {
    final GoogleSignInAccount googleSignInAccount =
        await googleSignIn.signIn().catchError((onError) => print(onError));

    final GoogleSignInAuthentication googleSignInAuthentication =
        await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );

    final AuthResult authResult = await _auth.signInWithCredential(credential);

    return authResult.user.uid;
  }

Do you have any idea, how to handle this exception?
Thanks.

Body:
The issue seems to be caused by an inability of the Dart VM to correctly detect exceptions that are caught with catchError() as explained in this StackOverflow question

There doesn't seem to be a perfect fix to this bug. However, I came across a somewhat good workaround on Github.

It requires you to edit package:flutter/src/services/platform_channel.dart.

You would have to wrap this

final Map<dynamic, dynamic> result = await invokeMethod<Map<dynamic, dynamic>>(method, arguments);
return result?.cast<K, V>();

with a try/catch block as follows  (found at the beginning of invokeMapMethod)

try {
    final Map<dynamic, dynamic> result = await invokeMethod<Map<dynamic, dynamic>>(method, arguments);
    return result?.cast<K, V>();
} on PlatformException catch (err) { // Checks for type PlatformException
    if (err.code == 'sign_in_canceled') { // Checks for sign_in_canceled exception
        print(err.toString());
    } else {
        throw err; // Throws PlatformException again because it wasn't the one we wanted
    }
}

You might also want to check if googleSignInAccount is null in which case, you should return return null to prevent further exceptions like NoSuchMethodError: The getter 'authentication' was called on null

So, your code can be re-written as

...

final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn().catchError((onError) => print(onError));

// Return null to prevent further exceptions if googleSignInAccount is null
if (googleSignInAccount == null) return null;

final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;

...

I hope this is easy to follow and it actually works for you.


Title: Looping through a list of tuples and removing them

Body:
Im having some difficulty understanding why my loop is not deleting invalid dates from a list of date tuples in the format of dd/mm/yyyy . heres what i have so far :

dates = [('12','10','1987'),('13','09','2010'), ('34','02','2002'), ('02','15','2005'),('37','10','2016'),('39','11','2001')]
print(dates)

for date in dates :
    day = int(date[0])
    month = int(date[1])
    year = int(date[2])

    if day > 31 :
        dates.remove(date)

    if month > 12 :
        dates.remove(date)

print(dates)

and heres the result :

[('12', '10', '1987'), ('13', '09', '2010'), ('34', '02', '2002'), ('02', '15', '2005'), ('37', '10', '2016'), ('39', '11', '2001')]

[('12', '10', '1987'), ('13', '09', '2010'), ('02', '15', '2005'), ('39', '11', '2001')]

I'm a total beginner and any help would be much appreciated.

Body:
You can easily accomplish that with this list comprehension:

dates = [('12','10','1987'),('13','09','2010'), ('34','02','2002'), ('02','15','2005'),('37','10','2016'),('39','11','2001')]
dates = [date for date in dates if int(date[1]) < 12 and int(date[0]) < 31]
print(dates)

Output:

[('12', '10', '1987'), ('13', '09', '2010')]


问:
Firefox Addon Publishing API
Does Firefox provide access to do the following programmatically?

Upload Firefox addon package/files

Update/modify addon package

Get analytics on extension (installs, uninstalls, etc.)

Delete/remove addon package

答: Found out that at the time of this post, Firefox does not have an API to post addons to their marketplace per their documentation here:  https://extensionworkshop.com/documentation/develop/getting-started-with-web-ext/</p>

Title: Firefox Addon Publishing API


问:
All tests get terminated in Intellij with Spring Boot and JUnit5
I was trying to write a simple test in my Spring boot app with JUnit5 and I notice that all of my tests get instanly terminated. I downloaded some unit testing example and it worked just fine so I don't know what is wrong with my set up.

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringDemoApplication.class, args);
    }

}

</code>```

Here's my example test that gets terminated:

```<code>import org.junit.jupiter.api.Test;

class DemoClassTest {

    @Test
    void testOne() {

    }
}
</code>```

And here's my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringDemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>14</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.2.0</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <version>2.23.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

</code>```

Image from Intellij

答:
You should remove junit-jupiter-engine and mockito-junit-jupiter dependencies as it is already included by spring-boot-starter-test which let SpringBoot handle incompatible versions issue between dependencies for you.

You might also want to remove the junit-vintage-engine exclusion to allow both Junit5 and Junit4 test execution

Body:
I was trying to write a simple test in my Spring boot app with JUnit5 and I notice that all of my tests get instanly terminated. I downloaded some unit testing example and it worked just fine so I don't know what is wrong with my set up.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringDemoApplication.class, args);
    }

}

Here's my example test that gets terminated:

import org.junit.jupiter.api.Test;

class DemoClassTest {

    @Test
    void testOne() {

    }
}

And here's my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringDemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>14</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.2.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <version>2.23.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Image from Intellij


问:
How to save output in python to .txt file
So basically i bought a book that teaches the basics of python and how to create a random number generator so I decided to go one step further and make a random password generator I found a tutorial online that gave me a good example of why and what is used to make a password generator but i want the output to be saved to a .txt file I do not know what i need to implement to get the result i want this is what i have i'm using python3.

```<code>import random

chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, @,#$%^&*.'

number = input('Number of passwords - ')
number = int(number)

length = input('password length? - ')
length = int(length)

answer = input

for P in range(number):
    password = ''
for C in range(length):
    password += random.choice(chars)
    print(password)

password = open("passlist.txt", "a")
password.write(password)
password.close()

file = open('passlist', 'w')
file.write(password)
file.close()
</code>```

this is what i get in shell

```<code> Traceback (most recent call last):
      File "C:\User\Desktop\passgen.py", line 21, in <module>
        password.write(password)
    TypeError: write() argument must be str, not _io.TextIOWrapper
</code>```

答:
The error originates from password being re-assigned in password = open("passlist.txt", "a"). This causes and error in the next line as you are attempting to pass password as parameter to itself in password.write(password).

Some farther assistance

You have the right idea but you forgot to indent. All the lines below for P in range(number): should be indented because the program must generate and write a new password until it has satisfied the required amount of passwords.

The password = open("passlist.txt", "a")
password.write(password)
password.close() lines are unnecessary as you are overriding the generated password and assigning that password variable to something that is not a string; that is why you are getting that error.

Here is the code with the adjustments.

```<code>import random

chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, @,#$%^&*.'

number = input('Number of passwords - ')
number = int(number)

length = input('password length? - ')
length = int(length)

answer = input

for P in range(number):
    password = ''
    for C in range(length):
        password += random.choice(chars)

    print(password)
    password += "\n" # writes the password in a new line

    file = open('passlist.tx', "a")
    file.write(password)
    file.close()

</code>```

Body:
So basically i bought a book that teaches the basics of python and how to create a random number generator so I decided to go one step further and make a random password generator I found a tutorial online that gave me a good example of why and what is used to make a password generator but i want the output to be saved to a .txt file I do not know what i need to implement to get the result i want this is what i have i'm using python3.

import random

chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, @,#$%^&*.'

number = input('Number of passwords - ')
number = int(number)

length = input('password length? - ')
length = int(length)

answer = input

for P in range(number):
    password = ''
for C in range(length):
    password += random.choice(chars)
    print(password)

password = open("passlist.txt", "a")
password.write(password)
password.close()

file = open('passlist', 'w')
file.write(password)
file.close()

this is what i get in shell

 Traceback (most recent call last):
      File "C:\User\Desktop\passgen.py", line 21, in <module>
        password.write(password)
    TypeError: write() argument must be str, not _io.TextIOWrapper

Body:
The error originates from password being re-assigned in password = open("passlist.txt", "a"). This causes and error in the next line as you are attempting to pass password as parameter to itself in password.write(password).

Some farther assistance

You have the right idea but you forgot to indent. All the lines below for P in range(number): should be indented because the program must generate and write a new password until it has satisfied the required amount of passwords.

The password = open("passlist.txt", "a")
password.write(password)
password.close() lines are unnecessary as you are overriding the generated password and assigning that password variable to something that is not a string; that is why you are getting that error.

Here is the code with the adjustments.

import random

chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, @,#$%^&*.'

number = input('Number of passwords - ')
number = int(number)

length = input('password length? - ')
length = int(length)

answer = input

for P in range(number):
    password = ''
    for C in range(length):
        password += random.choice(chars)

    print(password)
    password += "\n" # writes the password in a new line

    file = open('passlist.tx', "a")
    file.write(password)
    file.close()