问:
How to show new Mat-Progress Button on Button click
I have a mat-table which displays list of Jobs.I have created a function to stop and re-run the Jobs.
Whenever the user clicks on re-run a mat-progress bar is displayed that the Job is executing and the user can kill the Job by pressing the Stop Button.
However I would like to display individual mat-progress bar for each running job.

Stackblitz Link Here

How can i do that?
HTML Code:

```<code><div class="main-content">
<ng-container *ngIf="displayProgBar">
    <mat-toolbar>
        <mat-progress-bar
            mode="indeterminate"
            class="mat-progress-bar"
            color="primary"
        >
        </mat-progress-bar>

        <button
            mat-icon-button
            (click)="stop_exec_job2()"
            matTooltip="Stop Executing the Job"
        >
            <!-- Edit icon for row -->
            <i class="material-icons" style="color:red"> stop </i>
        </button>
    </mat-toolbar>
</ng-container>
<div class="card">
    <div class="card-header">
        <h5 class="title">Job Execution Stats</h5>
    </div>

    <mat-table [dataSource]="jobExecutionStat">
        <!-- Id Column -->
        <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
            <mat-cell *matCellDef="let element">{{ element.id }} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="exec_date">
            <mat-header-cell *matHeaderCellDef>
                Execution Date
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.exec_date }}
            </mat-cell>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="curr_time_period">
            <mat-header-cell *matHeaderCellDef>
                Current Time Period
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.curr_time_period }}
            </mat-cell>
        </ng-container>

        <!-- Symbol Column -->
        <ng-container matColumnDef="prev_time_period">
            <mat-header-cell *matHeaderCellDef>
                Previous Time Period
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.prev_time_period }}
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="status">
            <mat-header-cell *matHeaderCellDef> Status </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.status }}
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="actions">
            <mat-header-cell *matHeaderCellDef> </mat-header-cell>
            <mat-cell *matCellDef="let element; let index = index">
                <button
                    mat-icon-button
                    (click)="stop_exec_job(element)"
                    matTooltip="Stop Executing the Job"
                    [disabled]="element.status == 'Completed'"
                >
                    <!-- Edit icon for row -->
                    <i class="material-icons" style="color:red"> stop </i>
                </button>
                <!-- Delete icon for row -->
                <button
                    mat-icon-button
                    (click)="re_run_job(element)"
                    matTooltip="Re-Run the Job"
                    [disabled]="
                        element.status == 'Running' ||
                        element.status == 'Pending'
                    "
                >
                    <i class="material-icons" style="color:green">
                        cached
                    </i>
                </button>
            </mat-cell>
        </ng-container>

        <mat-header-row
            *matHeaderRowDef="jobExecStatDisplayedColumns"
        ></mat-header-row>
        <mat-row
            *matRowDef="
                let row;
                columns: jobExecStatDisplayedColumns;
                let element
            "
            (click)="showProgressBar(element)"
        >
        </mat-row>
    </mat-table>
</div>
</code>```

Typescript Code:

```<code>import { Component, OnInit, ɵConsole } from "@angular/core";
import { MatTableDataSource } from "@angular/material";
import { GlobalAppSateService } from "../../services/globalAppSate.service";
import { DataService } from "../../services/data.service";
import { SnakBarComponent } from "../custom-components/snak-bar/snak-
bar.component";

@Component({
selector: "app-job-execution-screen",
templateUrl: "./job-execution-screen.component.html",
styleUrls: ["./job-execution-screen.component.scss"]
})
export class JobExecutionScreenComponent implements OnInit {
displayProgBar:boolean = false;

jobExecStatDisplayedColumns = [
    "id",
    "exec_date",
    "prev_time_period",
    "curr_time_period",
    "status",
    "actions"
];
public selectedElem : any;

jobExecutionStat = new MatTableDataSource<Element>(ELEMENT_DATA);
constructor(
    private dataService: DataService,
    public globalAppSateService: GlobalAppSateService,
    private snakbar: SnakBarComponent
) {}
ngOnInit() {
    const project = JSON.parse(this.dataService.getObject("project"));
    if (project != null) {
        this.globalAppSateService.onMessage(project);
    }
}

stop_exec_job(element) {
    if(element.status == 'Running' || element.status == 'Pending') {
        this.displayProgBar = false;
        this.snakbar.statusBar('Job Execution Stopped','Sucess');
        element.status = 'Completed';
    }
}

stop_exec_job2(){
    this.stop_exec_job(this.selectedElem);
    this.displayProgBar = false;

}

re_run_job(element) {
    if(element.status == 'Completed') {
        this.snakbar.statusBar('Job Execution Started','Sucess');
        element.status = 'Running' ;
    }
}
showProgressBar(element) {
    this.selectedElem = element;
    if(element.status == 'Running' || element.status == 'Pending'){
        this.displayProgBar = true
    }

}
}
const ELEMENT_DATA: Element[] = [
{
    id: 1,
    exec_date: "17-01-2016",
    prev_time_period: "2016-04,2016-05,2016-06",
    curr_time_period: "2016-08",
    status: "Completed"
},
{
    id: 2,
    exec_date: "17-01-2017",
    prev_time_period: "2017-04,2017-05,2017-06",
    curr_time_period: "2017-08",
    status: "Running"
},
{
    id: 3,
    exec_date: "27-07-2017",
    prev_time_period: "2017-45,2017-46,2017-47",
    curr_time_period: "2018-01,2018-02",
    status: "Pending"
},
{
    id: 4,
    exec_date: "17-10-2018",
    prev_time_period: "2017-30,2017-31,2017-32",
    curr_time_period: "2018-01,2018-02",
    status: "Completed"
},
{
    id: 5,
    exec_date: "21-01-2018",
    prev_time_period: "2016-01,2016-02,2016-03,2016-04",
    curr_time_period: "2016-52",
    status: "Pending"
},
{
    id: 6,
    exec_date: "17-01-2018",
    prev_time_period: "2017-31,2017-32,2017-33,2017-34",
    curr_time_period: "2017-52",
    status: "Running"
}
];
export interface Element {
id: number;
exec_date: string;
prev_time_period: string;
curr_time_period: string;
status: string;
}
</code>```

答:
I know this is a year old, but i came across this when searching for something else. And thought of fixing this. I used the same stackblitz url app and modified it now.

Working app: https://angular-material-progressbar-autocomplete-bavr9a.stackblitz.io

code: https://stackblitz.com/edit/angular-material-progressbar-autocomplete-bavr9a

In summary: it was all simple to use the Material components and no need to create additional classes and logics. All changes are done at the html and i removed few unnecessary typescript logic methods.

Body:
I have a mat-table which displays list of Jobs.I have created a function to stop and re-run the Jobs.
Whenever the user clicks on re-run a mat-progress bar is displayed that the Job is executing and the user can kill the Job by pressing the Stop Button.
However I would like to display individual mat-progress bar for each running job.

Stackblitz Link Here

How can i do that?
HTML Code:

<ng-container *ngIf="displayProgBar">
    <mat-toolbar>
        <mat-progress-bar
            mode="indeterminate"
            class="mat-progress-bar"
            color="primary"
        >
        </mat-progress-bar>

        <button
            mat-icon-button
            (click)="stop_exec_job2()"
            matTooltip="Stop Executing the Job"
        >

             stop
        </button>
    </mat-toolbar>
</ng-container>

Job Execution Stats

    <mat-table [dataSource]="jobExecutionStat">

        <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
            <mat-cell *matCellDef="let element">{{ element.id }} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="exec_date">
            <mat-header-cell *matHeaderCellDef>
                Execution Date
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.exec_date }}
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="curr_time_period">
            <mat-header-cell *matHeaderCellDef>
                Current Time Period
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.curr_time_period }}
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="prev_time_period">
            <mat-header-cell *matHeaderCellDef>
                Previous Time Period
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.prev_time_period }}
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="status">
            <mat-header-cell *matHeaderCellDef> Status </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.status }}
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="actions">
            <mat-header-cell *matHeaderCellDef> </mat-header-cell>
            <mat-cell *matCellDef="let element; let index = index">
                <button
                    mat-icon-button
                    (click)="stop_exec_job(element)"
                    matTooltip="Stop Executing the Job"
                    [disabled]="element.status == 'Completed'"
                >

                     stop
                </button>

                <button
                    mat-icon-button
                    (click)="re_run_job(element)"
                    matTooltip="Re-Run the Job"
                    [disabled]="
                        element.status == 'Running' ||
                        element.status == 'Pending'
                    "
                >

                        cached

                </button>
            </mat-cell>
        </ng-container>

        <mat-header-row
            *matHeaderRowDef="jobExecStatDisplayedColumns"
        ></mat-header-row>
        <mat-row
            *matRowDef="
                let row;
                columns: jobExecStatDisplayedColumns;
                let element
            "
            (click)="showProgressBar(element)"
        >
        </mat-row>
    </mat-table>

