问:
How to edit or add one row at a time using reactive forms in angular8
I have a list of data, when i click on rows, all the rows are editable and when i click on edit button of the expanded row, all the rows will have the same value as in the first row, but that shouldnt happen.One row can be editable at a table, when clicked on edit button in the expanded row, add new should also not be done. But i am going wrong somewhere, can anyone help me.

DEMO:

DEMO

TS:

```<code>eoEdit(eo) {
    console.log(eo)
    this.eoDetailsList = eo
   this.hideEoView = false;
   this.initEoForm()
  }
</code>```

HTML:

```<code> <table class="table table-hover accordion-table">
        <thead>
            <tr>
                <th></th>
                <th scope="col" *ngFor="let field of eoListDetails" (click)="sortEoList(field.param)">
                    {{field.displayName}}
                    <i class="{{field.icon}}" aria-hidden="true"></i>
                </th>
                <th scope="col" class="width75"></th>
            </tr>
        </thead>
        <tbody>
            <ng-container *ngFor="let eo of eoList">
                <tr>
                    <td (click)="editEo(eo)"><a class="accordion-toggle" data-toggle="collapse" href="#row_{{eo.eoid}}"><i
                                class="fas fa-plus-circle"></i></a></td>
                    <td *ngFor="let field of eoListDetails" class="{{field.class}}">
                        {{eo[field.param]}}
                    </td>
                    <td><button class="btn btn-outline-primary btn-table" title="Request Update"><i
                                class="far fa-paper-plane"></i></button>
                        <button type="button" class="btn btn-outline-primary btn-table" title="View Dec Page"><i
                                class="fas fa-eye"></i></button></td>

                </tr>
                <tr>
                    <td colspan="6" class="hidden-row">
                        <div class="accordion-wrapper pt-3 px-3 collapse" id="row_{{eo.eoid}}">
                            <div class="row" *ngIf="hideEoView">
                                <div class="col">
                                    <div class="form-group">
                                        <label for="">Legal Liability Limit - Each Loss <span
                                                class="text-danger">*</span></label>
                                        <p class="form-control-plaintext font-weight-bold">{{eo.legalLiabilityLoss}}</p>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="form-group">
                                        <label for="">Legal Liability Limit - Aggregate <span
                                                class="text-danger">*</span></label>
                                        <p class="form-control-plaintext font-weight-bold">{{eo.legalLiabilityAggregate}}</p>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="form-group">
                                        <label for="">Deductible - Each Loss <span class="text-danger">*</span></label>
                                        <p class="form-control-plaintext font-weight-bold">{{eo.deductibleLoss}}</p>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="form-group">
                                        <label for="">Deductible - Aggregate <span class="text-danger">*</span></label>
                                        <p class="form-control-plaintext font-weight-bold">{{eo.deductibleAggregate}}</p>
                                    </div>
                                </div>
                            </div>
                            <div class="row" *ngIf="hideEoView">
                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="">Update Requested</label>
                                        <p class="form-control-plaintext font-weight-bold">{{eo.effectivedate}}</p>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="">Update Received</label>
                                        <p class="form-control-plaintext font-weight-bold">{{eo.updateReceived}}{{eo.updateReceivedHours}}</p>
                                    </div>
                                </div>
                            </div>
                            <div *ngIf="!hideEoView">
                            <form *ngIf="eoInfoForm && eoDetailsList" [formGroup]="eoInfoForm">
                                <div class="row">
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="">E&O Carrier <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" placeholder="E&O Carrier" formControlName="eoCarrier">
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="">Policy Number <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" placeholder="Policy Number" formControlName="policyNumber">
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="">Effective Date <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control onlyDate" placeholder="MM/DD/YYYY"
                                                formControlName="effectiveDate">
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="">Expiration Date <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control onlyDate" placeholder="MM/DD/YYYY"
                                                formControlName="expirationDate">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="">Legal Liability Limit - Each Loss <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" placeholder="Legal Liability Limit - Each Loss"
                                                formControlName="legalLiabilityLimitEachLoss">
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="">Legal Liability Limit - Aggregate <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" placeholder="Legal Liability Limit - Aggregate"
                                                formControlName="legalLiabilityLimitAggregate">
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="">Deductible - Each Loss <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" placeholder="Deductible - Each Loss"
                                                formControlName="deductibleEachLoss">
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="form-group">
                                            <label for="">Deductible - Aggregate <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" placeholder="Deductible - Aggregate"
                                                formControlName="deductibleAggregate">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-6">
                                        <div class="form-group">
                                            <label for="">Update Requested</label>
                                            <p class="form-control-plaintext font-weight-bold">12/19/19 4:19 PM jcargile</p>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="form-group" formGroupName="updateReceived">
                                            <label for="">Update Received</label>
                                            <div class="input-group">
                                                <input type="text" class="form-control onlyDate" placeholder="MM/DD/YYYY"
                                                    formControlName="date">
                                                <input type="text" class="form-control onlyTime" placeholder="hh:mm AM/PM"
                                                    formControlName="time">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="col d-flex justify-content-end align-items-end">
                            <div class="form-group">
                                <button class="btn btn-primary min-w100" (click)="eoDetailsList ? saveDetails() : eoEdit(eo)">{{eoDetailsList ? 'Save' : 'Edit'}}</button>
                            </div>
                        </div>
                        </div>

                    </td>
                </tr>
            </ng-container>
        </tbody>
    </table>
</code>```

答: You are using common controller eoDetailsList to ensure it is editable or not. That controller is affecting of the related functions in your project. The easiest way is controller for each task, like editable: true or editable: false. It will not affect whole projects rather than let you allow to edit the particular row.

Body:
I have a list of data, when i click on rows, all the rows are editable and when i click on edit button of the expanded row, all the rows will have the same value as in the first row, but that shouldnt happen.One row can be editable at a table, when clicked on edit button in the expanded row, add new should also not be done. But i am going wrong somewhere, can anyone help me.

DEMO:

DEMO

TS:

eoEdit(eo) {
    console.log(eo)
    this.eoDetailsList = eo
   this.hideEoView = false;
   this.initEoForm()
  }

HTML:

                    {{field.displayName}}

            <ng-container *ngFor="let eo of eoList">

                        {{eo[field.param]}}

                    <button class="btn btn-outline-primary btn-table" title="Request Update"></button>
                        <button type="button" class="btn btn-outline-primary btn-table" title="View Dec Page"></button>

                                        Legal Liability Limit - Each Loss *

{{eo.legalLiabilityLoss}}

                                        Legal Liability Limit - Aggregate *

{{eo.legalLiabilityAggregate}}

                                        Deductible - Each Loss *

{{eo.deductibleLoss}}

                                        Deductible - Aggregate *

{{eo.deductibleAggregate}}

                                        Update Requested

{{eo.effectivedate}}

                                        Update Received

{{eo.updateReceived}}{{eo.updateReceivedHours}}

                            <form *ngIf="eoInfoForm && eoDetailsList" [formGroup]="eoInfoForm">

                                            E&O Carrier *
                                            <input type="text" class="form-control" placeholder="E&O Carrier" formControlName="eoCarrier">

                                            Policy Number *
                                            <input type="text" class="form-control" placeholder="Policy Number" formControlName="policyNumber">

                                            Effective Date *
                                            <input type="text" class="form-control onlyDate" placeholder="MM/DD/YYYY"
                                                formControlName="effectiveDate">

                                            Expiration Date *
                                            <input type="text" class="form-control onlyDate" placeholder="MM/DD/YYYY"
                                                formControlName="expirationDate">

                                            Legal Liability Limit - Each Loss *
                                            <input type="text" class="form-control" placeholder="Legal Liability Limit - Each Loss"
                                                formControlName="legalLiabilityLimitEachLoss">

                                            Legal Liability Limit - Aggregate *
                                            <input type="text" class="form-control" placeholder="Legal Liability Limit - Aggregate"
                                                formControlName="legalLiabilityLimitAggregate">

                                            Deductible - Each Loss *
                                            <input type="text" class="form-control" placeholder="Deductible - Each Loss"
                                                formControlName="deductibleEachLoss">

                                            Deductible - Aggregate *
                                            <input type="text" class="form-control" placeholder="Deductible - Aggregate"
                                                formControlName="deductibleAggregate">

                                            Update Requested

12/19/19 4:19 PM jcargile

                                            Update Received

                                                <input type="text" class="form-control onlyDate" placeholder="MM/DD/YYYY"
                                                    formControlName="date">
                                                <input type="text" class="form-control onlyTime" placeholder="hh:mm AM/PM"
                                                    formControlName="time">

                            </form>

                                <button class="btn btn-primary min-w100" (click)="eoDetailsList ? saveDetails() : eoEdit(eo)">{{eoDetailsList ? 'Save' : 'Edit'}}</button>

            </ng-container>


来源: stackexchange

问:
How can I catch a marshalling error in Go?
I have an API that is expecting a "username":"string" request body, I am unmarshalling the request body into a user struct that matches what I am expecting. My code does not throw an error on mismatched struct data. Is there a function I could use instead of json.Unmarshal? If not how would I be able to catch a 400 error in this case?  (I have also tried using json.decoder)

Here is my code:

```<code>type User struct {
   Username string `json:"username" gorm:"primary_key;Column:username"`
}

var user models.User

body, err := ioutil.ReadAll(r.Body)
if err = json.Unmarshal(body, &user); err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}
</code>```

答:
You can use the DisallowUnknownFields option of json.Decoder to cause an error when the decoder finds a field that is not in the struct:

DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

ContentLicense: CC BY-SA 4.0

Body:
I have an API that is expecting a "username":"string" request body, I am unmarshalling the request body into a user struct that matches what I am expecting. My code does not throw an error on mismatched struct data. Is there a function I could use instead of json.Unmarshal? If not how would I be able to catch a 400 error in this case?  (I have also tried using json.decoder)