Typescript Code:

import { Component, OnInit, ɵConsole } from "@angular/core";
import { MatTableDataSource } from "@angular/material";
import { GlobalAppSateService } from "../../services/globalAppSate.service";
import { DataService } from "../../services/data.service";
import { SnakBarComponent } from "../custom-components/snak-bar/snak-
bar.component";

@Component({
selector: "app-job-execution-screen",
templateUrl: "./job-execution-screen.component.html",
styleUrls: ["./job-execution-screen.component.scss"]
})
export class JobExecutionScreenComponent implements OnInit {
displayProgBar:boolean = false;

jobExecStatDisplayedColumns = [
    "id",
    "exec_date",
    "prev_time_period",
    "curr_time_period",
    "status",
    "actions"
];
public selectedElem : any;

jobExecutionStat = new MatTableDataSource<Element>(ELEMENT_DATA);
constructor(
    private dataService: DataService,
    public globalAppSateService: GlobalAppSateService,
    private snakbar: SnakBarComponent
) {}
ngOnInit() {
    const project = JSON.parse(this.dataService.getObject("project"));
    if (project != null) {
        this.globalAppSateService.onMessage(project);
    }
}

stop_exec_job(element) {
    if(element.status == 'Running' || element.status == 'Pending') {
        this.displayProgBar = false;
        this.snakbar.statusBar('Job Execution Stopped','Sucess');
        element.status = 'Completed';
    }
}

stop_exec_job2(){
    this.stop_exec_job(this.selectedElem);
    this.displayProgBar = false;

}

re_run_job(element) {
    if(element.status == 'Completed') {
        this.snakbar.statusBar('Job Execution Started','Sucess');
        element.status = 'Running' ;
    }
}
showProgressBar(element) {
    this.selectedElem = element;
    if(element.status == 'Running' || element.status == 'Pending'){
        this.displayProgBar = true
    }

}
}
const ELEMENT_DATA: Element[] = [
{
    id: 1,
    exec_date: "17-01-2016",
    prev_time_period: "2016-04,2016-05,2016-06",
    curr_time_period: "2016-08",
    status: "Completed"
},
{
    id: 2,
    exec_date: "17-01-2017",
    prev_time_period: "2017-04,2017-05,2017-06",
    curr_time_period: "2017-08",
    status: "Running"
},
{
    id: 3,
    exec_date: "27-07-2017",
    prev_time_period: "2017-45,2017-46,2017-47",
    curr_time_period: "2018-01,2018-02",
    status: "Pending"
},
{
    id: 4,
    exec_date: "17-10-2018",
    prev_time_period: "2017-30,2017-31,2017-32",
    curr_time_period: "2018-01,2018-02",
    status: "Completed"
},
{
    id: 5,
    exec_date: "21-01-2018",
    prev_time_period: "2016-01,2016-02,2016-03,2016-04",
    curr_time_period: "2016-52",
    status: "Pending"
},
{
    id: 6,
    exec_date: "17-01-2018",
    prev_time_period: "2017-31,2017-32,2017-33,2017-34",
    curr_time_period: "2017-52",
    status: "Running"
}
];
export interface Element {
id: number;
exec_date: string;
prev_time_period: string;
curr_time_period: string;
status: string;
}


来源: stackexchange

问:
Why doesn't EOF (ctrl+d) execute in function code? And only ctrl+z
I have some code below that works fine but only exits out when I do ctrl+z on Linux but not ctrl+d (EOF)? Does it have something to do with ncurses? What should I use instead (ERR?) and why?

```<code>
#include <stdio.h>
#include <ncurses.h>
#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = -1;
         }
    }

    // to close curses terminal
    endwin();
}
</code>```

Thank you.

答:
When you type Ctrl-z, the program didn't exit, only stays in background. You can see it with jobs command. You can exit the program with Ctrl-d by this code :

```<code>#include <stdio.h>
#include <ncurses.h>
#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != 4; i++)
    {
        if  (i == (MAXLINE-1)) {
            printf("\r\n");
            i = -1;
        }
    }

    // to close curses terminal
    endwin();
}
</code>```

The change is in [(c = getch()) != 4]. The code for Ctrl-d is 4.

ContentLicense: CC BY-SA 4.0

Body:
I have some code below that works fine but only exits out when I do ctrl+z on Linux but not ctrl+d (EOF)? Does it have something to do with ncurses? What should I use instead (ERR?) and why?

#include <stdio.h>
#include <ncurses.h>
#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = -1;
         }
    }

    // to close curses terminal
    endwin();
}

Thank you.

Body:
When you type Ctrl-z, the program didn't exit, only stays in background. You can see it with jobs command. You can exit the program with Ctrl-d by this code :

#include <stdio.h>
#include <ncurses.h>
#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != 4; i++)
    {
        if  (i == (MAXLINE-1)) {
            printf("\r\n");
            i = -1;
        }
    }

    // to close curses terminal
    endwin();
}

The change is in [(c = getch()) != 4]. The code for Ctrl-d is 4.


问:
My eclipse luna won't start up
So this basically this happens either when:
-I install the e(fx)clipse plugin into eclipse and then restart eclipse
-I copy the eclipse folder onto a network and put the folder on another computer to use the eclipse.

Currently I am facing the second one. Can you guys teach me how to read an eclipse log file? Also, please tell me on what I have to do with this.

My remedy is always get the base eclipse luna zip and then plug in for e(fx)clipse. Then hope that on my next start up it won't die on me.

LOG FILE

```<code>org.osgi.framework.BundleException: Unable to acquire the state change lock for the module: osgi.identity; osgi.identity="org.eclipse.core.runtime"; type="osgi.bundle"; version:Version="3.10.0.v20140318-2214"; singleton:="true" [id=51] STARTED!SESSION 2014-09-01 11:27:12.399 -----------------------------------------------
eclipse.buildId=4.4.0.I20140606-1215
java.version=1.8.0_20
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US
Framework arguments:  -product org.eclipse.epp.package.standard.product
Command-line arguments:  -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.standard.product

!ENTRY org.eclipse.equinox.ds 2 0 2014-09-01 11:28:13.706
!MESSAGE [SCR - WorkThread] Timeout occurred! Thread was blocked on processing [QueuedJob] WorkPerformer: org.eclipse.equinox.internal.ds.SCRManager@ccdee4; actionType 1

!ENTRY org.eclipse.equinox.ds 2 0 2014-09-01 11:28:14.096
!MESSAGE [SCR] Enabling components of bundle org.eclipse.ui.trace did not complete in 30000 ms

!ENTRY org.eclipse.fx.ide.java6 4 0 2014-09-01 11:28:14.221
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Could not resolve module: org.eclipse.fx.ide.java6 [296]
  Unresolved requirement: Require-Capability: osgi.ee; filter:="(&(osgi.ee=JavaSE)(version>=1.3)(!(version>=1.8)))"

    at org.eclipse.osgi.container.Module.start(Module.java:434)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1561)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1476)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)

!ENTRY org.eclipse.core.runtime 4 0 2014-09-01 11:28:19.274
!MESSAGE FrameworkEvent ERROR
!STACK 0 [STARTED]
    at org.eclipse.osgi.container.Module.lockStateChange(Module.java:329)
    at org.eclipse.osgi.container.Module.start(Module.java:389)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1562)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1476)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
</code>```

答:
backup on a zip all your files from this folder

delete the files
the folder is
\MyEclipse 2017 CI\configuration\org.eclipse.osgi.manager

restart myeclipse

ContentLicense: CC BY-SA 3.0

Title: My eclipse luna won't start up

Body:
So this basically this happens either when:
-I install the e(fx)clipse plugin into eclipse and then restart eclipse
-I copy the eclipse folder onto a network and put the folder on another computer to use the eclipse.

Currently I am facing the second one. Can you guys teach me how to read an eclipse log file? Also, please tell me on what I have to do with this.

My remedy is always get the base eclipse luna zip and then plug in for e(fx)clipse. Then hope that on my next start up it won't die on me.

LOG FILE

org.osgi.framework.BundleException: Unable to acquire the state change lock for the module: osgi.identity; osgi.identity="org.eclipse.core.runtime"; type="osgi.bundle"; version:Version="3.10.0.v20140318-2214"; singleton:="true" [id=51] STARTED!SESSION 2014-09-01 11:27:12.399 -----------------------------------------------
eclipse.buildId=4.4.0.I20140606-1215
java.version=1.8.0_20
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US
Framework arguments:  -product org.eclipse.epp.package.standard.product
Command-line arguments:  -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.standard.product

!ENTRY org.eclipse.equinox.ds 2 0 2014-09-01 11:28:13.706
!MESSAGE [SCR - WorkThread] Timeout occurred! Thread was blocked on processing [QueuedJob] WorkPerformer: org.eclipse.equinox.internal.ds.SCRManager@ccdee4; actionType 1