Here is my code:

type User struct {
   Username string `json:"username" gorm:"primary_key;Column:username"`
}

var user models.User

body, err := ioutil.ReadAll(r.Body)
if err = json.Unmarshal(body, &user); err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}


问:
Django-admin.py not being recognized suddenly
I tried starting a new Django project yesterday but when I did "django-admin.py startproject projectname" I got an error stating: "django-admin.py is not recognized as an internal or external command." The strange thing is, when I first installed Django, I made a few projects and everything worked fine. But now after going back a few months later it has suddenly stopped working.

I've tried looking around for an answer and all I could find is that this typically has to do with the system path settings, however, I know that I have the proper paths set up so I don't understand what's happening. Does anybody have any idea what's going on?

答:
As per this link you may try,

python -m django <command> [options].

Where python is the version of the python you are using.

Usage python -m django startproject <projectname>.

ContentLicense: CC BY-SA 3.0


问:
South doesn't create default permissions on new models in time for latter migrations to use them
I'm not 100% sure I'm doing this right, but I think I've found an issue where auth.Permission objects aren't being created soon enough for migrations to use them when you initialize a DB from scratch.

The important details:

I'm trying to initialize a Django DB from scratch using ./manage.py syncdb --migrate --noinput

I have 11 migrations in my chain

The 1st migration creates a new model called myapp.CompanyAccount

The 9th migration tries to fetch the permission myapp.change_companyaccount with:

p = orm[ "auth.Permission" ].objects.get( codename = "change_companyaccount" )

At that point, an exception is raised:

django.contrib.auth.models.DoesNotExist: Permission matching query does not exist

I had assumed that the default permissions that are defined for every object (as per http://docs.djangoproject.com/en/dev/topics/auth/#default-permissions) would have been created by the time the 1st migration finished, but it doesn't appear that they are.  If I re-run the migration after the exception, it works the second time because apparently the permission now exists and the 9th migration can execute without error.

Is there anything that can be done to "flush" everything sometime before the 9th migration runs so that the whole thing can run in a single pass without bailing out?

Thanks for any help / advice.

EDIT: In response to John's comment below, I found out that the following command-line sequence will work:

./manage.py syncdb (this initializes the default Django tables)

./manage.py migrate myapp 0001 (this causes the CompanyAccount table to be created)

./manage.py migrate myapp (this migrates all the way to the end without error)

Unfortunately, skipping step #2 above means that you get the same exception in the 0009 migration, which tells me that my original suspicion was correct that default permissions on new models are not created by South immediately, and are somehow only pushed into the database when the entire migration chain finishes.

This is better than where I was (I'm at least avoiding exceptions now) but I still need to manually segment the migration around the creation of new models that latter migrations might need to touch the permissions of, so this isn't a complete solution.

答:
Don't you have to run the default "syncdb" on a virgin database in order to create the South migration table; before you can use south. Are you doing that?  It typically creates the permissions table at that time since you have django.contrib.auth in your INSTALLED_APPS.

http://south.aeracode.org/docs/installation.html#configuring-your-django-installation


问:
Unhandled Promise rejection: this._next is not a function : Zone in @angular/fire/messaging
When I am receiving firebase push notifications in the foreground, by using @angular/fire/messaging. The method is:

```<code>  this.angularFireMessaging.messages.subscribe(
      (payload) => {
        console.log("new message received. ", payload);
        this.currentMessage.next(payload);
      })
</code>```

Let me share my complete code: PushNotificationsService Code I have written.

My Angular-cli versions:

```<code>Angular CLI: 8.1.3
Node: 12.4.0
OS: linux x64
Angular: 8.1.3
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.801.3
@angular-devkit/build-angular     0.801.3
@angular-devkit/build-optimizer   0.801.3
@angular-devkit/build-webpack     0.801.3
@angular-devkit/core              8.1.3
@angular-devkit/schematics        8.1.3
@angular/fire                     5.3.0
@ngtools/webpack                  8.1.3
@schematics/angular               8.1.3
@schematics/update                0.801.3
rxjs                              6.4.0
typescript                        3.4.5
webpack                           4.35.2
</code>```

Let me share my package.json files: package.json

I am getting the below error when I receive message in the foreground:

```<code>Unhandled Promise rejection: this._next is not a function ; Zone: <root> ; Task: ServiceWorkerContainer.addEventListener:message ; Value: TypeError: "this._next is not a function"
    next RxJS
    messageEventListener index.esm.js:1046
    step tslib.es6.js:99
    verb tslib.es6.js:80
    __awaiter tslib.es6.js:73
    ZoneAwarePromise Angular
    __awaiter tslib.es6.js:69
    messageEventListener index.esm.js:1035
    WindowController index.esm.js:876
    Angular 5
 next@http://localhost:4200/vendor.js:111323:18
./node_modules/@firebase/messaging/dist/index.esm.js/WindowController.prototype.messageEventListener/</<@http://localhost:4200/firebase-messaging.js:2418:34
step@http://localhost:4200/vendor.js:127272:23
verb/<@http://localhost:4200/vendor.js:127253:53
__awaiter/<@http://localhost:4200/vendor.js:127246:71
ZoneAwarePromise@http://localhost:4200/polyfills.js:3882:29
__awaiter@http://localhost:4200/vendor.js:127242:12
./node_modules/@firebase/messaging/dist/index.esm.js/WindowController.prototype.messageEventListener@http://localhost:4200/firebase-messaging.js:2407:71
WindowController/<@http://localhost:4200/firebase-messaging.js:2248:26
invokeTask@http://localhost:4200/polyfills.js:3397:31
runTask@http://localhost:4200/polyfills.js:3174:47
invokeTask@http://localhost:4200/polyfills.js:3471:34
invokeTask@http://localhost:4200/polyfills.js:4609:14
globalZoneAwareCallback@http://localhost:4200/polyfills.js:4635:27
</code>```

Any help is highly appreciable! CODE: GITHUB REPO LINK

I have update my secret key from firebase in the GitHub code

答:
Yes What I have realized that i had using the wrong version of "@angular/fire": "^5.3.0" which is not compatible with "firebase": "^7.6.2", in my package.json.

So, What i have did-

In firebase-messaging-sw.js or the service worker file?

importScripts('https://www.gstatic.com/firebasejs/5.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.0/firebase-messaging.js');

should have the same version with your firebase on package.json

"dependencies": {
...
"firebase": "^5.0.0",
"@angular/fire": "^5.0.0",
...
}

And it is working like a charm.

Body:
When I am receiving firebase push notifications in the foreground, by using @angular/fire/messaging. The method is:

  this.angularFireMessaging.messages.subscribe(
      (payload) => {
        console.log("new message received. ", payload);
        this.currentMessage.next(payload);
      })

Let me share my complete code: PushNotificationsService Code I have written.

My Angular-cli versions:

Angular CLI: 8.1.3
Node: 12.4.0
OS: linux x64
Angular: 8.1.3
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.801.3
@angular-devkit/build-angular     0.801.3
@angular-devkit/build-optimizer   0.801.3
@angular-devkit/build-webpack     0.801.3
@angular-devkit/core              8.1.3
@angular-devkit/schematics        8.1.3
@angular/fire                     5.3.0
@ngtools/webpack                  8.1.3
@schematics/angular               8.1.3
@schematics/update                0.801.3
rxjs                              6.4.0
typescript                        3.4.5
webpack                           4.35.2

Let me share my package.json files: package.json

I am getting the below error when I receive message in the foreground:

Unhandled Promise rejection: this._next is not a function ; Zone: <root> ; Task: ServiceWorkerContainer.addEventListener:message ; Value: TypeError: "this._next is not a function"
    next RxJS
    messageEventListener index.esm.js:1046
    step tslib.es6.js:99
    verb tslib.es6.js:80
    __awaiter tslib.es6.js:73
    ZoneAwarePromise Angular
    __awaiter tslib.es6.js:69
    messageEventListener index.esm.js:1035
    WindowController index.esm.js:876
    Angular 5
 next@http://localhost:4200/vendor.js:111323:18
./node_modules/@firebase/messaging/dist/index.esm.js/WindowController.prototype.messageEventListener/</<@http://localhost:4200/firebase-messaging.js:2418:34
step@http://localhost:4200/vendor.js:127272:23
verb/<@http://localhost:4200/vendor.js:127253:53
__awaiter/<@http://localhost:4200/vendor.js:127246:71
ZoneAwarePromise@http://localhost:4200/polyfills.js:3882:29
__awaiter@http://localhost:4200/vendor.js:127242:12
./node_modules/@firebase/messaging/dist/index.esm.js/WindowController.prototype.messageEventListener@http://localhost:4200/firebase-messaging.js:2407:71
WindowController/<@http://localhost:4200/firebase-messaging.js:2248:26
invokeTask@http://localhost:4200/polyfills.js:3397:31
runTask@http://localhost:4200/polyfills.js:3174:47
invokeTask@http://localhost:4200/polyfills.js:3471:34
invokeTask@http://localhost:4200/polyfills.js:4609:14
globalZoneAwareCallback@http://localhost:4200/polyfills.js:4635:27

Any help is highly appreciable! CODE: GITHUB REPO LINK

I have update my secret key from firebase in the GitHub code


问:
How to get python code samples on Youtube API V3 with API KEY only
I want to get python samples on using an API KEY to interact with Google's Youtube API V3 and get the list of videos of a specific channel, I don't want to use OAuth, I want to use API KEY credentials.

The API explorer shows both credential types but the code samples only use the OAuth method.

I want to have a python script listing a channels published videos.

答:
I finally figured how to do this from the documentation of the python pakcage google-api-client from here.

This is how to build the service:

```<code>youtube = googleapiclient.discovery.build(
               api_service_name,
               api_version,
               developerKey='YOUR_API_KEY')
</code>```

and then the service will use the provided API to authenticate with Google.

Body:
I finally figured how to do this from the documentation of the python pakcage google-api-client from here.

This is how to build the service:

youtube = googleapiclient.discovery.build(
               api_service_name,
               api_version,
               developerKey='YOUR_API_KEY')

and then the service will use the provided API to authenticate with Google.


问:
XML preserve carriage return (CR) when loading XDocument
I have the following XML file which contains carriage return characters (CR):

After loading the XDocument,

```<code>XDocument xDocument = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
</code>```

the (CR) characters are converted to carriage return, line feed characters (CR)(LF):

Is there a way to prevent those characters conversion?

答:
As Michael Kay said, \r, \n and \r\n are treated as equivalent.

Therefore, if you need to have a separate \r character in the xml, then you must to write it as
 entity.

Let's create a test xml with the content we need.

```<code>string s = "<root><a/>
\r\n<b/>
<c/>\r\n</root>";

File.WriteAllText("test.xml", s, Encoding.UTF8);
</code>```

Now let's read it with preserve whitespace characters and see what they are converted to.

```<code>var doc = XDocument.Load("test.xml", LoadOptions.PreserveWhitespace);

foreach (var node in doc.DescendantNodes())
{
    if (node is XElement elem)
    {
        Console.WriteLine("Element: " + elem.Name);
    }
    if (node is XText text)
    {
        Console.WriteLine("Text: " +
            string.Join(", ", text.Value.Select(c => ((int)c).ToString("X"))));
    }
}
</code>```

The result will be as follows.

```<code>Element: root
Element: a
Text: D, A
Element: b
Text: D
Element: c
Text: A
</code>```

As you can see, whitespace characters are stored in XText nodes.

The
 entity is represented as the \r (D character in hexadecimal representation).

The newline \r\n is represented as a single character \n (A in hexadecimal representation).

Therefore, you can parse the contents of XText nodes and manually define their contents.

Body:
I have the following XML file which contains carriage return characters (CR):

After loading the XDocument,

XDocument xDocument = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);

the (CR) characters are converted to carriage return, line feed characters (CR)(LF):

Is there a way to prevent those characters conversion?

Body:
As Michael Kay said, \r, \n and \r\n are treated as equivalent.

Therefore, if you need to have a separate \r character in the xml, then you must to write it as &#x0D; entity.

Let's create a test xml with the content we need.

string s = "<root><a/>&#x0D;\r\n<b/>&#x0D;<c/>\r\n</root>";

File.WriteAllText("test.xml", s, Encoding.UTF8);

Now let's read it with preserve whitespace characters and see what they are converted to.

var doc = XDocument.Load("test.xml", LoadOptions.PreserveWhitespace);

foreach (var node in doc.DescendantNodes())
{
    if (node is XElement elem)
    {
        Console.WriteLine("Element: " + elem.Name);
    }
    if (node is XText text)
    {
        Console.WriteLine("Text: " +
            string.Join(", ", text.Value.Select(c => ((int)c).ToString("X"))));
    }
}

The result will be as follows.

Element: root
Element: a
Text: D, A
Element: b
Text: D
Element: c
Text: A

As you can see, whitespace characters are stored in XText nodes.

The &#x0D; entity is represented as the \r (D character in hexadecimal representation).

The newline \r\n is represented as a single character \n (A in hexadecimal representation).

Therefore, you can parse the contents of XText nodes and manually define their contents.


问:
How does malloc() know you want to use the block of memory it supplies as an array?
If malloc() returns a pointer to a single block of memory, how can it be used to store multiple values contiguously and allow access to each one using the subscript operator, acting as a pointer to an array?

If I were to try and change the "second element" of an integer by subscripting its address, it would cause undefined behaviour. As malloc() returns the pointer to a single block of memory, shouldn't the pointer it returns refer to the entire block, and thus subscripting it should access the garbage value next to it in memory?

Furthermore, the allocated memory can also be used to store a single value, but only up to the size of the type the pointer is cast to, not to that of the allocated block of memory.

Is all this something to do with the type the pointer is cast to after being returned? Could someone point me in the right direction?

答:
I think your misunderstanding is here:

As malloc() returns the pointer to a single block of memory, shouldn't the pointer it returns refer to the entire block, and thus subscripting it should access the garbage value next to it in memory?

Indeed if you do p = malloc(n) and p has type "pointer to some type of size n", then p[1] is an out-of-bounds array access. However, normally when you do p = malloc(n) to allocate an array, the type of p is not a pointer to the array (of size n), but a pointer to the first element of the array. That is, instead of

```<code>char (*p)[500] = malloc(500);
</code>```

you do:

```<code>char *p = malloc(500);
</code>```

and in this case p[1] is perfectly valid. Note that with the first, unusual, form, you could still do (*p)[1] or p[0][1] and have it be valid.

Body:
I think your misunderstanding is here:

As malloc() returns the pointer to a single block of memory, shouldn't the pointer it returns refer to the entire block, and thus subscripting it should access the garbage value next to it in memory?

Indeed if you do p = malloc(n) and p has type "pointer to some type of size n", then p[1] is an out-of-bounds array access. However, normally when you do p = malloc(n) to allocate an array, the type of p is not a pointer to the array (of size n), but a pointer to the first element of the array. That is, instead of

char (*p)[500] = malloc(500);

you do:

char *p = malloc(500);

and in this case p[1] is perfectly valid. Note that with the first, unusual, form, you could still do (*p)[1] or p[0][1] and have it be valid.


问:
If colours are accessible, will a gradient between those colours be accessible?
I work on websites where accessibility is an absolute must have, we aim for at least AA standard. Typically we use resources such as https://contrast-ratio.com and https://contrastchecker.com to test a background colour against black or white text.

In this instance let's take white (#fff) text at a size of 18px.
Colour one: #546FAF has a ratio of 4.92
Colour two: #B349B1 has a ratio of 4.66

If I made a linear gradient between those two colours as a background, would #fff text at 18px be safe accessibility wise? I've tried colour picking colours near the text that look close, but hoping it's a simple answer of during that gradient it would never go below the 4.5 ratio.

Thanks!

答:
Is your text bold too? If so, the min color contrast requirement would then be changed to 3:1 since the text would be large text (18px+bold).

According to Webaim, “Large text is defined as 14 point (typically 18.66px) and bold or larger, or 18 point (typically 24px) or larger.”

I know you’re aware of contrast checker but I want to call out that a tool can actually tell you whether the contrast is accessible on that gradient background if you test your content on that gradient using accessibility insights for web by Microsoft. The Fastpass feature will tell you that in seconds.

Lastly, the guidelines intent is to make it accessible to everyone so if despite the numbers and thresholds if it’s hard to read, tune it a better contrast ratio so that it is easily readable. E.g., most designs on csszengarden.com website are accessible according to these automated tools but in practical it is not really accessible.


问:
How much memory does an inet stream socket use in Node.js?
Of course data can be buffered and grow if the client is too slow to read the server's writes [1].

But what is the default buffer size?  I assume it's whatever is configured in /proc/sys/net/ipv4/tcp_rmem and tcp_wmem (assuming Linux)...

I'm trying to do some basic capacity planning. If I have a VPS with 512 MB RAM, and I assume the OS et al will use ~ 100MB, my app has ~ 400MB for whatever it wants to do.  If each connected client (regular old TCP/IP socket) requires say 8KB (4KB read, 4KB write) by default, I have capacity for 400MB / 8KB = ~ 50000 clients.

[1] http://nodejs.org/docs/v0.4.7/api/all.html#socket.bufferSize

答:
I don't know off the top of my head and it probably varies from platform to platform but here's how you can find out!

Use this code:

```<code>var net = require('net');

net.createServer(function (socket) {
    socket.on('data', function(data) {
      console.log('chunk length: ' + data.length);
    });
}).listen(function() {
    console.log("Server listening on %j", this.address());
});
</code>```

And then cat a large file (like an ISO) through 'nc localhost $port' using the port number that the script spits out when it starts up, and watch the output to see what the largest chunk size is. On my OS X machine, it looks like the largest buffer is 40960 bytes, but it might be different on yours.

Body:
I don't know off the top of my head and it probably varies from platform to platform but here's how you can find out!

Use this code:

var net = require('net');

net.createServer(function (socket) {
    socket.on('data', function(data) {
      console.log('chunk length: ' + data.length);
    });
}).listen(function() {
    console.log("Server listening on %j", this.address());
});

And then cat a large file (like an ISO) through 'nc localhost $port' using the port number that the script spits out when it starts up, and watch the output to see what the largest chunk size is. On my OS X machine, it looks like the largest buffer is 40960 bytes, but it might be different on yours.


问:
Can I save label title in laravel?
Is there a way to save label title in laravel.

```<code><label for="name">Name</label>
</code>```

Suppose I want to save "Name" in database.

答:
according to your structure, the label name comes from db, so when you are rendering the blade, you can make a hidden input with value of label name like below:</p>

```<code><form action="{{ route('sampleRoute') }}" >
 <label for="{{ $DBVARIABLE }}">{{ $DBVARIABLE }}</label>
 <input type="text" name="{{ $DBVARIABLE }}" id="{{ $DBVARIABLE }}" value="{{ $DBVARIABLE }}" style="visibility: hidden;">
 <input type="submit" value="Submit">
</form>
</code>```

Title: Can I save label title in laravel?

Body:
Is there a way to save label title in laravel.

Name

Suppose I want to save "Name" in database.

Body:
according to your structure, the label name comes from db, so when you are rendering the blade, you can make a hidden input with value of label name like below:

<form action="{{ route('sampleRoute') }}" >
 <label for="{{ $DBVARIABLE }}">{{ $DBVARIABLE }}</label>
 <input type="text" name="{{ $DBVARIABLE }}" id="{{ $DBVARIABLE }}" value="{{ $DBVARIABLE }}" style="visibility: hidden;">
 <input type="submit" value="Submit">
</form>


问:
PHP + Simple HTML DOM: Select a tag inside a div with class inside another div with class
In PHP: Simple HTML DOM, How do I select all  tag that are inside div with class abc, which are inside div with class 123:

```<code><div class="123">
 <div class="abc">
  <strong>Text</strong>
 </div>
</div>
</code>```

答:
You need to use a selector like div.123 div.abc strong and get the first element of the result. Here is a working example:

```<code><?php

require 'simple_html_dom.php';

$html =<<<html
<div class="123">
 <div class="abc">
  <strong>Text</strong>
 </div>
</div>
html;

$dom = str_get_html($html);
$el = $dom->find('div.123 div.abc strong', 0);
print $el;
print "\n";
print $el->innertext;
</code>```

Result:

```<code><strong>Text</strong>
Text
</code>```

You can refer to the manual for a better understanding of how selectors work.

Body:
In PHP: Simple HTML DOM, How do I select all  tag that are inside div with class abc, which are inside div with class 123:

  Text

Body:
You need to use a selector like div.123 div.abc strong and get the first element of the result. Here is a working example:

<?php

require 'simple_html_dom.php';

$html =<<<html
<div class="123">
 <div class="abc">
  <strong>Text</strong>
 </div>
</div>
html;

$dom = str_get_html($html);
$el = $dom->find('div.123 div.abc strong', 0);
print $el;
print "\n";
print $el->innertext;

Result:

<strong>Text</strong>
Text

You can refer to the manual for a better understanding of how selectors work.


问:
Should a separate event be allocated for an asynchronous delegate?
For asynchronous delegates in the code, I do the following everywhere:

```<code>public class SomeCaller
{
    public event Action SomeChanged;
    public event Func<Task> SomeChangedAsync;

    //If in Caller async method
    public async Task SomeMethodAsync()
    {
        SomeChanged?.Invoke();
        if (SomeChangedAsync != null)
            await SomeChangedAsync();
    }

    //if in Caller synchronous method
    public void SomeMethod()
    {
        SomeChanged?.Invoke();
        if (SomeChangedAsync != null)
            Task.Run(async () => await SomeChangedAsync());
    }
}
</code>```

Is there any point in such a solution (to separate the event for async) or is this an example of poor design?
If this is bad, then I would like to understand why and how best to call async delegates?

答:
The invocation of the SomeChangedAsync event is not implemented correctly. In case of multiple event handlers, only the last handler attached will be awaited. To await all the handlers you must get them with the method GetInvocationList, and then decide how you want to invoke and await them. Here is a sequential approach:

```<code>public async Task SomeMethodAsync()
{
    SomeChanged?.Invoke();

    Delegate[] delegates = SomeChangedAsync?.GetInvocationList();
    if (delegates != null)
    {
        var taskFactories = delegates.Cast<Func<Task>>().ToArray();
        foreach (var taskFactory in taskFactories)
        {
            var task = taskFactory();
            await task;
        }
    }
}
</code>```

You can also invoke and await them all at once (using Task.WhenAll), as it's suggested here.

Body:
For asynchronous delegates in the code, I do the following everywhere:

public class SomeCaller
{
    public event Action SomeChanged;
    public event Func<Task> SomeChangedAsync;

    //If in Caller async method
    public async Task SomeMethodAsync()
    {
        SomeChanged?.Invoke();
        if (SomeChangedAsync != null)
            await SomeChangedAsync();
    }

    //if in Caller synchronous method
    public void SomeMethod()
    {
        SomeChanged?.Invoke();
        if (SomeChangedAsync != null)
            Task.Run(async () => await SomeChangedAsync());
    }
}

Is there any point in such a solution (to separate the event for async) or is this an example of poor design?
If this is bad, then I would like to understand why and how best to call async delegates?

Body:
The invocation of the SomeChangedAsync event is not implemented correctly. In case of multiple event handlers, only the last handler attached will be awaited. To await all the handlers you must get them with the method GetInvocationList, and then decide how you want to invoke and await them. Here is a sequential approach:

public async Task SomeMethodAsync()
{
    SomeChanged?.Invoke();

    Delegate[] delegates = SomeChangedAsync?.GetInvocationList();
    if (delegates != null)
    {
        var taskFactories = delegates.Cast<Func<Task>>().ToArray();
        foreach (var taskFactory in taskFactories)
        {
            var task = taskFactory();
            await task;
        }
    }
}

You can also invoke and await them all at once (using Task.WhenAll), as it's suggested here.


问:
Print the key/value types of a Golang map
I am trying to print the type of a map, eg: map[int]string

```<code>func handleMap(m reflect.Value) string {

    keys := m.MapKeys()
    n := len(keys)

    keyType := reflect.ValueOf(keys).Type().Elem().String()
    valType := m.Type().Elem().String()

    return fmt.Sprintf("map[%s]%s>", keyType, valType)
}
</code>```

so if I do:

```<code>log.Println(handleMap(make(map[int]string)))
</code>```

I want to get "map[int]string"

but I can't figure out the right calls to make.

答:
```<code>func handleMap(m interface{}) string {
    return fmt.Sprintf("%T", m)
}
</code>```

Body:
I am trying to print the type of a map, eg: map[int]string

func handleMap(m reflect.Value) string {

    keys := m.MapKeys()
    n := len(keys)

    keyType := reflect.ValueOf(keys).Type().Elem().String()
    valType := m.Type().Elem().String()

    return fmt.Sprintf("map[%s]%s>", keyType, valType)
}

so if I do:

log.Println(handleMap(make(map[int]string)))

I want to get "map[int]string"

but I can't figure out the right calls to make.


问:
@angular-cli install fails with deprecated request@2.88.2: request has been deprecated (mac)
After updating node.js and npm to current LTS:

```<code>node -v
v12.16.0
</code>```

```<code>npm -v
6.13.4
</code>```

When I'm trying to install @angular-cli following the steps in the documentation, running npm install -g @angular/cli
 in the terminal stops the installation and the console output is:

```<code>npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/user/.npm-global/bin/ng -> /USERS/USER/.npm-global/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.0.2 postinstall /USERS/USER/.npm-global/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.0.2
updated 1 package in 12.202s
</code>```

And in this case, ng new project-name yields -bash: ng: command not found. Any help would be very welcome as I have a big project coming up.
Thanks all.

答: Uninstalling and installing angular cli works fine for me.

Body:
After updating node.js and npm to current LTS:

node -v
v12.16.0

npm -v
6.13.4

When I'm trying to install @angular-cli following the steps in the documentation, running npm install -g @angular/cli
 in the terminal stops the installation and the console output is:

npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/user/.npm-global/bin/ng -> /USERS/USER/.npm-global/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.0.2 postinstall /USERS/USER/.npm-global/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.0.2
updated 1 package in 12.202s

And in this case, ng new project-name yields -bash: ng: command not found. Any help would be very welcome as I have a big project coming up.
Thanks all.


问:
How to run a node.js app on Azure app service with a windows host
Trying to use Azure App Services.
From within Code I can create a new app service and deploy a html/js/css app choosing a windows host.
From within Code I can create a new app service and deploy a node.js app choosing a Linux host.

But I can't figure out how to create a new app service and deploy a node.js app choosing a windows host.  I am fairly sure it should work.  It gives no error when I deploy it, if I go to the resulting web page it gives me the "You do not have permission to view this directory or page." message.  I know about setting port 443.

You might ask, why do this?  Because I am a teacher, and Azure for students allows multiple app service instances using a windows host but only 1 on a Linux host.

答:
Referring solution mentioned here https://github.com/Azure-Samples/nodejs-docs-hello-world/issues/9

Create a web.config file at the root of the app directory.

Add the following code to web.config:

```<code><!-- indicates that the index.js file is a node.js application
to be handled by the iisnode module -->

<handlers>
  <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
</handlers>

<!-- adds index.js to the default document list to allow
URLs that only specify the application root location,
e.g. http://mysite.antarescloud.com/ -->

<defaultDocument enabled="true">
  <files>
    <add value="index.js" />
  </files>
</defaultDocument>
</code>```

You probably need change "index.js" to what initial js file name in your project.
hope it helps.

Body:
Referring solution mentioned here https://github.com/Azure-Samples/nodejs-docs-hello-world/issues/9

Create a web.config file at the root of the app directory.

Add the following code to web.config:

<!-- indicates that the index.js file is a node.js application
to be handled by the iisnode module -->

<handlers>
  <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
</handlers>

<!-- adds index.js to the default document list to allow
URLs that only specify the application root location,
e.g. http://mysite.antarescloud.com/ -->

<defaultDocument enabled="true">
  <files>
    <add value="index.js" />
  </files>
</defaultDocument>

You probably need change "index.js" to what initial js file name in your project.
hope it helps.


问:
how to solve this div overlay problem in css
How to solve div overlay problem here I've one div in this div I've added two class col-sm-6. But when I am checking responsive it will going over of the div. I don't know how to solve. can anyone please help me.

I've attch the image of the output you can see :)

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Showing 1 to 6 of 6 entries

        <button class="btn btn-link previous">Previous</button>
        <button class="btn btn-info number">1</button>
        <button class="btn btn-link next">Next</button>

```

答:
you should set the div "col-12" for mobile size in bootstrap4."col-sm-6" don't work for size less than 557px.and make your div's "float" right.

.float-right{
  float:rigth !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="block">
  <div class="row">
    <div class="col-sm-6 col-12 float-right">
      <p><strong>Showing 1 to 6 of 6 entries</strong></p>
    </div>

    <div class="col-sm-6 col-12 float-right" style="top: -8px;">
      <div class="pagination">
        <button class="btn btn-link previous">Previous</button>
        <button class="btn btn-info number">1</button>
        <button class="btn btn-link next">Next</button>
      </div>
    </div>
  </div>
</div></code>```

Body:
you should set the div "col-12" for mobile size in bootstrap4."col-sm-6" don't work for size less than 557px.and make your div's "float" right.

.float-right{
  float:rigth !important;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="block">
  <div class="row">
    <div class="col-sm-6 col-12 float-right">
      <p><strong>Showing 1 to 6 of 6 entries</strong></p>
    </div>

    <div class="col-sm-6 col-12 float-right" style="top: -8px;">
      <div class="pagination">
        <button class="btn btn-link previous">Previous</button>
        <button class="btn btn-info number">1</button>
        <button class="btn btn-link next">Next</button>
      </div>
    </div>
  </div>
</div>


问:
Do-While to ask user to repeat entire int main programme
Very new to programming and l can't find any basic explanation online or code that will work well for what l need. I have a fairly long piece of programme (approx 300 lines) it all works. This is the structure to give an idea:

```<code>#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
      //code....

    {
         //code... etc...
    }

}
</code>```

I want to ask the user to repeat the programme. If enters y, then repeat int main up to the point of asking the same repeat question again. Else to cout<< "e.g. Thank you, goodbye";

答:
```<code>#include <iostream>
#include <conio.h>

using namespace std;

//Class
class DollarToRs {
  public:

      int Dollar;
      int Rs;
      int ToRs;
      ConversionToRs() {
      cout << "Enter the amount of Dollar: ";
      cin >> Dollar;
      ToRs = Dollar * 154;
      cout << "This is the total amount in PKR: " << ToRs <<endl;
      }

};

int main()
{
  //Dollar Convertion Function
  DollarToRs convert;
  convert.ConversionToRs();

  //For Repeating Program

  int repeat;
  int exit;

  cout << "To repeat program enter 1" <<endl;
  cin >> repeat;

  while (repeat == 1) {
    convert.ConversionToRs();
    cout << "To repeat program enter 1" <<endl;
    cin >> repeat;
  }
  exit =0;

  if (exit == 0) {

  }

  getch();
  return 0;
}
</code>```

Body:
Very new to programming and l can't find any basic explanation online or code that will work well for what l need. I have a fairly long piece of programme (approx 300 lines) it all works. This is the structure to give an idea:

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
      //code....

    {
         //code... etc...
    }

}

I want to ask the user to repeat the programme. If enters y, then repeat int main up to the point of asking the same repeat question again. Else to cout<< "e.g. Thank you, goodbye";


问:
Get deltas from an array using foreach in PHP
I am trying to show some values using json api. It returns a date and some density value in numbers. Successfully, I have printed all return values from url. Now, I want to find the difference between one density value to previous day density value.

I know how to calculate the difference in normal static numbers. But, I am not sure how do I achieve this inside a foreach loop.

PHP Code:

```<code>$json_url = "https://www.example.com/api";

$json = file_get_contents($json_url);
$obj  = json_decode($json,true);
$data = $obj["data"];

foreach(array_slice($data, 0, 10) as $k) {

    echo $k["date"]." - ".$k["density"]."<br/><br/>";

}
</code>```

Current Output:

```
14-02-2020 - 110

13-02-2020 - 114

12-02-2020 - 112

11-02-2020 - 110

10-02-2020 - 105

07-02-2020 - 125

06-02-2020 - 122

05-02-2020 - 118

04-02-2020 - 119

03-02-2020 - 119
```

Expected Output:

```
14-02-2020 - 110 - Diff is -4 from Previous Date

13-02-2020 - 114 - Diff is +2 from Previous Date

12-02-2020 - 112 - Diff is +2 from Previous Date

11-02-2020 - 110 - Diff is +5 from Previous Date

10-02-2020 - 105 - Diff is -20 from Previous Date

07-02-2020 - 125 - Diff is +3 from Previous Date

06-02-2020 - 122 - Diff is +4 from Previous Date

05-02-2020 - 118 - Diff is -1 from Previous Date

04-02-2020 - 119 - No Difference - Same

03-02-2020 - 119 - No Difference - Same
```

答:
To achieve the desired effect you will need to iterate the array two elements at a time. This can't easily be done with foreach outright. So instead I will implement a generator that returns pairs of values from the array at a time.

```<code>function getPairs(Array $array) {
    reset($array);
    do {
        $a1  = current($array);
        $key = key($array);
        $a2  = next($array);
        yield [$a1, $a2];
    } while($key = key($array) !== null);
}
</code>```

You can then use this generator implementation to traverse the array, attaining the desired effect.

```<code>$array = [
    ["date" => "14-02-2020", "density" => 110],
    ["date" => "13-02-2020", "density" => 114],
    ["date" => "12-02-2020", "density" => 112],
    ["date" => "11-02-2020", "density" => 110],
    ["date" => "10-02-2020", "density" => 105],
    ["date" => "07-02-2020", "density" => 125],
    ["date" => "12-02-2020", "density" => 112],
    ["date" => "06-02-2020", "density" => 122],
    ["date" => "05-02-2020", "density" => 118],
    ["date" => "04-02-2020", "density" => 119],
    ["date" => "03-02-2020", "density" => 119],
];

foreach(getPairs($array) as [$a, $b]) {
    // We must check if $b is empty to account for end of the array
    if ($b) {
        $diff = $a["density"] - $b["density"];
    } else { // Otherwise there are no more elements to diff against
        $diff = 0;
    }
    if ($diff > 0) {
        $diff = "+$diff";
    }
    echo "{$a['date']} - {$a['density']} - Diff is $diff from Previous Date<br><br>";
}
</code>```

This should give you the desired output.

```
14-02-2020 - 110 - Diff is -4 from Previous Date

13-02-2020 - 114 - Diff is +2 from Previous Date

12-02-2020 - 112 - Diff is +2 from Previous Date

11-02-2020 - 110 - Diff is +5 from Previous Date

10-02-2020 - 105 - Diff is -20 from Previous Date

07-02-2020 - 125 - Diff is +13 from Previous Date

12-02-2020 - 112 - Diff is -10 from Previous Date

06-02-2020 - 122 - Diff is +4 from Previous Date

05-02-2020 - 118 - Diff is -1 from Previous Date

04-02-2020 - 119 - Diff is 0 from Previous Date

03-02-2020 - 119 - Diff is 0 from Previous Date
```

N.B.

Technically speaking you aren't actually getting the difference between the current date and the previous date, here. Rather, you are getting the difference between the current date and the next date. If you were getting the deltas between previous dates you wouldn't need the information from the next date at all. Instead you'd just use a temporary variable to store the last density value and diff against that with each iteration. However, I've tailored my answer to suit your expected result.

Otherwise the expected output would actually be:

```
14-02-2020 - 110 - Diff is +110 from Previous Date

13-02-2020 - 114 - Diff is +4 from Previous Date

12-02-2020 - 112 - Diff is -2 from Previous Date

11-02-2020 - 110 - Diff is -2 from Previous Date

10-02-2020 - 105 - Diff is -5 from Previous Date

07-02-2020 - 125 - Diff is +20 from Previous Date

12-02-2020 - 112 - Diff is -13 from Previous Date

06-02-2020 - 122 - Diff is +10 from Previous Date

05-02-2020 - 118 - Diff is -4 from Previous Date

04-02-2020 - 119 - Diff is +1 from Previous Date

03-02-2020 - 119 - Diff is 0 from Previous Date
```

And to achieve that you don't need the generator implementation I used at all. You can simply do this with a regular foreach loop like so:

```<code>$lastDiff = 0; // Initialize the diff to 0

foreach($array as $a) {
    $date = $a['date'];
    $density = $a['density'];
    $diff = $a["density"] - $lastDiff; // diff against the last known value
    if ($diff > 0) {
        $diff = "+$diff";
    }
    echo "$date - $density - Diff is $diff from Previous Date<br><br>";
    $lastDiff = $a["density"]; // store the last known density here for the next iteration
}
</code>```

Body:
I am trying to show some values using json api. It returns a date and some density value in numbers. Successfully, I have printed all return values from url. Now, I want to find the difference between one density value to previous day density value.

I know how to calculate the difference in normal static numbers. But, I am not sure how do I achieve this inside a foreach loop.

PHP Code:

$json_url = "https://www.example.com/api";

$json = file_get_contents($json_url);
$obj  = json_decode($json,true);
$data = $obj["data"];

foreach(array_slice($data, 0, 10) as $k) {

    echo $k["date"]." - ".$k["density"]."

";

}

Current Output:

14-02-2020 - 110

13-02-2020 - 114

12-02-2020 - 112

11-02-2020 - 110

10-02-2020 - 105

07-02-2020 - 125

06-02-2020 - 122

05-02-2020 - 118

04-02-2020 - 119

03-02-2020 - 119

Expected Output:

14-02-2020 - 110 - Diff is -4 from Previous Date

13-02-2020 - 114 - Diff is +2 from Previous Date

12-02-2020 - 112 - Diff is +2 from Previous Date

11-02-2020 - 110 - Diff is +5 from Previous Date

10-02-2020 - 105 - Diff is -20 from Previous Date

07-02-2020 - 125 - Diff is +3 from Previous Date

06-02-2020 - 122 - Diff is +4 from Previous Date

05-02-2020 - 118 - Diff is -1 from Previous Date

04-02-2020 - 119 - No Difference - Same

03-02-2020 - 119 - No Difference - Same

Body:
To achieve the desired effect you will need to iterate the array two elements at a time. This can't easily be done with foreach outright. So instead I will implement a generator that returns pairs of values from the array at a time.

function getPairs(Array $array) {
    reset($array);
    do {
        $a1  = current($array);
        $key = key($array);
        $a2  = next($array);
        yield [$a1, $a2];
    } while($key = key($array) !== null);
}

You can then use this generator implementation to traverse the array, attaining the desired effect.

$array = [
    ["date" => "14-02-2020", "density" => 110],
    ["date" => "13-02-2020", "density" => 114],
    ["date" => "12-02-2020", "density" => 112],
    ["date" => "11-02-2020", "density" => 110],
    ["date" => "10-02-2020", "density" => 105],
    ["date" => "07-02-2020", "density" => 125],
    ["date" => "12-02-2020", "density" => 112],
    ["date" => "06-02-2020", "density" => 122],
    ["date" => "05-02-2020", "density" => 118],
    ["date" => "04-02-2020", "density" => 119],
    ["date" => "03-02-2020", "density" => 119],
];

foreach(getPairs($array) as [$a, $b]) {
    // We must check if $b is empty to account for end of the array
    if ($b) {
        $diff = $a["density"] - $b["density"];
    } else { // Otherwise there are no more elements to diff against
        $diff = 0;
    }
    if ($diff > 0) {
        $diff = "+$diff";
    }
    echo "{$a['date']} - {$a['density']} - Diff is $diff from Previous Date<br><br>";
}

This should give you the desired output.

14-02-2020 - 110 - Diff is -4 from Previous Date

13-02-2020 - 114 - Diff is +2 from Previous Date

12-02-2020 - 112 - Diff is +2 from Previous Date

11-02-2020 - 110 - Diff is +5 from Previous Date

10-02-2020 - 105 - Diff is -20 from Previous Date

07-02-2020 - 125 - Diff is +13 from Previous Date

12-02-2020 - 112 - Diff is -10 from Previous Date

06-02-2020 - 122 - Diff is +4 from Previous Date

05-02-2020 - 118 - Diff is -1 from Previous Date

04-02-2020 - 119 - Diff is 0 from Previous Date

03-02-2020 - 119 - Diff is 0 from Previous Date

N.B.

Technically speaking you aren't actually getting the difference between the current date and the previous date, here. Rather, you are getting the difference between the current date and the next date. If you were getting the deltas between previous dates you wouldn't need the information from the next date at all. Instead you'd just use a temporary variable to store the last density value and diff against that with each iteration. However, I've tailored my answer to suit your expected result.

Otherwise the expected output would actually be:

14-02-2020 - 110 - Diff is +110 from Previous Date

13-02-2020 - 114 - Diff is +4 from Previous Date

12-02-2020 - 112 - Diff is -2 from Previous Date

11-02-2020 - 110 - Diff is -2 from Previous Date

10-02-2020 - 105 - Diff is -5 from Previous Date

07-02-2020 - 125 - Diff is +20 from Previous Date

12-02-2020 - 112 - Diff is -13 from Previous Date

06-02-2020 - 122 - Diff is +10 from Previous Date

05-02-2020 - 118 - Diff is -4 from Previous Date

04-02-2020 - 119 - Diff is +1 from Previous Date

03-02-2020 - 119 - Diff is 0 from Previous Date

And to achieve that you don't need the generator implementation I used at all. You can simply do this with a regular foreach loop like so:

$lastDiff = 0; // Initialize the diff to 0

foreach($array as $a) {
    $date = $a['date'];
    $density = $a['density'];
    $diff = $a["density"] - $lastDiff; // diff against the last known value
    if ($diff > 0) {
        $diff = "+$diff";
    }
    echo "$date - $density - Diff is $diff from Previous Date<br><br>";
    $lastDiff = $a["density"]; // store the last known density here for the next iteration
}


问:
keras image classifier model configuration
I am trying to learn image classification using Keras and TensorFlow.
I am referring to https://www.kaggle.com/c/dogs-vs-cats problem.

My Code is as below:

```<code>#!/usr/bin/env python
# coding: utf-8

# # Cats and Dogs Identification Kaggle
#
# https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

# ## Tensorflow and GPU Memory Config

# In[14]:

import tensorflow as tf
from tensorflow.keras.models import Sequential
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

from tensorflow.keras.layers import Dense, Flatten, Activation, Conv2D, MaxPooling2D,  Reshape, BatchNormalization
from keras import backend as K

# tf.reset_default_graph()
# tf.set_random_seed(42)
# tf.config.set_per_process_memory_growth(True)
# tf.config.gpu.set_per_process_memory_fraction(0.4)
tf.debugging.set_log_device_placement(True)

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
tf.config.experimental.list_physical_devices('GPU')

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.experimental.set_virtual_device_configuration(
        gpus[0],
        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048)])
    logical_gpus = tf.config.experimental.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)

print('Keras image_data_format {}'.format(K.image_data_format()))
print('if keras image_data_format is channel_last means data should be loaded in 32X32X3 dimensions')

# In[2]:

import os
import shutil
from shutil import copyfile
from random import seed
from random import random

def createPathIfNoExists(path):
    if not os.path.exists(path):
        os.mkdir(path)

cats_dir = '/cats'
dogs_dir = '/dogs'

source_images = '/home/user/Desktop/dogs_cat_keras'
data_dir = source_images + '/data'

train_dir = data_dir + '/train'
train_cats_dir = train_dir + cats_dir
train_dogs_dir = train_dir + dogs_dir

validation_dir = data_dir + '/validation'
validation_cats_dir = validation_dir + cats_dir
validation_dogs_dir = validation_dir + dogs_dir

createPathIfNoExists(data_dir)

createPathIfNoExists(train_dir)
createPathIfNoExists(train_cats_dir)
createPathIfNoExists(train_dogs_dir)

createPathIfNoExists(validation_dir)
createPathIfNoExists(validation_cats_dir)
createPathIfNoExists(validation_dogs_dir)

print('Source directory {}'.format(source_images))
print('Data directory {}'.format(data_dir))
print('train directory {}'.format(train_dir))
print('train cats directory {}'.format(train_cats_dir))
print('train dogs directory {}'.format(train_dogs_dir))
print('validation directory {}'.format(validation_dir))
print('validation directory {}'.format(validation_cats_dir))
print('validation directory {}'.format(validation_dogs_dir))

# inputFiles = source_images + '/train'

# cats = [inputFiles+'/' + d for d in os.listdir(inputFiles) if d.startswith('cat')]

# print('All cats count {}'.format(len(cats)))

# dogs = [inputFiles+'/' + d for d in os.listdir(inputFiles) if d.startswith('dog')]

# print('All dogs count {}'.format(len(dogs)))

# data_split_70 = 8400

# train_cats = cats[:data_split_70]
# validation_cats = cats[data_split_70:]

# train_dogs = dogs[:data_split_70]
# validation_dogs = dogs[data_split_70:]

# print('Total train cats {} and validation cats {}'.format(len(train_cats), len(validation_cats)))
# print('Total train dogs {} and validation dogs {}'.format(len(train_dogs), len(validation_dogs)))

# # Put train cats data in train directory
# for item in train_cats:
#     if os.path.isfile(item):
#         shutil.copyfile(item, train_cats_dir + '/' + os.path.basename(item))

# # Put validation cats data in validation directory
# for item in validation_cats:
#     if os.path.isfile(item):
#         shutil.copyfile(item, validation_cats_dir + '/' + os.path.basename(item))

# # Put train cats data in train directory
# for item in train_dogs:
#     if os.path.isfile(item):
#         shutil.copyfile(item, train_dogs_dir + '/' + os.path.basename(item))

# # Put validation cats data in validation directory
# for item in validation_dogs:
#     if os.path.isfile(item):
#         shutil.copyfile(item, validation_dogs_dir + '/' + os.path.basename(item))

# ## General imports

# In[15]:

import datetime
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.model_selection import KFold, GridSearchCV, RandomizedSearchCV
from sklearn.preprocessing import MinMaxScaler

get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt

from sklearn.neighbors import KNeighborsClassifier

import h5py

# ## Data Import

# In[16]:

dataGenerator = ImageDataGenerator(rotation_range=40,
                                  width_shift_range=0.2,
                                  height_shift_range=0.2,
                                  shear_range=0.2,
                                  zoom_range=0.2,
                                  horizontal_flip=True,
                                  fill_mode='nearest')

# ### Image Display

# In[17]:

img = load_img('/home/user/Desktop/dogs_cat_keras/data/train/cats/cat.12467.jpg')  # this is a PIL image
x = img_to_array(img)  # this is a Numpy array with shape (width X height X 3)
print(x.shape)
# print(type(img))
# print(img.size)
# print(img.mode)
plt.imshow(x/255)
plt.show()
print('Shape before reshape {}'.format(x.shape))

## Generate data = 0
x = x.reshape((1,) + x.shape)  # this is a Numpy array with shape (1, width, height, 3)
print('Shape after reshape {}'.format(x.shape))

# ### Generate augumented data using image generator

# In[6]:

# import os

# augumented_data_path = data_path + '/preview'

# if not os.path.exists(augumented_data_path):
#     os.mkdir(augumented_data_path)

# i = 0
# for batch in dataGenerator.flow(x, batch_size=1,
#                           save_to_dir=augumented_data_path, save_prefix='cat', save_format='jpeg'):
#     i += 1
#     if i > 20:
#         break  # otherwise the generator would loop indefinitely

# ### Building Graph

# In[23]:

img_width, img_height = 150, 150
input_shape = (img_width, img_height, 3)

nnModel = Sequential()

nnModel.add(Flatten(input_shape=(input_shape)))
nnModel.add(Dense(32, activation='relu'))
nnModel.add(Dense(16, activation='relu'))
nnModel.add(Dense(2, activation='softmax'))

# ### Compile function

# In[26]:

nnModel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])

# ### Train Generator

# In[20]:

batch_size = 32

train_data_gen = ImageDataGenerator(rescale = 1/255,
                                    shear_range=0.2,
                                    zoom_range=0.2,
                                    horizontal_flip=True)
train_generator = train_data_gen.flow_from_directory(
        train_dir,  # this is the target directory
        target_size=(img_width, img_height),  # all images will be resized to 150x150
        batch_size=batch_size,
        class_mode='binary')

print('Train path {}'.format(train_dir))

test_data_gen = ImageDataGenerator(rescale = 1/255)

print('Test path {}'.format(validation_dir))

validation_generator = test_data_gen.flow_from_directory(
        validation_dir,  # this is the target directory
        target_size=(img_width, img_height),  # all images will be resized to 150x150
        batch_size=batch_size,
        class_mode='binary')

# In[24]:

nnModel.summary()

# ### Train

# In[27]:

nnModel.fit_generator(train_generator,
                      steps_per_epoch=2048,
                      epochs=64,
                      validation_data=validation_generator,
                      validation_steps=1024)
</code>```

I am getting following exception

```<code><ipython-input-27-59bf3c75cdc4> in <module>
      3                       epochs=64,
      4                       validation_data=validation_generator,
----> 5                       validation_steps=1024)...

A target array with shape (32, 1) was passed for an output of shape (None, 2) while using as loss `binary_crossentropy`. This loss expects targets to have the same shape as the output.

</code>```

Problem statement has lot of notebook solution, but here i don't want to use cnn for learning purpose. Please help me solve this.

答:
Your problem in your code comes from this line:

```<code>nnModel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
</code>```

You have to change your loss function to categorical_crossentropy, not binary_crossentropy. Practically, in your code, you have to write     nnModel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

If you have a binary classification problem, you can opt for one of these two variants:

Dense(1,activation='sigmoid') + loss = 'binary_crossentropy'

Dense(2,activation='softmax') + loss = 'categorical_crossentropy'

The only small change you may need to also make is for ImageDataGenerator, with the class_mode(set it to 'binary' in the first case and to 'categorical' in the second case)

Body:
I am trying to learn image classification using Keras and TensorFlow.
I am referring to https://www.kaggle.com/c/dogs-vs-cats problem.

My Code is as below:

#!/usr/bin/env python
# coding: utf-8

# # Cats and Dogs Identification Kaggle
#
# https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

# ## Tensorflow and GPU Memory Config

# In[14]:

import tensorflow as tf
from tensorflow.keras.models import Sequential
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

from tensorflow.keras.layers import Dense, Flatten, Activation, Conv2D, MaxPooling2D,  Reshape, BatchNormalization
from keras import backend as K

# tf.reset_default_graph()
# tf.set_random_seed(42)
# tf.config.set_per_process_memory_growth(True)
# tf.config.gpu.set_per_process_memory_fraction(0.4)
tf.debugging.set_log_device_placement(True)

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
tf.config.experimental.list_physical_devices('GPU')

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.experimental.set_virtual_device_configuration(
        gpus[0],
        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048)])
    logical_gpus = tf.config.experimental.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)