!ENTRY org.eclipse.equinox.ds 2 0 2014-09-01 11:28:14.096
!MESSAGE [SCR] Enabling components of bundle org.eclipse.ui.trace did not complete in 30000 ms

!ENTRY org.eclipse.fx.ide.java6 4 0 2014-09-01 11:28:14.221
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Could not resolve module: org.eclipse.fx.ide.java6 [296]
  Unresolved requirement: Require-Capability: osgi.ee; filter:="(&(osgi.ee=JavaSE)(version>=1.3)(!(version>=1.8)))"

    at org.eclipse.osgi.container.Module.start(Module.java:434)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1561)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1476)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)

!ENTRY org.eclipse.core.runtime 4 0 2014-09-01 11:28:19.274
!MESSAGE FrameworkEvent ERROR
!STACK 0 [STARTED]
    at org.eclipse.osgi.container.Module.lockStateChange(Module.java:329)
    at org.eclipse.osgi.container.Module.start(Module.java:389)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1582)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1562)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1533)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1476)
    at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)


问:
How do I disable a UIButton?
I am working on a project in which I have to show all photos of Photo Library in a plist and show them horizontally on UIButtons.

My app will also have an edit button: when the user clicks this button, a delete mark (such as usually appears in other iPhone/iPad apps) should show on each button.

But here's the crucial bit: as soon as this delete mark appears, the functionality of the button should be disabled. I've tried accomplishing this with the following:

```<code>{
  editbutton.enabled=NO;
}
</code>```

...but it neither produces an error nor works. What should I do?

答:
Please set this...

```<code> editButton.userInteractionEnabled = NO;
</code>```

or You can use

```<code> editButton.enabled = NO;
</code>```

Title: How do I disable a UIButton?

Body:
I am working on a project in which I have to show all photos of Photo Library in a plist and show them horizontally on UIButtons.

My app will also have an edit button: when the user clicks this button, a delete mark (such as usually appears in other iPhone/iPad apps) should show on each button.

But here's the crucial bit: as soon as this delete mark appears, the functionality of the button should be disabled. I've tried accomplishing this with the following:

{
  editbutton.enabled=NO;
}

...but it neither produces an error nor works. What should I do?

Body:
Please set this...

 editButton.userInteractionEnabled = NO;

or You can use

 editButton.enabled = NO;


问:
How to edit html element with Javascript dom?
i try to edit the span element inside with javascript dom:

```<code><div class="data">
<span>Jan. 16, 2019</span>
</div>
</code>```

So that only last 4 characters are shown,

```<code>var list = document.getElementById("data");
list.removeChild(list.childNodes[3]);
</code>```

But it doesnot work

答:
In order to only keep the last four characters in the span:

var list = document.getElementsByClassName("data")[0];
let str = list.childNodes[1].textContent;
list.childNodes[1].textContent = str.substring(str.length-4, str.length);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="data">
     <span>Jan. 16, 2019</span>
</div></code>```

Body:
i try to edit the span element inside with javascript dom:

Jan. 16, 2019

So that only last 4 characters are shown,

var list = document.getElementById("data");
list.removeChild(list.childNodes[3]);

But it doesnot work

Body:
In order to only keep the last four characters in the span:

var list = document.getElementsByClassName("data")[0];
let str = list.childNodes[1].textContent;
list.childNodes[1].textContent = str.substring(str.length-4, str.length);

<div class="data">
     <span>Jan. 16, 2019</span>
</div>


问:
CMake referencing random shell script i created in ~/bin (even after i deleted it)?
In Ubuntu (20.04, Cinnamon desktop), I created a basic shell script to run .desktop files from the command line with these contents:

#!/bin/sh
$(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
```

<p>and then ran <code>chmod +x</code> in order to be able to execute that as a command. Now, whenever I use <code>cmake --build</code>, it includes the contents of this file -- even after I've deleted the offending script, <em>and</em> a full restart.
Here's the output from my latest attempt to cmake:</p>

<pre class="lang-sh prettyprint-override"><code>alexander@alexander-Inspiron-7559:~/Documents/Code/CPP/SDLProject/bin$ cmake --build .
CMake Error: The current CMakeCache.txt directory /home/alexander/Documents/Code/CPP/SDLProject/bin/CMakeCache.txt is different than the directory /home/alexander/Documents/Code/CPP/OGRE-Project-1/bin where CMakeCache.txt was created. This may result in binaries being created in the wrong place. If you are not sure, reedit the CMakeCache.txt
[  0%] Building CXX object CMakeFiles/SDLProject.dir/src/main.cpp.o
In file included from /home/alexander/Documents/Code/CPP/OGRE-Project-1/src/App.hpp:10,
                 from /home/alexander/Documents/Code/CPP/OGRE-Project-1/src/main.cpp:1:
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:8: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |        ^~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:35: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |                                   ^~~~~~~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:54: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |                                                      ^~~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:69: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |                                                                     ^~~~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:85: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |                                                                                ^~~~~~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:2: error: expected constructor, destructor, or type conversion before ‘(’ token
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |  ^
In file included from /home/alexander/Documents/Code/CPP/OGRE-Project-1/src/main.cpp:1:
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/App.hpp:24:2: error: ‘Label’ does not name a type
   24 |  Label *lb;
      |  ^~~~~
make[2]: *** [CMakeFiles/SDLProject.dir/build.make:63: CMakeFiles/SDLProject.dir/src/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/SDLProject.dir/all] Error 2
make: *** [Makefile:84: all] Error 2```
```

答:
See if the script that you created then deleted is referenced in the CMakeCache.txt file. If it is, then remove/delete the reference.

Cmake as I recall is an 'out of source directory' build tool (you create a new, empty build directory then reference your source directory). When it starts a build it generates a cache/list for files--see 'CMakeCache.txt'--to assist with dependencies at compilation time.

Deleting the 'CMakeCache.txt' file may also work for you, as it will be regenerated by cmake.

Body:
In Ubuntu (20.04, Cinnamon desktop), I created a basic shell script to run .desktop files from the command line with these contents:

#!/bin/sh
$(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &

and then ran chmod +x in order to be able to execute that as a command. Now, whenever I use cmake --build, it includes the contents of this file -- even after I've deleted the offending script, and a full restart.
Here's the output from my latest attempt to cmake:

alexander@alexander-Inspiron-7559:~/Documents/Code/CPP/SDLProject/bin$ cmake --build .
CMake Error: The current CMakeCache.txt directory /home/alexander/Documents/Code/CPP/SDLProject/bin/CMakeCache.txt is different than the directory /home/alexander/Documents/Code/CPP/OGRE-Project-1/bin where CMakeCache.txt was created. This may result in binaries being created in the wrong place. If you are not sure, reedit the CMakeCache.txt
[  0%] Building CXX object CMakeFiles/SDLProject.dir/src/main.cpp.o
In file included from /home/alexander/Documents/Code/CPP/OGRE-Project-1/src/App.hpp:10,
                 from /home/alexander/Documents/Code/CPP/OGRE-Project-1/src/main.cpp:1:
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:8: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |        ^~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:35: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |                                   ^~~~~~~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:54: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |                                                      ^~~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:69: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |                                                                     ^~~~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:85: warning: character constant too long for its type
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |                                                                                ^~~~~~~~~~~
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/text/Label.hpp:8:2: error: expected constructor, destructor, or type conversion before ‘(’ token
    8 | $(grep '^Exec' $1 | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g') &
      |  ^
In file included from /home/alexander/Documents/Code/CPP/OGRE-Project-1/src/main.cpp:1:
/home/alexander/Documents/Code/CPP/OGRE-Project-1/src/App.hpp:24:2: error: ‘Label’ does not name a type
   24 |  Label *lb;
      |  ^~~~~
make[2]: *** [CMakeFiles/SDLProject.dir/build.make:63: CMakeFiles/SDLProject.dir/src/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/SDLProject.dir/all] Error 2
make: *** [Makefile:84: all] Error 2```


问:
Numpy remove unique rows based on column
I am trying to get an array where it would remove all unique rows based on the first column. My array works looks like this,

```<code>[['Aaple' 'Red']
 ['Aaple' '0.0']
 ['Banana' 'Yellow']
 ['Banana' '0.0']
 ['Orange' 'Orange']
 ['Pear' 'Yellow']
 ['Pear' '0.0']
 ['Strawberry' 'Red']]
</code>```

I want it to look like this,

```<code>[['Aaple' 'Red']
 ['Aaple' '0.0']
 ['Banana' 'Yellow']
 ['Banana' '0.0']
 ['Pear' 'Yellow']
 ['Pear' '0.0']]
</code>```

Where it would remove the unique values from column one. My current code looks like this,

```<code>arr = np.array(["Aaple", "Pear", "Banana"])

arr2 = np.array([["Strawberry", "Red"], ["Aaple", "Red"], ["Orange", "Orange"], ["Pear", "Yellow"], ["Banana", "Yellow"]])

arr = arr.reshape(-1,1)
zero_arr = np.zeros((len(arr), 1))
arr = np.column_stack((arr, zero_arr))
combine = np.vstack((arr2, arr))
sort = combine[combine[:,0].argsort()]
#Where the first array printed is sort
</code>```

I was able to get ['Aaple' 'Banana' 'Pear'], the rows I want to keep by adding x = sort[:-1][sort[1:] == sort[:-1]], what would be the next steps?

答:
It may be easier to use pandas:

```<code>df = pd.DataFrame(sort, columns=list('ab'))
df[df.groupby('a').a.transform('count')>1].values
</code>```

Result:

```<code>array([['Aaple', 'Red'],
       ['Aaple', '0.0'],
       ['Banana', 'Yellow'],
       ['Banana', '0.0'],
       ['Pear', 'Yellow'],
       ['Pear', '0.0']], dtype=object)
</code>```

Body:
I am trying to get an array where it would remove all unique rows based on the first column. My array works looks like this,

[['Aaple' 'Red']
 ['Aaple' '0.0']
 ['Banana' 'Yellow']
 ['Banana' '0.0']
 ['Orange' 'Orange']
 ['Pear' 'Yellow']
 ['Pear' '0.0']
 ['Strawberry' 'Red']]

I want it to look like this,

[['Aaple' 'Red']
 ['Aaple' '0.0']
 ['Banana' 'Yellow']
 ['Banana' '0.0']
 ['Pear' 'Yellow']
 ['Pear' '0.0']]

Where it would remove the unique values from column one. My current code looks like this,

arr = np.array(["Aaple", "Pear", "Banana"])

arr2 = np.array([["Strawberry", "Red"], ["Aaple", "Red"], ["Orange", "Orange"], ["Pear", "Yellow"], ["Banana", "Yellow"]])

arr = arr.reshape(-1,1)
zero_arr = np.zeros((len(arr), 1))
arr = np.column_stack((arr, zero_arr))
combine = np.vstack((arr2, arr))
sort = combine[combine[:,0].argsort()]
#Where the first array printed is sort

I was able to get ['Aaple' 'Banana' 'Pear'], the rows I want to keep by adding x = sort[:-1][sort[1:] == sort[:-1]], what would be the next steps?

Body:
It may be easier to use pandas:

df = pd.DataFrame(sort, columns=list('ab'))
df[df.groupby('a').a.transform('count')>1].values

Result:

array([['Aaple', 'Red'],
       ['Aaple', '0.0'],
       ['Banana', 'Yellow'],
       ['Banana', '0.0'],
       ['Pear', 'Yellow'],
       ['Pear', '0.0']], dtype=object)


答:
One error: you're searching with getElementById for an element with id data but data is the class.

 should make the list assignment work. Or use document.querySelector('.data')

The next line with removeChild makes no sense to me, at least with given HTML.

Title: How to edit html element with Javascript dom?

Body:
One error: you're searching with getElementById for an element with id data but data is the class.

<div id="data"> should make the list assignment work. Or use document.querySelector('.data')

The next line with removeChild makes no sense to me, at least with given HTML.


问:
Firebase sign out not working in Swift
I am using newest Firebase API (3.2.1) and I am using this code to check if user is signed in:

```<code>override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    if(self.navigationController != nil){
        self.navigationController!.setNavigationBarHidden(true, animated: true)
    }

    if(FIRAuth.auth() != nil){
        self.performSegueWithIdentifier("loginSuccessSegue", sender: self)
    }
}
</code>```

In other words if auth object is present I am switching to other controller. On that controller I have sign out button which is doing sign out like this:

```<code>do{
    try FIRAuth.auth()?.signOut()
    self.performSegueWithIdentifier("logoutSegue", sender: self)
}catch{
    print("Error while signing out!")
}
</code>```

I do not get error on this operation but when I am switched to login controller, this auth object is present and I get switched back again to controller with data. I also tried checking the current user object in auth and it is present and valid.

Anyone knows how an I properly do sign out?

答:
2020 ...

```<code>do { try Auth.auth().signOut() }
catch { print("already logged out") }
</code>```

Typically, on your "base" screen, something like ...

```<code>func logoutUser() {
    // call from any screen

    do { try Auth.auth().signOut() }
    catch { print("already logged out") }

    navigationController?.popToRootViewController(animated: true)
}
</code>```

Title: Firebase sign out not working in Swift

Body:
I am using newest Firebase API (3.2.1) and I am using this code to check if user is signed in:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    if(self.navigationController != nil){
        self.navigationController!.setNavigationBarHidden(true, animated: true)
    }

    if(FIRAuth.auth() != nil){
        self.performSegueWithIdentifier("loginSuccessSegue", sender: self)
    }
}

In other words if auth object is present I am switching to other controller. On that controller I have sign out button which is doing sign out like this:

do{
    try FIRAuth.auth()?.signOut()
    self.performSegueWithIdentifier("logoutSegue", sender: self)
}catch{
    print("Error while signing out!")
}

I do not get error on this operation but when I am switched to login controller, this auth object is present and I get switched back again to controller with data. I also tried checking the current user object in auth and it is present and valid.

Anyone knows how an I properly do sign out?

Body:
2020 ...

do { try Auth.auth().signOut() }
catch { print("already logged out") }

Typically, on your "base" screen, something like ...

func logoutUser() {
    // call from any screen

    do { try Auth.auth().signOut() }
    catch { print("already logged out") }

    navigationController?.popToRootViewController(animated: true)
}


问:
Javascript Class: getter value when instantiating the class
I have a quick question - it was challenge in Hacker Rank - trying  to find an answer.

Question goes like this.

Console log should print the reverse order of numbers in the class.
Restrictions:
1. Class constructor should not be modified.
2. Console log statement should not be modified.

You can do anything else to make it working.

```<code>class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2
</code>```

Just curious to know how we can implement this?

答:
using symbol iterator is one of many ways

class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }
  [Symbol.iterator]() {
    return this.numbers.reverse().values()
  }
  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2```

Body:
I have a quick question - it was challenge in Hacker Rank - trying  to find an answer.

Question goes like this.

Console log should print the reverse order of numbers in the class.
Restrictions:
1. Class constructor should not be modified.
2. Console log statement should not be modified.

You can do anything else to make it working.

class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2

Just curious to know how we can implement this?


问:
End-to-end encryption with Azure CosmosDB vs Storage
We develop a cloud based SaaS solution suitable for multiple tenants. For very sensitive data, we need to isolate tenants and provide end-to-end encryption for users assigned to this tenant. Not even the operators of the SaaS solution provider should be able to decrypt the data.

Azure Storage

I see that i could use the client-side encryption feature along with Azure Key Value for Azure Storage to accomplish this, allowing every tenant to provide a separate Azure KeyVault account which manages the encryption keys.

Azure Cosmos DB

As Azure Cosmos DB provides superior features regarding scalability, we would like to use Cosmos over Azure Storage. However, i didn't find a comparable feature for Cosmos DB providing end-to-end encryption capabilitys. The only Cosmos DB encryption feature i found is encryption at rest.

So my question is:

Is there a comparable feature for Azure Cosmos DB i could use to achieve the same goal (end-to-end encryption)?

答:
In May 2020, Microsoft have made customer-managed-keys feature GA which means you can choose to add a second layer of encryption with keys you manage (customer-managed keys).

Note: This feature can be enabled only for New Azure Cosmos Accounts. Can't enable for existing accounts.

https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-setup-cmk


问:
Get Linenumber of TypeError causing test discovery to fail in VSCode
I have a python test file using the unittest framework and test discovery fails because of a TypeError.
Is there a way in Visual Studio Code to show the line number that causes this TypeError? It is really cumbersome to comment out tests to find the culprit

答:
1.pytest works charmly with VS Code. More info is here.

pytest --tb=line

modifying-python-traceback-printing

2.Or use pytest-instafail

```<code>pip install pytest-instafail
</code>```

Sample code:

```<code>def print_failure(self, report):
    if self.config.option.tbstyle != "no":
        if self.config.option.tbstyle == "line":
            line = self._getcrashline(report)
            self.write_line(line)
        else:
            msg = self._getfailureheadline(report)
            # "when" was unset before pytest 4.2 for collection errors.
            when = getattr(report, "when", "collect")
            if when == "collect":
                msg = "ERROR collecting " + msg
            elif when == "setup":
                msg = "ERROR at setup of " + msg
            elif when == "teardown":
                msg = "ERROR at teardown of " + msg
            self.write_sep("_", msg)
            if not self.config.getvalue("usepdb"):
                self._outrep_summary(report)
</code>```

pytest_instafail

Body:
1.pytest works charmly with VS Code. More info is here.

pytest --tb=line

modifying-python-traceback-printing

2.Or use pytest-instafail

pip install pytest-instafail

Sample code:

def print_failure(self, report):
    if self.config.option.tbstyle != "no":
        if self.config.option.tbstyle == "line":
            line = self._getcrashline(report)
            self.write_line(line)
        else:
            msg = self._getfailureheadline(report)
            # "when" was unset before pytest 4.2 for collection errors.
            when = getattr(report, "when", "collect")
            if when == "collect":
                msg = "ERROR collecting " + msg
            elif when == "setup":
                msg = "ERROR at setup of " + msg
            elif when == "teardown":
                msg = "ERROR at teardown of " + msg
            self.write_sep("_", msg)
            if not self.config.getvalue("usepdb"):
                self._outrep_summary(report)

pytest_instafail


问:
Object object is shown in select tag in react
Data inside options(JSON) is </p>

<p>const options =  {"option":"Male","value":"M"};
Raect code is </p>

```<code>{props.options.map((option) => {
      return (
         <option key={option.value} value={option.option}>
            <Translate>{option.option}</Translate>
         </option>
      );
})}
</code>```

答:
You are interpreting the map in the wrong way. Please follow this and use it in a similar way. Make sure the options are in an array.</p>

```<code>const values = [{option: 'male': value: 'm'}, {option: 'female': value: 'f'}, {option: 'others': value: 'o'}];

function App() {
 return (
  <div>
    {values.map(val => (
      <option key={val.value} value={val.option}>
         <Translate>{val.option}</Translate>
       </option>
    ))}
  </div>
 );
}
</code>```

Body:
Data inside options(JSON) is

const options =  {"option":"Male","value":"M"};
Raect code is

{props.options.map((option) => {
      return (
         <option key={option.value} value={option.option}>
            <Translate>{option.option}</Translate>
         </option>
      );
})}

Body:
You are interpreting the map in the wrong way. Please follow this and use it in a similar way. Make sure the options are in an array.

const values = [{option: 'male': value: 'm'}, {option: 'female': value: 'f'}, {option: 'others': value: 'o'}];

function App() {
 return (
  <div>
    {values.map(val => (
      <option key={val.value} value={val.option}>
         <Translate>{val.option}</Translate>
       </option>
    ))}
  </div>
 );
}


问:
TypeError: val.set is not a function (JS Map())
I'm having this issue where I'm executing val.set(key, value) and is throwing a type error TypeError: val.set is not a function in the file vendor-es2015.js.

The code (simplified):

```<code>import { Storage } from '@ionic/storage';

map = new Map();

this.storage.set('sth', map);

this.storage.get('sth').then((val) => {
    val.set(key, value); //TypeError, returns { } insead of a map.
});
</code>```

The interesting thing is that this works fine in browsers, but when it's compiled to Android with Capacitor, this error is thrown.

tsconfig.json

```<code>"target": "es2015",
"lib": [
  "es2018",
  "dom"
]
</code>```

答:
As the documentation says :

Storage works on Strings only. However, storing JSON blobs is easy:
  just JSON.stringify the object before calling set, then JSON.parse the
  value returned from get. See the example below for more details.

Might look like this (updated with help from Bergi):

```<code>const mapStr = JSON.stringify(Array.from(map.entries()));
this.storage.set('sth', mapStr);

this.storage.get('sth').then((val) => {
    const theMap = new Map(JSON.parse(val));
    theMap.set(key, value);
});
</code>```

Body:
I'm having this issue where I'm executing val.set(key, value) and is throwing a type error TypeError: val.set is not a function in the file vendor-es2015.js.

The code (simplified):

import { Storage } from '@ionic/storage';

map = new Map();

this.storage.set('sth', map);

this.storage.get('sth').then((val) => {
    val.set(key, value); //TypeError, returns { } insead of a map.
});

The interesting thing is that this works fine in browsers, but when it's compiled to Android with Capacitor, this error is thrown.

tsconfig.json

"target": "es2015",
"lib": [
  "es2018",
  "dom"
]

Body:
As the documentation says :

Storage works on Strings only. However, storing JSON blobs is easy:
  just JSON.stringify the object before calling set, then JSON.parse the
  value returned from get. See the example below for more details.

Might look like this (updated with help from Bergi):

const mapStr = JSON.stringify(Array.from(map.entries()));
this.storage.set('sth', mapStr);

this.storage.get('sth').then((val) => {
    const theMap = new Map(JSON.parse(val));
    theMap.set(key, value);
});


问:
JavaScript Unique Browser Id
is there anyway to create a unique ID for a browser within javascript?

Im not talking about an ID that is random everytime it is generated but an ID that is unique to the browser it is generated in but also takes into account the computer its running on.

Example:

Windows 7 Chrome might generate: asdh128hakj4gh

Windows 7 Opera might generate: 23hjad823hjakk

Windows 7 Chrome, diff hardware, might generate: asd238881jaal

etc...

Is there anyway to do this?

答:
You can use biri library.
The ID is generated per computer, and doesn't change unless the MAC address of the computer changes.</p>

ContentLicense: CC BY-SA 2.5

Title: JavaScript Unique Browser Id


问:
Where do i start in making an android app?
So I'm new to programming and I really want to get into the deep stuffs. So firstly I'm looking to make an android app but I really don't know where to even begin. Which framework do i use? What programming language should I master. I just need a little light to be shed here.</p>

答:
For Programming Language, you can learn Java or Kotlin .. Etc

For Java, use NetBeans to train and improve, I really recommend it for beginners.

https://netbeans.org

After you learn programming language, start learning Android development.
You will need Android studio

https://developer.android.com/studio

You also need to learn SQLite for databases.
Wish this helps.


问:
Card display vue js
I'm new to vue.js and I'm currently practicing it with vuetify. I'm trying to make this layout for hours but I'm still stuck. Can anyone help me by explaining how to approach this problem please?

I have an array of objects which contains a description and an image. I would like to display them like in the picture below.

The first card, i'll display a description, the second one, an image. When changing row, for example the second row, I'll keep an image just like the fourth card. The eighth and ninth will be text and continue alternating from there.

<template>

    <v-container grid-list-lg>

Home

      <v-layout row>
        <v-flex lg3 v-for="(item, index) in arr" :key="item.id" class="space-bottom">
          <v-card class="mx-auto" max-width="344" outlined>
            <v-list-item three-line>
              <v-list-item-content v-if="index % 2 === 0" height="400px">
                <v-list-item-subtitle>{{item.description}}</v-list-item-subtitle>

                <v-list-item-subtitle class="subtitle-style">

                    Read more

                </v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>

            <v-hover>
              <template v-slot:default="{ hover }">
                <v-list-item-content v-if="index % 2 !== 0">

                  <v-fade-transition>
                    <v-overlay v-if="hover" absolute color="#036358">
                      <v-btn>See more info</v-btn>
                    </v-overlay>
                  </v-fade-transition>
                </v-list-item-content>
              </template>
            </v-hover>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>

</template>

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script></code>```

Currently, it is like this:

答:
This should do it:

```<code>methods: {
  getCardType(index) {
    return (this.rowLength * 2 + index) % (this.rowLength * 2) >= this.rowLength
      ? index % 2 ? 'text' : 'img'
      : index % 2 ? 'img' : 'text'
  }
}
</code>```

Where rowLength is 4:

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: '#app',
  data: () => ({
    rowLength: 4
  }),
  methods: {
    getCardType(index) {
      return (this.rowLength * 2 + index) % (this.rowLength * 2) >= this.rowLength
        ? index % 2 ? 'text' : 'img'
        : index % 2 ? 'img' : 'text'
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#app {
  display: flex;
  flex-wrap: wrap;
}</code>```

  <div v-for="n in 100" class="card" :style="{flex: `1 0 ${100/rowLength}%`}">{{getCardType(n - 1)}}

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

<p>It can probably be simplified and/or adjusted for a different number of items/row.</strike></p>

<p>Here's a version which keeps the "chekers" pattern on both odd and even number of columns:</p>

```getCardType(index) {
  return this.rowLength % 2 ||
  (this.rowLength * 2 + index) % (this.rowLength * 2) >= this.rowLength
  ? index % 2 ? 'text' : 'img'
  : index % 2 ? 'img' : 'text'
}
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: '#app',
  data: () => ({
    rowLength: 4
  }),
  methods: {
    getCardType(index) {
      return this.rowLength % 2 ||
      (this.rowLength * 2 + index) % (this.rowLength * 2) >= this.rowLength
      ? index % 2 ? 'text' : 'img'
      : index % 2 ? 'img' : 'text'
    }
  }
})</code>```

.columns {
  display: flex;
  flex-wrap: wrap;
}
.card {
  padding: 1rem;
  box-sizing: border-box;
}
.img {
  background-color: #f5f5f5;
}
body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<div id="app">
  <div>Columns: <input type="number" v-model="rowLength"></div>
  <div class="columns">
    <div v-for="n in 100" class="card"
         :style="{flex: `1 0 ${100/rowLength}%`}"
         :class="[getCardType(n - 1)]"
         >{{getCardType(n - 1)}}
    </div>
  </div>
</div></code>```

which, in English, would be: return img or text based on index parity but reverse the condition on even rows if the number of items per row is even.

Title: Card display vue js

Body:
I'm new to vue.js and I'm currently practicing it with vuetify. I'm trying to make this layout for hours but I'm still stuck. Can anyone help me by explaining how to approach this problem please?

I have an array of objects which contains a description and an image. I would like to display them like in the picture below.

The first card, i'll display a description, the second one, an image. When changing row, for example the second row, I'll keep an image just like the fourth card. The eighth and ninth will be text and continue alternating from there.

<template>

    <v-container grid-list-lg>

Home

      <v-layout row>
        <v-flex lg3 v-for="(item, index) in arr" :key="item.id" class="space-bottom">
          <v-card class="mx-auto" max-width="344" outlined>
            <v-list-item three-line>
              <v-list-item-content v-if="index % 2 === 0" height="400px">
                <v-list-item-subtitle>{{item.description}}</v-list-item-subtitle>

                <v-list-item-subtitle class="subtitle-style">

                    Read more

                </v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>

            <v-hover>
              <template v-slot:default="{ hover }">
                <v-list-item-content v-if="index % 2 !== 0">

                  <v-fade-transition>
                    <v-overlay v-if="hover" absolute color="#036358">
                      <v-btn>See more info</v-btn>
                    </v-overlay>
                  </v-fade-transition>
                </v-list-item-content>
              </template>
            </v-hover>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>

</template>

Currently, it is like this:

Body:
This should do it:

methods: {
  getCardType(index) {
    return (this.rowLength * 2 + index) % (this.rowLength * 2) >= this.rowLength
      ? index % 2 ? 'text' : 'img'
      : index % 2 ? 'img' : 'text'
  }
}

Where rowLength is 4:

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: '#app',
  data: () => ({
    rowLength: 4
  }),
  methods: {
    getCardType(index) {
      return (this.rowLength * 2 + index) % (this.rowLength * 2) >= this.rowLength
        ? index % 2 ? 'text' : 'img'
        : index % 2 ? 'img' : 'text'
    }
  }
})

#app {
  display: flex;
  flex-wrap: wrap;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<div id="app">
  <div v-for="n in 100" class="card" :style="{flex: `1 0 ${100/rowLength}%`}">{{getCardType(n - 1)}}</div>
</div>

It can probably be simplified and/or adjusted for a different number of items/row.

Here's a version which keeps the "chekers" pattern on both odd and even number of columns:

getCardType(index) {
  return this.rowLength % 2 ||
  (this.rowLength * 2 + index) % (this.rowLength * 2) >= this.rowLength
  ? index % 2 ? 'text' : 'img'
  : index % 2 ? 'img' : 'text'
}

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: '#app',
  data: () => ({
    rowLength: 4
  }),
  methods: {
    getCardType(index) {
      return this.rowLength % 2 ||
      (this.rowLength * 2 + index) % (this.rowLength * 2) >= this.rowLength
      ? index % 2 ? 'text' : 'img'
      : index % 2 ? 'img' : 'text'
    }
  }
})

.columns {
  display: flex;
  flex-wrap: wrap;
}
.card {
  padding: 1rem;
  box-sizing: border-box;
}
.img {
  background-color: #f5f5f5;
}
body {
  margin: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<div id="app">
  <div>Columns: <input type="number" v-model="rowLength"></div>
  <div class="columns">
    <div v-for="n in 100" class="card"
         :style="{flex: `1 0 ${100/rowLength}%`}"
         :class="[getCardType(n - 1)]"
         >{{getCardType(n - 1)}}
    </div>
  </div>
</div>

which, in English, would be: return img or text based on index parity but reverse the condition on even rows if the number of items per row is even.


问:
Vue bootstrap  not firing function @click event
I don't want to go into trying to pass props to the  buttons so I just want to call signinUser() @click in my modal when I click the default OK button but my modal doesn't seem to fire on this.

The signinUser() will fire on @hidden though.

I'm also trying to prevent the modal from dismissing unless a user is authenticated (which is why I don't want it firing on @hidden)

Can someone point me in the right direction?

Here's my component where I am authenticating with firebase:

<template>

      <input id="email" v-model="email" placeholder="email">
      <input id="pass" v-model="password" placeholder="password">

    <form v-on:submit.prevent class="cube" v-if="modalShow == false">

        <input id="title" v-model="title" placeholder="title">

        <textarea id="body" v-model="body" placeholder="body"></textarea>

        Publish

    </form>

</template>

```

答:
use @ok instead of @click:

```<code><b-modal id="signinModal" @ok="signinUser($event)" v-model="modalShow" :no-close-on-backdrop="true">
  <!-- more code -->
</b-modal>
</code>```

Title: Vue bootstrap <b-modal> not firing function @click event

Body:
use @ok instead of @click:

<b-modal id="signinModal" @ok="signinUser($event)" v-model="modalShow" :no-close-on-backdrop="true">
  <!-- more code -->
</b-modal>


问:
How to catch Exception like in a FrontController in Spring
Basically every repository method can possibly throw a DataAccessException . A lot of exceptions inherit from DataAccessException. So maybe I will catch DuplicateKeyException or maybe DataIntegrityViolationException . But all the other say 40 - 50 exceptions I will not catch explicitly. Instead I will just catch DataAccessException . So why always catch DataAccessException  ?? Instead I would prefer catching it just once. But how to do that in Spring. There is no Front Controller. There are just Controllers. So how should I catch it in a central place. The only place I know whould be start of Spring. But I don't think that works.</p>

```<code>@SpringBootApplication
@EnableJpaRepositories
public class Application {

    public static void main(String[] args) {
        try{
        SpringApplication.run(Application.class, args);
        }
        catch(DataAccessException e)
        {
              //Do your error handling here
        }
    }

}
</code>```

答: You should catch the exceptions at the beans or controllers that has the code managing db access, you can catch and manage this each controller bu the better approach is to implement an exception handler as th guid is showing here https://www.baeldung.com/exception-handling-for-rest-with-spring</p>

Body:
Basically every repository method can possibly throw a DataAccessException . A lot of exceptions inherit from DataAccessException. So maybe I will catch DuplicateKeyException or maybe DataIntegrityViolationException . But all the other say 40 - 50 exceptions I will not catch explicitly. Instead I will just catch DataAccessException . So why always catch DataAccessException  ?? Instead I would prefer catching it just once. But how to do that in Spring. There is no Front Controller. There are just Controllers. So how should I catch it in a central place. The only place I know whould be start of Spring. But I don't think that works.

@SpringBootApplication
@EnableJpaRepositories
public class Application {

    public static void main(String[] args) {
        try{
        SpringApplication.run(Application.class, args);
        }
        catch(DataAccessException e)
        {
              //Do your error handling here
        }
    }

}


问:
How to solve link Posts and users to comments in Django Admin
I am trying to link each comment to a post and to a username

I have proceeded with the logic of the comment with the following models.py

```<code>class Comment(models.Model):
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, null=True, blank=True)
    content = models.TextField(max_length=160)

    def __str__(self):
        return self.content
</code>```

Now that the comment is working and everything I am trying to link the comment section to the post and the user of the comment in the admin so I used the following models.py

```<code>class Comment(models.Model):
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, null=True, blank=True)
    content = models.TextField(max_length=160)

    def __str__(self):
        return '{}-{}'.format(self.post.title, str(self.user.username)) <----Error line
</code>```

Which is returning

```<code>AttributeError at /admin/score/comment/
'NoneType' object has no attribute 'title'
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'title'
</code>```

What should fix this problem
I have also used the following which did not work

```<code>    def __str__(self):
       return '%s %s' % (self.post.title, self.user.username)
</code>```

答: It looks like there is at least one instance of Comment created which does not have a post entry (which you allow via null=True, blank=True). Therefore, self.post.title tries to access the Attribute title of None, raising the error you see. You could set null=False which will raise an error when trying to generate the Comment without a post.

Body:
I am trying to link each comment to a post and to a username

I have proceeded with the logic of the comment with the following models.py

class Comment(models.Model):
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, null=True, blank=True)
    content = models.TextField(max_length=160)

    def __str__(self):
        return self.content

Now that the comment is working and everything I am trying to link the comment section to the post and the user of the comment in the admin so I used the following models.py

class Comment(models.Model):
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, null=True, blank=True)
    content = models.TextField(max_length=160)

    def __str__(self):
        return '{}-{}'.format(self.post.title, str(self.user.username)) <----Error line

Which is returning

AttributeError at /admin/score/comment/
'NoneType' object has no attribute 'title'
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'title'

What should fix this problem
I have also used the following which did not work

    def __str__(self):
       return '%s %s' % (self.post.title, self.user.username)


问:
Find service`s uuid of a bluetooth device
I'm trying to get information about services provided by bluetooth devices. Using WSALookupServiceNext I can get list of all services. However, regardless of what bluetooth device I try to discover, the resulting WSAQUERYSET structure (pqs) never contains lpServiceClassId field (while the lpszServiceInstanceName is always present). I want to know UUID of a service to determine to which class of the Table 2: Service Class Profile Identifiers it belongs.

```<code>#include<winsock2.h>

int main()
{
    WSADATA data;
    WSAStartup(MAKEWORD(2, 2), &data);

    WSAQUERYSET qs{};
    qs.dwSize = sizeof(WSAQUERYSET);
    qs.dwNameSpace = NS_BTH;
    qs.dwNumberOfCsAddrs = 0;
    qs.lpszContext = (LPWSTR)L"12:34:56:78:99:11";
    qs.lpServiceClassId = const_cast<LPGUID>(&PublicBrowseGroupServiceClass_UUID);

    const DWORD flags = LUP_FLUSHCACHE | LUP_RETURN_ALL;
    HANDLE hlookup = nullptr;
    WSALookupServiceBegin(&qs, flags, &hlookup);
    while (true) {
        char buff[4096];
        WSAQUERYSET* pqs = (WSAQUERYSET*)buff;
        DWORD size = sizeof(buff);
        memset(buff, 0, size);

        const INT res = WSALookupServiceNext(hlookup, flags, &size, pqs);
        if (res != 0 && GetLastError() == WSA_E_NO_MORE) {
            break;
        }

        // it prints "service name=Advanced Audio, service uuid=0x0"
        wprintf(L"service name=%s, service uuid=0x%X\n", pqs->lpszServiceInstanceName, pqs->lpServiceClassId->Data1);
    }
}
</code>```

答:
Answering my own question:
In order to get service ID we have to parse SPD structures which are returned from WSALookupServiceNext function call and accessible via WSAQUERYSET.lpBlob member.
For more details see Mike Petrichenko's comment.
Also, there is a very good example how to implement it from Qt framework source code.

As for myself, I decided not to follow this path, because my goal was to write a console utility for pairing Bluetooth devices. I have found that there is a better way to do that using Windows.Devices.Enumeration API. Finally, using this API, I managed to create the BluetoothDevicePairing utility I was working on.

Body:
I'm trying to get information about services provided by bluetooth devices. Using WSALookupServiceNext I can get list of all services. However, regardless of what bluetooth device I try to discover, the resulting WSAQUERYSET structure (pqs) never contains lpServiceClassId field (while the lpszServiceInstanceName is always present). I want to know UUID of a service to determine to which class of the Table 2: Service Class Profile Identifiers it belongs.

#include<winsock2.h>

int main()
{
    WSADATA data;
    WSAStartup(MAKEWORD(2, 2), &data);

    WSAQUERYSET qs{};
    qs.dwSize = sizeof(WSAQUERYSET);
    qs.dwNameSpace = NS_BTH;
    qs.dwNumberOfCsAddrs = 0;
    qs.lpszContext = (LPWSTR)L"12:34:56:78:99:11";
    qs.lpServiceClassId = const_cast<LPGUID>(&PublicBrowseGroupServiceClass_UUID);

    const DWORD flags = LUP_FLUSHCACHE | LUP_RETURN_ALL;
    HANDLE hlookup = nullptr;
    WSALookupServiceBegin(&qs, flags, &hlookup);
    while (true) {
        char buff[4096];
        WSAQUERYSET* pqs = (WSAQUERYSET*)buff;
        DWORD size = sizeof(buff);
        memset(buff, 0, size);

        const INT res = WSALookupServiceNext(hlookup, flags, &size, pqs);
        if (res != 0 && GetLastError() == WSA_E_NO_MORE) {
            break;
        }

        // it prints "service name=Advanced Audio, service uuid=0x0"
        wprintf(L"service name=%s, service uuid=0x%X\n", pqs->lpszServiceInstanceName, pqs->lpServiceClassId->Data1);
    }
}


问:
How to collapse an array by joining all strings, but leaving objects
While I'm sure I'm waay over-complicating things, I'm curious to know how I would "collapse" an array by combining all adjacent strings, but leaving objects as objects so that:

```<code>array = ["I","want","to",[Obj],"come","together"]
</code>```

outputs

```<code>["I want to", [Obj], "come together"];
</code>```

I feel like array.reduce() might be the ticket here, but I'm still wrapping my head around that function.

答:
Reduce the array. If the current item and the last item in the accumulator (r) are strings, concatenate them. If not, push the current item to the accumulator:

const array = ["I","want","to",[{}],"come","together"]

const isString = s => typeof s === 'string'

const result = array.reduce((r, o) => {
  if(isString(o) && isString(r[r.length - 1])) {
    r[r.length - 1] = `${r[r.length - 1]} ${o}`
  } else {
    r.push(o)
  }

  return r
}, [])

console.log(result)```

Body:
While I'm sure I'm waay over-complicating things, I'm curious to know how I would "collapse" an array by combining all adjacent strings, but leaving objects as objects so that:

array = ["I","want","to",[Obj],"come","together"]

outputs

["I want to", [Obj], "come together"];

I feel like array.reduce() might be the ticket here, but I'm still wrapping my head around that function.


问:
Xamarin forms Listview within a listview with actions per item on child list
I need to create the following view (HTML design)
Final Layout

The data is as follows, and we are just not able to get a ListView working to do this:

{  "chronicScripts": [
          {
              "forName": "MR JOHN DOE",  "scriptNumber": 4000000,  "scriptDate": "2020-04-27T00:00:00",  "chronics": [
                  {
                      "description": "TAMSUL 0.4MG SR  CAP",  "order": "order",  },
                  {
                      "description": "STORWIN 20MG     TAB",  "order": "order",  },
                  {
                      "description": "COXLEON 200MG    CAP",  "order": "order",  }
              ]
          },
          {
              "forName": " JANE DOE",  "scriptNumber": 4800001,  "scriptDate": "2020-04-27T00:00:00",  "chronics": [
                  {
                      "description": "CILODEX EAR DROPS",  "order": "order",  },
                  {
                      "description": "VUSOR 5MG        TAB",  "order": "order",  },
                  {
                      "description": "MIZART 40MG      TAB",  "order": "order",  },
                  {
                      "description": "ELTROXIN NF 0.1MG",  "order": "order",  }
              ]
          }
      ] }

Can you please advise how we can achieve such a design with what controls

[LISTVIEW (chronicscripts)]

[HEADER

[LISTVIEW (chronicscripts.chronics)]

[DETAILS

答:
```<code><telerikDataControls:RadListView
    x:Name="chronicProfileListView"
    BackgroundColor="Transparent"
    HorizontalOptions="FillAndExpand"
    ItemsSource="{Binding Chronics.ChronicScripts}"
    SelectionMode="None"
    VerticalOptions="FillAndExpand">
    <telerikDataControls:RadListView.ItemTemplate>
        <DataTemplate x:DataType="local:ChronicScriptsDataModel">
            <telerikListView:ListViewTemplateCell>
                <telerikListView:ListViewTemplateCell.View>
                    <Frame
                        Margin="0,0,0,10"
                        Padding="0,0,0,5"
                        BorderColor="LightGray"
                        HasShadow="False">
                        <Grid VerticalOptions="FillAndExpand">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>

                            <telerikPrimitives:RadBorder
                                Grid.Row="0"
                                Padding="0,15,0,15"
                                BackgroundColor="#17469e"
                                HorizontalOptions="FillAndExpand"
                                VerticalOptions="FillAndExpand">
                                <StackLayout>
                                    <Label
                                        HorizontalTextAlignment="Center"
                                        VerticalOptions="FillAndExpand"
                                        VerticalTextAlignment="Center">
                                        <Label.FormattedText>
                                            <FormattedString>
                                                <Span
                                                    FontAttributes="Bold"
                                                    FontSize="15"
                                                    Text="{Binding ForName}"
                                                    TextColor="White">
                                                    <Span.FontFamily>
                                                        <OnPlatform x:TypeArguments="x:String">
                                                            <On Platform="iOS" Value="Futura" />
                                                            <On Platform="Android" Value="Futura-Bookfont.ttf#Futura-Bookfont" />
                                                        </OnPlatform>
                                                    </Span.FontFamily>
                                                </Span>
                                                <Span
                                                    FontSize="15"
                                                    Text=" | "
                                                    TextColor="White">
                                                    <Span.FontFamily>
                                                        <OnPlatform x:TypeArguments="x:String">
                                                            <On Platform="iOS" Value="Futura" />
                                                            <On Platform="Android" Value="Futura-Bookfont.ttf#Futura-Bookfont" />
                                                        </OnPlatform>
                                                    </Span.FontFamily>
                                                </Span>
                                                <Span
                                                    FontSize="15"
                                                    Text="{Binding ScriptNumber}"
                                                    TextColor="White">
                                                    <Span.FontFamily>
                                                        <OnPlatform x:TypeArguments="x:String">
                                                            <On Platform="iOS" Value="Futura" />
                                                            <On Platform="Android" Value="Futura-Bookfont.ttf#Futura-Bookfont" />
                                                        </OnPlatform>
                                                    </Span.FontFamily>
                                                </Span>
                                                <Span
                                                    FontSize="15"
                                                    Text=" | "
                                                    TextColor="White">
                                                    <Span.FontFamily>
                                                        <OnPlatform x:TypeArguments="x:String">
                                                            <On Platform="iOS" Value="Futura" />
                                                            <On Platform="Android" Value="Futura-Bookfont.ttf#Futura-Bookfont" />
                                                        </OnPlatform>
                                                    </Span.FontFamily>
                                                </Span>
                                                <Span
                                                    FontSize="15"
                                                    Text="{Binding ScriptDate}"
                                                    TextColor="White">
                                                    <Span.FontFamily>
                                                        <OnPlatform x:TypeArguments="x:String">
                                                            <On Platform="iOS" Value="Futura" />
                                                            <On Platform="Android" Value="Futura-Bookfont.ttf#Futura-Bookfont" />
                                                        </OnPlatform>
                                                    </Span.FontFamily>
                                                </Span>
                                            </FormattedString>
                                        </Label.FormattedText>
                                    </Label>
                                </StackLayout>
                            </telerikPrimitives:RadBorder>

                            <!--  Display items per Order  -->
                            <telerikDataControls:NonVirtualizedItemsControl
                                Grid.Row="1"
                                ItemsSource="{Binding Chronics, Mode=TwoWay}"
                                SelectionMode="Single">
                                <telerikDataControls:NonVirtualizedItemsControl.ItemTemplate>
                                    <DataTemplate x:DataType="local:ChronicDataModel">
                                        <telerikPrimitives:RadBorder>
                                            <views:ChronicMainItemTemplate />
                                        </telerikPrimitives:RadBorder>
                                    </DataTemplate>
                                </telerikDataControls:NonVirtualizedItemsControl.ItemTemplate>
                            </telerikDataControls:NonVirtualizedItemsControl>

                        </Grid>
                    </Frame>
                </telerikListView:ListViewTemplateCell.View>
            </telerikListView:ListViewTemplateCell>
        </DataTemplate>
    </telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
</code>```


问:
Showing scraped information in pairs
I'm trying to scrape a website for stock information.  It should show me the 'size' followed by the 'quantity' available.

```<code>element_size_name = browser.find_elements_by_class_name('itemSize')
element_qty_name = browser.find_elements_by_class_name('quantity')
for e in element_size_name:
    print(e.text)
for q in element_qty_name:
    print(q.text)
</code>```

The above code gives me the following output:

```<code>>XL
>2XL
>5 Backorderable (Available: 06/02/2020)
>0 Backorderable (Available: 06/09/2020)
</code>```

How can I put the first line '5 Backorderable (Available: 06/02/2020)' next to the XL and so on.
I've tried so many different things that give me totally different outputs

答:
Try builtin zip() function:

```<code>element_size_name = browser.find_elements_by_class_name('itemSize')
element_qty_name = browser.find_elements_by_class_name('quantity')

for e, q in zip(element_size_name, element_qty_name):
    print(e.text, q.text)
</code>```

Test with "hard-coded" values:

```<code>element_size_name = ['XL', '2XL']
element_qty_name = ['5 Backorderable (Available: 06/02/2020)', '0 Backorderable (Available: 06/09/2020)']

for e, q in zip(element_size_name, element_qty_name):
    print(e, q)
</code>```

Prints:

```<code>XL 5 Backorderable (Available: 06/02/2020)
2XL 0 Backorderable (Available: 06/09/2020)
</code>```

Title: Showing scraped information in pairs

Body:
I'm trying to scrape a website for stock information.  It should show me the 'size' followed by the 'quantity' available.

element_size_name = browser.find_elements_by_class_name('itemSize')
element_qty_name = browser.find_elements_by_class_name('quantity')
for e in element_size_name:
    print(e.text)
for q in element_qty_name:
    print(q.text)

The above code gives me the following output:

>XL
>2XL
>5 Backorderable (Available: 06/02/2020)
>0 Backorderable (Available: 06/09/2020)

How can I put the first line '5 Backorderable (Available: 06/02/2020)' next to the XL and so on.
I've tried so many different things that give me totally different outputs

Body:
Try builtin zip() function:

element_size_name = browser.find_elements_by_class_name('itemSize')
element_qty_name = browser.find_elements_by_class_name('quantity')

for e, q in zip(element_size_name, element_qty_name):
    print(e.text, q.text)

Test with "hard-coded" values:

element_size_name = ['XL', '2XL']
element_qty_name = ['5 Backorderable (Available: 06/02/2020)', '0 Backorderable (Available: 06/09/2020)']

for e, q in zip(element_size_name, element_qty_name):
    print(e, q)

Prints:

XL 5 Backorderable (Available: 06/02/2020)
2XL 0 Backorderable (Available: 06/09/2020)


问:
How to remove keys from a params array of hashes
I have a list of params.

I have a sales_attributes key, which can contain an unlimited array of hashes.

I'm trying to remove the name and code keys and values from each sales_attributes array.

I tried iterating over each sales_attributes and doing delete, except or reject, but they only return the sales_attributes instead of the original param list. I want to return the exact same list as below, but not including the name or code key/values.

I looked at quite a few other posts on here and nothing has worked so far.

```<code><ActionController::Parameters {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
[<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first",
"code"=>"G32"} permitted: true>, <ActionController::Parameters
{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33"} permitted: true>,
<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34"} permitted: true>]} permitted: true>
</code>```

答:
In Rails, the general philosophy with parameters is that you should whitelist attributes to maintain more control over what you are exposing, instead of blacklisting and possibly accidentally exposing something private in the future.

Along those lines, you can cherry-pick all the attributes in the :sale_attributes array, except those you don't want and permit access to those alone:

```<code># abbreviated parameters, from @Cary Swoveland
params = ActionController::Parameters.new({
  "patient_id"=>"22", "sales_attributes"=>[
    { "type"=>"Product1", "price"=>"0", "name"=>"first", "code"=>"G32" },
    { "type"=>"Product2", "price"=>"1", "name"=>"second", "code"=>"G33" },
    { "type"=>"Product3", "price"=>"3", "name"=>"third", "code"=>"G34" }
  ]
})

params.permit(:patient_id, sales_attributes: [:type, :price])
# => <ActionController::Parameters {"patient_id"=>"22",
    "sales_attributes"=>[
      <ActionController::Parameters {"type"=>"Product1", "price"=>"0"} permitted: true>,
      <ActionController::Parameters {"type"=>"Product2", "price"=>"1"} permitted: true>,
      <ActionController::Parameters {"type"=>"Product3", "price"=>"3"} permitted: true>]} permitted: true>
</code>```

Body:
I have a list of params.

I have a sales_attributes key, which can contain an unlimited array of hashes.

I'm trying to remove the name and code keys and values from each sales_attributes array.

I tried iterating over each sales_attributes and doing delete, except or reject, but they only return the sales_attributes instead of the original param list. I want to return the exact same list as below, but not including the name or code key/values.

I looked at quite a few other posts on here and nothing has worked so far.

<ActionController::Parameters {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
[<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first",
"code"=>"G32"} permitted: true>, <ActionController::Parameters
{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33"} permitted: true>,
<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34"} permitted: true>]} permitted: true>

Body:
In Rails, the general philosophy with parameters is that you should whitelist attributes to maintain more control over what you are exposing, instead of blacklisting and possibly accidentally exposing something private in the future.

Along those lines, you can cherry-pick all the attributes in the :sale_attributes array, except those you don't want and permit access to those alone:

# abbreviated parameters, from @Cary Swoveland
params = ActionController::Parameters.new({
  "patient_id"=>"22", "sales_attributes"=>[
    { "type"=>"Product1", "price"=>"0", "name"=>"first", "code"=>"G32" },
    { "type"=>"Product2", "price"=>"1", "name"=>"second", "code"=>"G33" },
    { "type"=>"Product3", "price"=>"3", "name"=>"third", "code"=>"G34" }
  ]
})

params.permit(:patient_id, sales_attributes: [:type, :price])
# => <ActionController::Parameters {"patient_id"=>"22",
    "sales_attributes"=>[
      <ActionController::Parameters {"type"=>"Product1", "price"=>"0"} permitted: true>,
      <ActionController::Parameters {"type"=>"Product2", "price"=>"1"} permitted: true>,
      <ActionController::Parameters {"type"=>"Product3", "price"=>"3"} permitted: true>]} permitted: true>