print('Keras image_data_format {}'.format(K.image_data_format()))
print('if keras image_data_format is channel_last means data should be loaded in 32X32X3 dimensions')

# In[2]:

import os
import shutil
from shutil import copyfile
from random import seed
from random import random

def createPathIfNoExists(path):
    if not os.path.exists(path):
        os.mkdir(path)

cats_dir = '/cats'
dogs_dir = '/dogs'

source_images = '/home/user/Desktop/dogs_cat_keras'
data_dir = source_images + '/data'

train_dir = data_dir + '/train'
train_cats_dir = train_dir + cats_dir
train_dogs_dir = train_dir + dogs_dir

validation_dir = data_dir + '/validation'
validation_cats_dir = validation_dir + cats_dir
validation_dogs_dir = validation_dir + dogs_dir

createPathIfNoExists(data_dir)

createPathIfNoExists(train_dir)
createPathIfNoExists(train_cats_dir)
createPathIfNoExists(train_dogs_dir)

createPathIfNoExists(validation_dir)
createPathIfNoExists(validation_cats_dir)
createPathIfNoExists(validation_dogs_dir)

print('Source directory {}'.format(source_images))
print('Data directory {}'.format(data_dir))
print('train directory {}'.format(train_dir))
print('train cats directory {}'.format(train_cats_dir))
print('train dogs directory {}'.format(train_dogs_dir))
print('validation directory {}'.format(validation_dir))
print('validation directory {}'.format(validation_cats_dir))
print('validation directory {}'.format(validation_dogs_dir))

# inputFiles = source_images + '/train'

# cats = [inputFiles+'/' + d for d in os.listdir(inputFiles) if d.startswith('cat')]

# print('All cats count {}'.format(len(cats)))

# dogs = [inputFiles+'/' + d for d in os.listdir(inputFiles) if d.startswith('dog')]

# print('All dogs count {}'.format(len(dogs)))

# data_split_70 = 8400

# train_cats = cats[:data_split_70]
# validation_cats = cats[data_split_70:]

# train_dogs = dogs[:data_split_70]
# validation_dogs = dogs[data_split_70:]

# print('Total train cats {} and validation cats {}'.format(len(train_cats), len(validation_cats)))
# print('Total train dogs {} and validation dogs {}'.format(len(train_dogs), len(validation_dogs)))

# # Put train cats data in train directory
# for item in train_cats:
#     if os.path.isfile(item):
#         shutil.copyfile(item, train_cats_dir + '/' + os.path.basename(item))

# # Put validation cats data in validation directory
# for item in validation_cats:
#     if os.path.isfile(item):
#         shutil.copyfile(item, validation_cats_dir + '/' + os.path.basename(item))

# # Put train cats data in train directory
# for item in train_dogs:
#     if os.path.isfile(item):
#         shutil.copyfile(item, train_dogs_dir + '/' + os.path.basename(item))

# # Put validation cats data in validation directory
# for item in validation_dogs:
#     if os.path.isfile(item):
#         shutil.copyfile(item, validation_dogs_dir + '/' + os.path.basename(item))

# ## General imports

# In[15]:

import datetime
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.model_selection import KFold, GridSearchCV, RandomizedSearchCV
from sklearn.preprocessing import MinMaxScaler

get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt

from sklearn.neighbors import KNeighborsClassifier

import h5py

# ## Data Import

# In[16]:

dataGenerator = ImageDataGenerator(rotation_range=40,
                                  width_shift_range=0.2,
                                  height_shift_range=0.2,
                                  shear_range=0.2,
                                  zoom_range=0.2,
                                  horizontal_flip=True,
                                  fill_mode='nearest')

# ### Image Display

# In[17]:

img = load_img('/home/user/Desktop/dogs_cat_keras/data/train/cats/cat.12467.jpg')  # this is a PIL image
x = img_to_array(img)  # this is a Numpy array with shape (width X height X 3)
print(x.shape)
# print(type(img))
# print(img.size)
# print(img.mode)
plt.imshow(x/255)
plt.show()
print('Shape before reshape {}'.format(x.shape))

## Generate data = 0
x = x.reshape((1,) + x.shape)  # this is a Numpy array with shape (1, width, height, 3)
print('Shape after reshape {}'.format(x.shape))

# ### Generate augumented data using image generator

# In[6]:

# import os

# augumented_data_path = data_path + '/preview'

# if not os.path.exists(augumented_data_path):
#     os.mkdir(augumented_data_path)

# i = 0
# for batch in dataGenerator.flow(x, batch_size=1,
#                           save_to_dir=augumented_data_path, save_prefix='cat', save_format='jpeg'):
#     i += 1
#     if i > 20:
#         break  # otherwise the generator would loop indefinitely

# ### Building Graph

# In[23]:

img_width, img_height = 150, 150
input_shape = (img_width, img_height, 3)

nnModel = Sequential()

nnModel.add(Flatten(input_shape=(input_shape)))
nnModel.add(Dense(32, activation='relu'))
nnModel.add(Dense(16, activation='relu'))
nnModel.add(Dense(2, activation='softmax'))

# ### Compile function

# In[26]:

nnModel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])

# ### Train Generator

# In[20]:

batch_size = 32

train_data_gen = ImageDataGenerator(rescale = 1/255,
                                    shear_range=0.2,
                                    zoom_range=0.2,
                                    horizontal_flip=True)
train_generator = train_data_gen.flow_from_directory(
        train_dir,  # this is the target directory
        target_size=(img_width, img_height),  # all images will be resized to 150x150
        batch_size=batch_size,
        class_mode='binary')

print('Train path {}'.format(train_dir))

test_data_gen = ImageDataGenerator(rescale = 1/255)

print('Test path {}'.format(validation_dir))

validation_generator = test_data_gen.flow_from_directory(
        validation_dir,  # this is the target directory
        target_size=(img_width, img_height),  # all images will be resized to 150x150
        batch_size=batch_size,
        class_mode='binary')

# In[24]:

nnModel.summary()

# ### Train

# In[27]:

nnModel.fit_generator(train_generator,
                      steps_per_epoch=2048,
                      epochs=64,
                      validation_data=validation_generator,
                      validation_steps=1024)

I am getting following exception

<ipython-input-27-59bf3c75cdc4> in <module>
      3                       epochs=64,
      4                       validation_data=validation_generator,
----> 5                       validation_steps=1024)...

A target array with shape (32, 1) was passed for an output of shape (None, 2) while using as loss `binary_crossentropy`. This loss expects targets to have the same shape as the output.

Problem statement has lot of notebook solution, but here i don't want to use cnn for learning purpose. Please help me solve this.

Body:
Your problem in your code comes from this line:

nnModel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])

You have to change your loss function to categorical_crossentropy, not binary_crossentropy. Practically, in your code, you have to write     nnModel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

If you have a binary classification problem, you can opt for one of these two variants:

Dense(1,activation='sigmoid') + loss = 'binary_crossentropy'

Dense(2,activation='softmax') + loss = 'categorical_crossentropy'

The only small change you may need to also make is for ImageDataGenerator, with the class_mode(set it to 'binary' in the first case and to 'categorical' in the second case)


问:
Roles and permissions in php
I am making a menu, but I want to limit it to only some users with a specific permission can see it.

the query:

SELECT idpermission,userid FROM user_permissions WHERE userid = "U001"

Result: User U001 has 3 permissions stored.

```<code>idpermission,userid
 IDP001,U001
 IDP002,U001
 IDP003,U001
</code>```

I have 3 tables (users,permissions and user_permissions), in user_permissions I store each permission of each user

```<code>Example:

Table

user | permission | user_permissions

result:

user: u001,carlos,carlos@...

permissions: IDP001 = book | IDP002 = create_book | IDP003 = edit_book | IDP004 = user | IDP005 = edit_user...

user_permissions:
IDP001,U001
IDP002,U001
IDP003,U001
IDP001,U002
IDP003,U002...
</code>```

when i call the query

```<code>while($sqlRow=$sqlPermissions->fetch(PDO::FETCH_ASSOC))
 {
   if ($sqlRow['idpermission'] == 'IDP001' || $sqlRow['idpermission'] == 'IDP002' || $sqlRow['idpermission'] == 'IDP003')
     {
        echo "user menu ";
     }
 }
</code>```

but the result that appears to me is 3:

user menu user menu user menu

You should only show me one, making only a comparison if you have such permission shows but shows nothing.

What I want to reach is that the user can have many permissions for different items on the menu, such as view, edit, create, delete, each one is a permission, and each item (user menu, books menu) is another permission.

答:
Use a pivot technique to gather all permissions for a single user and form a single row to fetch with pdo.

This way all expected columns are declared and you can use simple truthy/falsey conditional checks in your php for any of the permission settings.

So long as the userid exists in the table, you will have a fully populated row to access.  This will be clean, direct, efficient, and easy to maintain.

Schema (MySQL v5.7)

```<code>CREATE TABLE user_permissions (
  idpermission VARCHAR(20),
  userid VARCHAR(20)
);

INSERT INTO user_permissions VALUES
('IDP001', 'U001'),
('IDP002', 'U001'),
('IDP003', 'U001'),
('IDP001', 'U002'),
('IDP003', 'U002');
</code>```

Query #1

```<code>SELECT MAX(IF(idpermission = 'IDP001', 1, 0)) AS book,
       MAX(IF(idpermission = 'IDP002', 1, 0)) AS create_book,
       MAX(IF(idpermission = 'IDP003', 1, 0)) AS edit_book,
       MAX(IF(idpermission = 'IDP004', 1, 0)) AS user,
       MAX(IF(idpermission = 'IDP005', 1, 0)) AS edit_user
FROM user_permissions
WHERE userid = 'U001'
GROUP BY userid;
</code>```

Result set:

```<code>| book | create_book | edit_book | user | edit_user |
| ---- | ----------- | --------- | ---- | --------- |
| 1    | 1           | 1         | 0    | 0         |
</code>```

View on DB Fiddle

Title: Roles and permissions in php

Body:
I am making a menu, but I want to limit it to only some users with a specific permission can see it.

the query:

SELECT idpermission,userid FROM user_permissions WHERE userid = "U001"

Result: User U001 has 3 permissions stored.

idpermission,userid
 IDP001,U001
 IDP002,U001
 IDP003,U001

I have 3 tables (users,permissions and user_permissions), in user_permissions I store each permission of each user

Example:

Table

user | permission | user_permissions

result:

user: u001,carlos,carlos@...

permissions: IDP001 = book | IDP002 = create_book | IDP003 = edit_book | IDP004 = user | IDP005 = edit_user...

user_permissions:
IDP001,U001
IDP002,U001
IDP003,U001
IDP001,U002
IDP003,U002...

when i call the query

while($sqlRow=$sqlPermissions->fetch(PDO::FETCH_ASSOC))
 {
   if ($sqlRow['idpermission'] == 'IDP001' || $sqlRow['idpermission'] == 'IDP002' || $sqlRow['idpermission'] == 'IDP003')
     {
        echo "user menu ";
     }
 }

but the result that appears to me is 3:

user menu user menu user menu

You should only show me one, making only a comparison if you have such permission shows but shows nothing.

What I want to reach is that the user can have many permissions for different items on the menu, such as view, edit, create, delete, each one is a permission, and each item (user menu, books menu) is another permission.

Body:
Use a pivot technique to gather all permissions for a single user and form a single row to fetch with pdo.

This way all expected columns are declared and you can use simple truthy/falsey conditional checks in your php for any of the permission settings.

So long as the userid exists in the table, you will have a fully populated row to access.  This will be clean, direct, efficient, and easy to maintain.

Schema (MySQL v5.7)

CREATE TABLE user_permissions (
  idpermission VARCHAR(20),
  userid VARCHAR(20)
);

INSERT INTO user_permissions VALUES
('IDP001', 'U001'),
('IDP002', 'U001'),
('IDP003', 'U001'),
('IDP001', 'U002'),
('IDP003', 'U002');

Query #1

SELECT MAX(IF(idpermission = 'IDP001', 1, 0)) AS book,
       MAX(IF(idpermission = 'IDP002', 1, 0)) AS create_book,
       MAX(IF(idpermission = 'IDP003', 1, 0)) AS edit_book,
       MAX(IF(idpermission = 'IDP004', 1, 0)) AS user,
       MAX(IF(idpermission = 'IDP005', 1, 0)) AS edit_user
FROM user_permissions
WHERE userid = 'U001'
GROUP BY userid;

Result set:

| book | create_book | edit_book | user | edit_user |
| ---- | ----------- | --------- | ---- | --------- |
| 1    | 1           | 1         | 0    | 0         |

View on DB Fiddle


问:
How to add margins to a
 tags?
I am in a bit of a predicament.  I have the nl2br function which will add spaces/breaks to sentences, but the gap is too big and the output looks to spaced out.  So I realized I can use #br and give a margin-top etc, but that will mess up other
 where there is only one line by default.

Is there a way that I can either replace the
 with a
 tag or something?

答: Why don't you add a css class or id to the parent tag and then us CSS to style the child containers / tag?</p>

Title: How to add margins to a <br> tags?


问:
Check if UserDefault exists - Swift
I'm trying to check if the a user default exists, seen below:

```<code>func userAlreadyExist() -> Bool {
    var userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()

    if userDefaults.objectForKey(kUSERID) {
        return true
    }

    return false
}
</code>```

However, no mater what it will always return true even when the object doesn't exist yet? Is this the right way for checking existence ?

答:
```<code>public class PreferencesUtils {

    private init() {

    }

    public static func setBoolData(boolValue: Bool, dataName: String) {
        UserDefaults.standard.set(boolValue, forKey: dataName)
    }

    public static func getBoolData(dataName: String)-> Bool{

        let defaults = UserDefaults.standard

        if(defaults.value(forKey: dataName) != nil) {
            return defaults.value(forKey: dataName)! as! Bool

        } else {
            return false
        }
    }

    public static func saveStringData(data: String, dataName: String){
        let preferences = UserDefaults.standard
        preferences.set(data, forKey: dataName)
        let didSave = preferences.synchronize()
        if !didSave {
            debugPrint("Not saved yet")
        }
    }

    public static func getSavedStringData(dataName: String)-> String{
        let defaults = UserDefaults.standard
        if(defaults.value(forKey: dataName) != nil){
            return defaults.value(forKey: dataName) as! String
        } else {
            return ""
        }
    }

    public static func saveIntData(data : Int, dataName: String){
        let preferences = UserDefaults.standard
        preferences.set(data, forKey: dataName)
        let didSave = preferences.synchronize()
        if !didSave {
            debugPrint("Not saved yet")
        }
    }

    public static func getSavedIntData(dataName: String) -> Int {
        let defaults = UserDefaults.standard
        if(defaults.value(forKey: dataName) != nil){
            return defaults.value(forKey: dataName) as! Int
        }else{
            return 0
        }
    }

}
</code>```

Or you can try this library: Link

Title: Check if UserDefault exists - Swift

Body:
I'm trying to check if the a user default exists, seen below:

func userAlreadyExist() -> Bool {
    var userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()

    if userDefaults.objectForKey(kUSERID) {
        return true
    }

    return false
}

However, no mater what it will always return true even when the object doesn't exist yet? Is this the right way for checking existence ?

Body:
public class PreferencesUtils {

    private init() {

    }

    public static func setBoolData(boolValue: Bool, dataName: String) {
        UserDefaults.standard.set(boolValue, forKey: dataName)
    }

    public static func getBoolData(dataName: String)-> Bool{

        let defaults = UserDefaults.standard

        if(defaults.value(forKey: dataName) != nil) {
            return defaults.value(forKey: dataName)! as! Bool

        } else {
            return false
        }
    }

    public static func saveStringData(data: String, dataName: String){
        let preferences = UserDefaults.standard
        preferences.set(data, forKey: dataName)
        let didSave = preferences.synchronize()
        if !didSave {
            debugPrint("Not saved yet")
        }
    }

    public static func getSavedStringData(dataName: String)-> String{
        let defaults = UserDefaults.standard
        if(defaults.value(forKey: dataName) != nil){
            return defaults.value(forKey: dataName) as! String
        } else {
            return ""
        }
    }

    public static func saveIntData(data : Int, dataName: String){
        let preferences = UserDefaults.standard
        preferences.set(data, forKey: dataName)
        let didSave = preferences.synchronize()
        if !didSave {
            debugPrint("Not saved yet")
        }
    }

    public static func getSavedIntData(dataName: String) -> Int {
        let defaults = UserDefaults.standard
        if(defaults.value(forKey: dataName) != nil){
            return defaults.value(forKey: dataName) as! Int
        }else{
            return 0
        }
    }

}

Or you can try this library: Link