问:
How to set column width in adaptive card so its uniform
I'm trying to ask user informations in adaptive card. But the column size is varying because of which the card looks clumsy. How can I make it look good with uniform gap between each columnset columns. I tried using width as "Auto" and "Stretch" I even tried setting width with "50px" and "100px" but I didn't achieve.

Kindly help me on this.

Edit 1: Adding Code

I'm creating card in C#

Here is my code

```<code>AdaptiveCard card = new AdaptiveCard()
    {
        Body = new List<AdaptiveElement>()
        {
            new AdaptiveColumnSet()
            {
                 Columns = new List<AdaptiveColumn>
                 {
                     new AdaptiveColumn()
                     {
                         Items = new List<AdaptiveElement>()
                         {
                             new AdaptiveTextBlock()
                             {
                                  Text="*First Name",
                                  Weight = AdaptiveTextWeight.Bolder
                              },
                         } ,
                         Width = AdaptiveColumnWidth.Auto
                     },
                      new AdaptiveColumn()
                      {
                           Width = AdaptiveColumnWidth.Auto,
                           Separator = true,
                           Items=new List<AdaptiveElement>()
                            {
                                new AdaptiveTextInput()
                                {
                                    Id = "FirstName",
                                    MaxLength = 300,
                                    Style = AdaptiveTextInputStyle.Text,
                                },
                           }
                      }
                 }
            }, // First Name
            new AdaptiveColumnSet()
            {
                Columns = new List<AdaptiveColumn>
                {
                    new AdaptiveColumn()
                    {
                        Items = new List<AdaptiveElement>()
                        {
                            new AdaptiveTextBlock()
                            {
                                 Text="Middle Name",
                                  Weight = AdaptiveTextWeight.Bolder
                            },
                        }
                    },
                    new AdaptiveColumn()
                    {
                         Width = "stretch",
                         Separator = true,
                         Items=new List<AdaptiveElement>()
                          {
                              new AdaptiveTextInput()
                              {
                                  Id = "MiddleName",
                                  MaxLength = 300,
                                  Style = AdaptiveTextInputStyle.Text,
                              },
                          }
                    }
                 }
            },
            new AdaptiveColumnSet()
            {
                Columns = new List<AdaptiveColumn>
                {
                    new AdaptiveColumn()
                    {
                        Items = new List<AdaptiveElement>()
                        {
                             new AdaptiveTextBlock()
                             {
                                  Text="*Last Name",
                                  Weight = AdaptiveTextWeight.Bolder
                             },
                         }
                    },
                    new AdaptiveColumn()
                    {
                         Width = "stretch",
                         Separator = true,
                         Items=new List<AdaptiveElement>()
                         {
                             new AdaptiveTextInput()
                             {
                                 Id = "LastName",
                                 MaxLength = 300,
                                 Style = AdaptiveTextInputStyle.Text,

                             },

                         }

                    }

                }

            },
            new AdaptiveColumnSet()
            {
               Columns = new List<AdaptiveColumn>
               {
                   new AdaptiveColumn()
                   {
                       Items = new List<AdaptiveElement>()
                       {
                           new AdaptiveTextBlock()
                           {
                               Text="*Date Of Birth",
                               Weight = AdaptiveTextWeight.Bolder
                           },
                       }
                   },
                    new AdaptiveColumn()
                    {
                         Width = "stretch",
                         Separator = true,
                         Items=new List<AdaptiveElement>()
                         {
                             new AdaptiveDateInput()
                             {
                                 Id = "DoB",

                             },

                         }

                    }

               }

            }, // Date Of Birth
        }
    };
</code>```

答:
first of all you could control your card a lot easier if you'd have a look at templating.

Creating cards in code like that is soooort of deprecated, you can still use it but using json directly and templating is way more convinient.

To answer your question, yes you can can set width of columns in either pixel, stretch, automatic or weighted. Similar to this example:

```<code>        "type": "ColumnSet",
        "columns": [
            {
                "type": "Column",
                "width": 25,
                "horizontalAlignment": "Center",
                "verticalContentAlignment": "Center"
            },
            {
                "type": "Column",
                "width": "stretch"
            }
        ]
</code>```

You have to set all the label columns in your example to the same size. Easiest is by just setting them to a fixed width or weighted.

If this does not work, make sure the term is used correct, you have to use a lower case "stretch" and width when weighted has to be an integer, You can try this in the designer. Adaptive Cards as such doesn't really care about "Stretch" or "stretch" but webchat for example has some issues around that, also the card version has to match what your host supports.

Easiest way, and thats where templating comes in again, is to design and try your card in the designer. If its fine in the designer it usually is in the host you want to render the card.

Hope thats helpful for you

Body:
I'm trying to ask user informations in adaptive card. But the column size is varying because of which the card looks clumsy. How can I make it look good with uniform gap between each columnset columns. I tried using width as "Auto" and "Stretch" I even tried setting width with "50px" and "100px" but I didn't achieve.

Kindly help me on this.

Edit 1: Adding Code

I'm creating card in C#

Here is my code

AdaptiveCard card = new AdaptiveCard()
    {
        Body = new List<AdaptiveElement>()
        {
            new AdaptiveColumnSet()
            {
                 Columns = new List<AdaptiveColumn>
                 {
                     new AdaptiveColumn()
                     {
                         Items = new List<AdaptiveElement>()
                         {
                             new AdaptiveTextBlock()
                             {
                                  Text="*First Name",
                                  Weight = AdaptiveTextWeight.Bolder
                              },
                         } ,
                         Width = AdaptiveColumnWidth.Auto
                     },
                      new AdaptiveColumn()
                      {
                           Width = AdaptiveColumnWidth.Auto,
                           Separator = true,
                           Items=new List<AdaptiveElement>()
                            {
                                new AdaptiveTextInput()
                                {
                                    Id = "FirstName",
                                    MaxLength = 300,
                                    Style = AdaptiveTextInputStyle.Text,
                                },
                           }
                      }
                 }
            }, // First Name
            new AdaptiveColumnSet()
            {
                Columns = new List<AdaptiveColumn>
                {
                    new AdaptiveColumn()
                    {
                        Items = new List<AdaptiveElement>()
                        {
                            new AdaptiveTextBlock()
                            {
                                 Text="Middle Name",
                                  Weight = AdaptiveTextWeight.Bolder
                            },
                        }
                    },
                    new AdaptiveColumn()
                    {
                         Width = "stretch",
                         Separator = true,
                         Items=new List<AdaptiveElement>()
                          {
                              new AdaptiveTextInput()
                              {
                                  Id = "MiddleName",
                                  MaxLength = 300,
                                  Style = AdaptiveTextInputStyle.Text,
                              },
                          }
                    }
                 }
            },
            new AdaptiveColumnSet()
            {
                Columns = new List<AdaptiveColumn>
                {
                    new AdaptiveColumn()
                    {
                        Items = new List<AdaptiveElement>()
                        {
                             new AdaptiveTextBlock()
                             {
                                  Text="*Last Name",
                                  Weight = AdaptiveTextWeight.Bolder
                             },
                         }
                    },
                    new AdaptiveColumn()
                    {
                         Width = "stretch",
                         Separator = true,
                         Items=new List<AdaptiveElement>()
                         {
                             new AdaptiveTextInput()
                             {
                                 Id = "LastName",
                                 MaxLength = 300,
                                 Style = AdaptiveTextInputStyle.Text,

                             },

                         }

                    }

                }

            },
            new AdaptiveColumnSet()
            {
               Columns = new List<AdaptiveColumn>
               {
                   new AdaptiveColumn()
                   {
                       Items = new List<AdaptiveElement>()
                       {
                           new AdaptiveTextBlock()
                           {
                               Text="*Date Of Birth",
                               Weight = AdaptiveTextWeight.Bolder
                           },
                       }
                   },
                    new AdaptiveColumn()
                    {
                         Width = "stretch",
                         Separator = true,
                         Items=new List<AdaptiveElement>()
                         {
                             new AdaptiveDateInput()
                             {
                                 Id = "DoB",

                             },

                         }

                    }

               }

            }, // Date Of Birth
        }
    };

Body:
first of all you could control your card a lot easier if you'd have a look at templating.

Creating cards in code like that is soooort of deprecated, you can still use it but using json directly and templating is way more convinient.

To answer your question, yes you can can set width of columns in either pixel, stretch, automatic or weighted. Similar to this example:

        "type": "ColumnSet",
        "columns": [
            {
                "type": "Column",
                "width": 25,
                "horizontalAlignment": "Center",
                "verticalContentAlignment": "Center"
            },
            {
                "type": "Column",
                "width": "stretch"
            }
        ]

You have to set all the label columns in your example to the same size. Easiest is by just setting them to a fixed width or weighted.

If this does not work, make sure the term is used correct, you have to use a lower case "stretch" and width when weighted has to be an integer, You can try this in the designer. Adaptive Cards as such doesn't really care about "Stretch" or "stretch" but webchat for example has some issues around that, also the card version has to match what your host supports.

Easiest way, and thats where templating comes in again, is to design and try your card in the designer. If its fine in the designer it usually is in the host you want to render the card.

Hope thats helpful for you


来源: stackexchange

问:
error TS2339 when trying to add child FormGroup in Angular
I'm using Angular8 and trying to add a child FormGroup to a form using addControl:

```<code>    this.testForm = new FormGroup({
        id: new FormControl(0),
        people: new FormGroup({
        }),
    });
    this.testForm.controls['people'].addControl('numbers', new FormGroup({
        number: new FormControl('1234')
    }));
</code>```

This gives me compiler error:
error TS2339: Property 'addControl' does not exist on type 'AbstractControl'.

Really stuck with this, so all help much appreaciated!

答:
Type assertion should be enough: instead of

```<code>    this.testForm.controls['people'].addControl( // ...
</code>```

do

```<code>    (this.testForm.controls['people'] as FormGroup).addControl( //...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Angular8 and trying to add a child FormGroup to a form using addControl:

    this.testForm = new FormGroup({
        id: new FormControl(0),
        people: new FormGroup({
        }),
    });
    this.testForm.controls['people'].addControl('numbers', new FormGroup({
        number: new FormControl('1234')
    }));

This gives me compiler error:
error TS2339: Property 'addControl' does not exist on type 'AbstractControl'.

Really stuck with this, so all help much appreaciated!

Body:
Type assertion should be enough: instead of

    this.testForm.controls['people'].addControl( // ...

do

    (this.testForm.controls['people'] as FormGroup).addControl( //...


问:
Sorting an array by date in typescript
I want to custom a page in D365 Event Management.
Its written in HTML,CSS,JS,AngularJS and Typescript.

I have a html file with an overview of events:

```<code><div class="spinner-container m-5" *ngIf="isLoading">
    <app-spinner></app-spinner>
</div>

<div *ngIf="!isLoading">
    <div class="container">
        <div class="page-header">
            <h3 [appTranslate]="'AvailableEvents'">Available events</h3>
        </div>
    </div>

    <div *ngIf="error">
        <app-errormessage
            [serverErrorMessage]="error.message"
            [errorMessageTranslationKey]="error.localizationKey">
        </app-errormessage>
    </div>

    <div *ngIf="allEvents" class="container mt-5" id="all-events">
        <div class="row">
            <div class="col-12 col-md-6 col-lg-4" attr.data-href="/event?id={{ event.readableEventId }}" *ngFor="let event of allEvents">
                <div class="card mx-auto mb-4" style="width: 18rem;">
                    <div class="card-body">
                        <h5 class="card-title">
                             <a [routerLink]="['/event']" [queryParams]="{id: event.readableEventId}" title="{{ event.eventName }}" [attr.aria-label]="getAreaLabel(event)">
                                {{ event.eventName }}</a>
                        </h5>
                        <h6 *ngIf="event.building" class="card-subtitle mb-2 text-dark">at {{ event.building.name }} </h6>
                    </div>
                    <div class="card-footer text-dark" >
                       {{ getDateString(event) }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

First I tried to sort the divs but as the value of the dates are dynamic I thought its not possible.
So I went to the typescript file:

```<code>import { EVENT_SERVICE } from './../../providers/service.providers';
import { EventService } from '../../services/event.service';
import { Component, Inject, OnInit } from '@angular/core';
import { Event } from '../../models/Event';

...

export class HomeComponent implements OnInit {
    public allEvents: Event[];
    public isLoading: boolean;
    public error?: LocalizableError;

    constructor(@Inject(EVENT_SERVICE) private eventService: EventService) {
    }

    ngOnInit(): void {
        this.sortEvents();
        this.loadPublishedEvents();
    }

//---> This is my try to sort it
    private sortEvents(){
        this.allEvents.sort((a, b) => a.startDate.getDate() - b.startDate.getDate());
    }
//<---
    private loadPublishedEvents() {
        this.isLoading = true;
        this.eventService.getPublishedEvents().subscribe(
            events => {
                this.allEvents = events;
                this.isLoading = false;
            },
            (error: LocalizableError) => this.handleErrorResponse(error)
        );
    }

...

private getDateString(event:Event): string{

        var startDate = new Date(event.startDate.toString());
        var endDate = new Date(event.endDate.toString());
        var locale = undefined;
        const dateOptions = { year: 'numeric', month: 'short', day: 'numeric' };
        const timeOptions = { hour:'numeric', minute:'numeric' };

        var includeTime = startDate.getFullYear() ===  endDate.getFullYear() && startDate.getMonth() ===  endDate.getMonth() && startDate.getDate() ===  endDate.getDate();
        if(includeTime)
        {
            return `${startDate.toLocaleDateString(locale, dateOptions)} ${startDate.toLocaleTimeString(locale, timeOptions)} - ${endDate.toLocaleTimeString(locale, timeOptions)}`;
        }
        return `${startDate.toLocaleDateString(locale, dateOptions)} - ${endDate.toLocaleDateString(locale, dateOptions)}`;
    }

</code>```

Event.ts:

```<code>export interface Event {
    ...
    endDate: Date;
    startDate: Date;
    ...
}
</code>```

My question is now how to sort this Events by date. In standard its sorted by name.
when I sort it like I did the elements won't appear.
I think the problem is that the date of the events are not created with "newDate" like in getDateString().
I'm not very familiar with typescript. Also couldn't find anything on google except of this what I already tried.

Would be very nice if someone could help me here.
If you have any questions, just ask.

thx in advance :)

答:
It might be the case here, that the actual date values of a.startDate and b.startDate during runtime are undefined.

You could try to see if you get some results again when you use this:

```<code>this.allEvents.sort((a, b) => (a.startDate && b.startDate) ? a.startDate.getTime() - b.startDate.getTime() : 0);
</code>```

If you see (partially unsorted) results again, you know the issue is indeed caused by undefined values of those date fields. In that case, you can customize the sorting function further by correctly handling those undefined values:

```<code>this.allEvents.sort((a, b) => {
  if (a.startDate && b.startDate) {
    return a.startDate.getTime() - b.startDate.getTime();
  }
  else {
    // do something sophisticated regarding the `undefined` values and return a correct sorting value here...
  }
});
</code>```

Title: Sorting an array by date in typescript

Body:
I want to custom a page in D365 Event Management.
Its written in HTML,CSS,JS,AngularJS and Typescript.

I have a html file with an overview of events:

    <app-spinner></app-spinner>

Available events

        <app-errormessage
            [serverErrorMessage]="error.message"
            [errorMessageTranslationKey]="error.localizationKey">
        </app-errormessage>

                                {{ event.eventName }}

at {{ event.building.name }}

                       {{ getDateString(event) }}

First I tried to sort the divs but as the value of the dates are dynamic I thought its not possible.
So I went to the typescript file:

import { EVENT_SERVICE } from './../../providers/service.providers';
import { EventService } from '../../services/event.service';
import { Component, Inject, OnInit } from '@angular/core';
import { Event } from '../../models/Event';

...

export class HomeComponent implements OnInit {
    public allEvents: Event[];
    public isLoading: boolean;
    public error?: LocalizableError;

    constructor(@Inject(EVENT_SERVICE) private eventService: EventService) {
    }

    ngOnInit(): void {
        this.sortEvents();
        this.loadPublishedEvents();
    }

//---> This is my try to sort it
    private sortEvents(){
        this.allEvents.sort((a, b) => a.startDate.getDate() - b.startDate.getDate());
    }
//<---
    private loadPublishedEvents() {
        this.isLoading = true;
        this.eventService.getPublishedEvents().subscribe(
            events => {
                this.allEvents = events;
                this.isLoading = false;
            },
            (error: LocalizableError) => this.handleErrorResponse(error)
        );
    }

...

private getDateString(event:Event): string{

        var startDate = new Date(event.startDate.toString());
        var endDate = new Date(event.endDate.toString());
        var locale = undefined;
        const dateOptions = { year: 'numeric', month: 'short', day: 'numeric' };
        const timeOptions = { hour:'numeric', minute:'numeric' };

        var includeTime = startDate.getFullYear() ===  endDate.getFullYear() && startDate.getMonth() ===  endDate.getMonth() && startDate.getDate() ===  endDate.getDate();
        if(includeTime)
        {
            return `${startDate.toLocaleDateString(locale, dateOptions)} ${startDate.toLocaleTimeString(locale, timeOptions)} - ${endDate.toLocaleTimeString(locale, timeOptions)}`;
        }
        return `${startDate.toLocaleDateString(locale, dateOptions)} - ${endDate.toLocaleDateString(locale, dateOptions)}`;
    }

Event.ts:

export interface Event {
    ...
    endDate: Date;
    startDate: Date;
    ...
}

My question is now how to sort this Events by date. In standard its sorted by name.
when I sort it like I did the elements won't appear.
I think the problem is that the date of the events are not created with "newDate" like in getDateString().
I'm not very familiar with typescript. Also couldn't find anything on google except of this what I already tried.

Would be very nice if someone could help me here.
If you have any questions, just ask.

thx in advance :)

Body:
It might be the case here, that the actual date values of a.startDate and b.startDate during runtime are undefined.

You could try to see if you get some results again when you use this:

this.allEvents.sort((a, b) => (a.startDate && b.startDate) ? a.startDate.getTime() - b.startDate.getTime() : 0);

If you see (partially unsorted) results again, you know the issue is indeed caused by undefined values of those date fields. In that case, you can customize the sorting function further by correctly handling those undefined values:

this.allEvents.sort((a, b) => {
  if (a.startDate && b.startDate) {
    return a.startDate.getTime() - b.startDate.getTime();
  }
  else {
    // do something sophisticated regarding the `undefined` values and return a correct sorting value here...
  }
});


问:
how to compare type of an object's instance to a generic type?
how can i write this code in java?

```<code>public class ComponentsManager
    {
        private List<IComponent> list = new ArrayList<IComponent>();

        public <U extends IComponent> U GetComponent() {

            for (IComponent component : list) {

                if(component instanceof U)
                {
                    return component;
                }
            }
        }
}
</code>```

but i cant perform instanceof on generic types. how should i do it?
thanks.

答:
Basically you can't do that due to type erasure.  The normal workaround is to pass a Class object as a parameter; e.g.

```<code>    public <U extends IComponent> U GetComponent(Class<U> clazz) {
        for (IComponent component : list) {
            if (clazz.isInstance(component)) {
                return clazz.cast(component);
            }
        }
    }
</code>```

You could also use if (clazz.equals(component.getClass())) { ... but that does an exact type match ... which is not what the instanceof operator does.  The instanceof operator and the Class.instanceOf method both test to see if the value's type is assignment compatible.

ContentLicense: CC BY-SA 3.0

Body:
how can i write this code in java?

public class ComponentsManager
    {
        private List<IComponent> list = new ArrayList<IComponent>();

        public  U GetComponent() {

            for (IComponent component : list) {

                if(component instanceof U)
                {
                    return component;
                }
            }
        }
}

but i cant perform instanceof on generic types. how should i do it?
thanks.

Body:
Basically you can't do that due to type erasure.  The normal workaround is to pass a Class object as a parameter; e.g.

    public <U extends IComponent> U GetComponent(Class<U> clazz) {
        for (IComponent component : list) {
            if (clazz.isInstance(component)) {
                return clazz.cast(component);
            }
        }
    }

You could also use if (clazz.equals(component.getClass())) { ... but that does an exact type match ... which is not what the instanceof operator does.  The instanceof operator and the Class.instanceOf method both test to see if the value's type is assignment compatible.


问:
How can I add two different tensorflow models from two different applications?
I use two models from two diffrent applications. First one is EAST Scene Text Detector and second is Calamari Ocr. Both of them use Tensorflow. Code is as followed:

```<code>east_detector = EASTDetector(model_path='east_models/EAST_IC15+13_model.h5')
calamari = ocr.Predictor(checkpoint='calamari_models/model_00623553.ckpt')
</code>```

There is not a parameter, method etc to set Tensorflow session for both applications. Is there a way to allow two models to run in same tf session?

答:
I haven't checked how to do it in TensorFlow 2 but I have implemented it in TF-1 quite a year back.

you can check this python Notebook

here I have merged two Xception models in one by averaging their output of the softmax layer(kind off ensembling technique.)

For Keras model(h5), you need to convert that model from h5 to ckpt formate to use the above code using tf.Saver.

Body:
I use two models from two diffrent applications. First one is EAST Scene Text Detector and second is Calamari Ocr. Both of them use Tensorflow. Code is as followed:

east_detector = EASTDetector(model_path='east_models/EAST_IC15+13_model.h5')
calamari = ocr.Predictor(checkpoint='calamari_models/model_00623553.ckpt')

There is not a parameter, method etc to set Tensorflow session for both applications. Is there a way to allow two models to run in same tf session?


问:
Check for existence of at least one string in a list
I have code that checks whether there is at least one of the modal verbs in my word_list.

```<code>with open('Requirements_good.txt') as myfile:
    word_list=[word for line in myfile for word in line.split()]

with open('Badwords_modalverbs.txt') as file:
    modalv = 0
    for word in file.readlines():
        if word.strip() in word_list:
            modalv = 1
    if modalv == 1:
        print ("one of the words found")
</code>```

But there must be an easier, more elegant way to solve this. What is the quickest way to check it?

And how would one check for the opposit?: print anything if none of the words are found

答:
First, make word_list a set instead of a list, so that it's efficient to test membership of it. Then, you can use the any function:

with open('Requirements_good.txt') as myfile:
    # set comprehension instead of list comprehension
    word_set = {word for line in myfile for word in line.split()}

with open('Badwords_modalverbs.txt') as file:
    if any(word.strip() in word_set for word in file):
        print("one of the words found")
```

This is more efficient because you're no longer searching a list to test membership, but also the any function won't keep searching after it finds one match. The file.readlines() function is also unnecessary here; for word in file iterates over the lines without creating a list first.

Body:
I have code that checks whether there is at least one of the modal verbs in my word_list.

with open('Requirements_good.txt') as myfile:
    word_list=[word for line in myfile for word in line.split()]

with open('Badwords_modalverbs.txt') as file:
    modalv = 0
    for word in file.readlines():
        if word.strip() in word_list:
            modalv = 1
    if modalv == 1:
        print ("one of the words found")

But there must be an easier, more elegant way to solve this. What is the quickest way to check it?

And how would one check for the opposit?: print anything if none of the words are found

Body:
First, make word_list a set instead of a list, so that it's efficient to test membership of it. Then, you can use the any function:

with open('Requirements_good.txt') as myfile:
    # set comprehension instead of list comprehension
    word_set = {word for line in myfile for word in line.split()}

with open('Badwords_modalverbs.txt') as file:
    if any(word.strip() in word_set for word in file):
        print("one of the words found")

This is more efficient because you're no longer searching a list to test membership, but also the any function won't keep searching after it finds one match. The file.readlines() function is also unnecessary here; for word in file iterates over the lines without creating a list first.


问:
jsTree - disable drag option
how can I disable draggable option in jsTree? I want to disable moving nodes. How can I achieve this?</p>

答:
The property is_draggable seems to only disable dragging the Nodes to other positions inside the Tree. But the Nodes still remain draggable on the Page.
So it's possible for example to drag the Node to an input field on the Page.

Since researching how to completely disable the dragging took me a while, this might be usefull for others that stumble upon this topic.

You can completely disable dragging by calling preventDefault() on the Event:

```<code>dnd: {
      "is_draggable": function (node) {
         e.preventDefault();
         return false;
      }
}
</code>```

https://github.com/vakata/jstree/issues/1103

ContentLicense: CC BY-SA 2.5

Title: jsTree - disable drag option

Body:
The property is_draggable seems to only disable dragging the Nodes to other positions inside the Tree. But the Nodes still remain draggable on the Page.
So it's possible for example to drag the Node to an input field on the Page.

Since researching how to completely disable the dragging took me a while, this might be usefull for others that stumble upon this topic.

You can completely disable dragging by calling preventDefault() on the Event:

dnd: {
      "is_draggable": function (node) {
         e.preventDefault();
         return false;
      }
}

https://github.com/vakata/jstree/issues/1103


问:
Validator giving stray start tag error but I have no script and nothing outside  except !DOCTYPE
I'm getting the "Error: Stray start tag script" in the W3 Nu Html Checker. I have no script (because I haven't learned any yet, lol) and I also have nothing outside my  tags except for !DOCTYPE.

Here's my code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="styles.css">
    <link rel="shortcut icon" href="https://res.cloudinary.com/amanda-sterling-art/image/upload/v1578777557/AmandaSterling.Art/favicon_dkiz5j.ico" />
    <link href="https://fonts.googleapis.com/css?family=Walter+Turncoat&display=swap" rel="stylesheet">
    <title>Amanda Sterling Art</title>

Amanda Sterling Art

Etsy

Redbubble

Instagram (art)

Instagram (photography)

Twitter

Pinterest

Contact

            © Amanda Sterling Fink 2020

```

答:
When your checking source codes for errors you should always check that there is not stuff being prepended or appended to your file. if there is change hosting providers there are loads that offer free hosting without in-page advertisements use one of them. https://www.free-webhosts.com/ (you want one without forced adds)

You should also always go to the page in the browser and view the source of the page from the server, not the code you have written to check for appended or prepended content to do this go to the page in your browser and (right-click, view source)

Title: Validator giving stray start tag error but I have no script and nothing outside <html> except !DOCTYPE


问:
PayPal Express Checkout Shipping Calculations
I would like to:

Have the user log into paypal

Fetch the users information (billing&shipping addresses)

Then calculate the shipping fee

Place the payment

But, how can I receive the address and calculate the fee before I place the payment?

```<code><script>
paypal.Button.render({
    // Configure environment
    env: '<?php echo $paypal->paypalEnv; ?>',
    client: {
        sandbox: '<?php echo $paypal->paypalClientID; ?>',
        production: '<?php echo $paypal->paypalClientID; ?>'
    },
    // Customize button (optional)
    locale: 'de_DE',
    style: {
        size: 'small',
        color: 'gold',
        shape: 'rect',
    },
    // Set up a payment
    payment: function (data, actions) {
        return actions.payment.create({
            transactions: [{
                amount: {
                    total: '10',
                    currency: 'EUR'
                }
            }]
      });
    },
    // Execute the payment
    onAuthorize: function (data, actions) {
        return actions.payment.execute()
        .then(function () {
            window.location = "process.php?paymentID="+data.paymentID+"&token="+data.paymentToken+"&payerID="+data.payerID+"&pid=<?php echo $productID; ?>";
        });
    }
}, '#paypal-button');
</script>
</code>```

Instead of "return actions.payment.execute()" calling the execute directly, I would like to fetch the address, then show the final basket with all the costs and then click on "pay now" - how can I do this?

答:
thank you! mhhh okay but what has to be in the serverside part? i dont see any example of the actions to receive the buyers adress information before checkout and afterwards. ?

/demo/checkout/api/paypal/order/create

Body:
I would like to:

Have the user log into paypal

Fetch the users information (billing&shipping addresses)

Then calculate the shipping fee

Place the payment

But, how can I receive the address and calculate the fee before I place the payment?

Instead of "return actions.payment.execute()" calling the execute directly, I would like to fetch the address, then show the final basket with all the costs and then click on "pay now" - how can I do this?


问:
Java GWT Application - Compile Works Sometimes and Sometimes Not
Hopefully I provide everything needed for this:

Java 8
GWT 2.5.1
Eclipse 2018-09 (4.9.0)
Git

I have a project that I cannot get to consistently compile.  In Eclipse, I compile using the GWT -> Compile option, while on our web servers we use Ant.

I can get successful compiles on one or more of these machines (we have a Dev and a QA server).  I can get them to compile once, twice, maybe three times.  Then, on any machine, it will fail and fail and fail.

The error is this:

[ERROR] Errors in 'jar:file:/C:/Users/htaylor/git/codemanagerclient/CodeManagerClient/war/WEB-INF/lib/guava-gwt-12.0.jar!/com/google/common/base/Strings.java'
      [ERROR] Line 1: The type java.util.regex.Pattern cannot be resolved. It is indirectly referenced from required .class files

I've only been coding with Java for a bit over a year and I'm just frankly stumped. I don't understand why it would compile one time and then not the next, even when done immediately after the successful one.  To me, it suggests that something is not getting done in the same, proper, order each time.

I'm just wondering if anyone can help shed some light on this.

答:
I appreciate your comments.  I do not disagree with those of you saying our stuff is too old. It definitely is. The reasons for that are complicated. All I can say is, we're working on it.

I also appreciate the suggestion about using regex from the GWT libraries. I may test that out.

I did resolve my problem, not so much by solving it as by working around it. I was able to determine that we only used one method from the Strings.java class, and that was isNullOrEmpty().  And we only used it a few times in two classes. I just wrote a local version of that method in those classes, which meant that the compiler was no longer looking for the class. It's cheesy and is essentially a dodge, but it worked in this case.


问:
Cancel async fetch request in React Native using Expo
I have a React Native app that has been built using Expo (v35.0.0). I have a simple async function (loadData()) that runs a fetch (via fetchData()) request to an API that the response is then passed into my redux store:

```<code>const loadData = async (id, token) => {
  setIsLoading(true);
  try {
    await dispatch(fetchData(id, token));
  } catch (error) {
    setHasError(true);
  }
  setIsLoading(false);
};

useEffect(() => {
  loadData(user.client.id, user.token);
}, [user.client.id]);
</code>```

However, when the user logs out we are presented with the warning: "Can't perform a React state update on an unmounted component", which I understand is because the async request has been cancelled.

I have attempted to implement the AbortController approach (as outlined in this article: https://dev.to/iquirino/react-hook-clean-up-useeffect-24e7), however then we are presented with an error stating AbortConroller is unknown.

I thought that support for AbortConroller would be within Expo now as it was added to React Native back in July last year as part of the v0.60 release.

So, is it possible to implement AbortController within Expo to cancel the async request? If not, how should I go about cancelling the request to avoid the warning (& memory leak)?

答:
Because your dispatch is async, it's possible for it to finish after your component is unmounted.

Inside useEffect you can return a function that you call to cleanup.  Here you can set a flag to indicate the component is no longer mounted, and if this flag indicates it's no longer mounted, you can tell it not to update state.

eg.

```<code>let mounted = true;

const loadData = async (id, token) => {
  setIsLoading(true);
  try {
    await dispatch(fetchData(id, token));
  } catch (error) {
    if (mounted) setHasError(true);
  }
  if (mounted) setIsLoading(false);
};

useEffect(() => {
  loadData(user.client.id, user.token);
  return () => mounted = false;
}, [user.client.id]);
</code>```

Body:
I have a React Native app that has been built using Expo (v35.0.0). I have a simple async function (loadData()) that runs a fetch (via fetchData()) request to an API that the response is then passed into my redux store:

const loadData = async (id, token) => {
  setIsLoading(true);
  try {
    await dispatch(fetchData(id, token));
  } catch (error) {
    setHasError(true);
  }
  setIsLoading(false);
};

useEffect(() => {
  loadData(user.client.id, user.token);
}, [user.client.id]);

However, when the user logs out we are presented with the warning: "Can't perform a React state update on an unmounted component", which I understand is because the async request has been cancelled.

I have attempted to implement the AbortController approach (as outlined in this article: https://dev.to/iquirino/react-hook-clean-up-useeffect-24e7), however then we are presented with an error stating AbortConroller is unknown.

I thought that support for AbortConroller would be within Expo now as it was added to React Native back in July last year as part of the v0.60 release.

So, is it possible to implement AbortController within Expo to cancel the async request? If not, how should I go about cancelling the request to avoid the warning (& memory leak)?

Body:
Because your dispatch is async, it's possible for it to finish after your component is unmounted.

Inside useEffect you can return a function that you call to cleanup.  Here you can set a flag to indicate the component is no longer mounted, and if this flag indicates it's no longer mounted, you can tell it not to update state.

eg.

let mounted = true;

const loadData = async (id, token) => {
  setIsLoading(true);
  try {
    await dispatch(fetchData(id, token));
  } catch (error) {
    if (mounted) setHasError(true);
  }
  if (mounted) setIsLoading(false);
};

useEffect(() => {
  loadData(user.client.id, user.token);
  return () => mounted = false;
}, [user.client.id]);


问:
UPDATE or MERGE of very big tables in SQL Server
I need to perform a daily update of a very large (300M records) and broad TABLE1. The the source data for the updates is located in another table UTABLE that is 10%-25% the rows of TABLE1 but is narrow. Both tables have record_id as a primary key.

Presently, I am recreating TABLE1 using the following approach:

```<code><!-- language: sql -->
    1) SELECT (required columns) INTO TMP_TABLE1
    FROM TABLE1 T join UTABLE U on T.record_id=U.record_id
    2) DROP TABLE TABLE1
    3) sp_rename 'TMP_TABLE1', 'TABLE1'
</code>```

However this takes nearly 40 minutes on my server (60GB of RAM for SQL Server). I want to achieve a 50% performance gain - what other options can I try?

MERGE and UPDATE - something like the code below works faster only for a very small UTABLE table - at full size, everything just hangs:

```<code><!-- language: SQL -->
MERGE TABLE1 as target
USING UTABLE as source
ON target.record_id = source.record_id
  WHEN MATCHED THEN
    UPDATE SET Target.columns=source.columns
</code>```

I heard that I can perform a batch MERGE by using ROWCOUNT - but I don't think it can be fast enough for a 300M row table.

Any SQL query hints that can be helpful?

答:
Actually i've found out general recommendations for such a queries: Idea to use SQL Merge or Update is a very clever one but it fails when we need to update many records (i.e. 75M) in a big and wide table (i.e. 240M).

Looking at the query plan of the query below we can say that TABLE SCAN of TABLE1 and final MERGE are taking 90% of time.

```<code>MERGE TABLE1 as Target
USING UTABLE as source
ON Target.record_id = source.record_id
WHEN MATCHED AND (condition) THEN
    UPDATE SET Target.columns=source.columns
</code>```

So in order to use MERGE we need to:

Reduce the number of rows we need to update and correctly pass this information to SQL Server. This can be done by making UTABLE smaller or specifying additional condition that narrows part to-be-merged.

Make sure that part to-be-merged fits in memory otherwise query runs way slower. Making TABLE1 twice less reduced my real query time from 11 hours to 40 minutes.

As Mark mentioned you can use UPDATE syntax and use WHERE clause to narrow part to-be-merged - this will give same results. Also please avoid indexing TABLE1 as this will cause additional work to rebuild index during MERGE

Body:
I need to perform a daily update of a very large (300M records) and broad TABLE1. The the source data for the updates is located in another table UTABLE that is 10%-25% the rows of TABLE1 but is narrow. Both tables have record_id as a primary key.

Presently, I am recreating TABLE1 using the following approach:

    1) SELECT (required columns) INTO TMP_TABLE1
    FROM TABLE1 T join UTABLE U on T.record_id=U.record_id
    2) DROP TABLE TABLE1
    3) sp_rename 'TMP_TABLE1', 'TABLE1'

However this takes nearly 40 minutes on my server (60GB of RAM for SQL Server). I want to achieve a 50% performance gain - what other options can I try?

MERGE and UPDATE - something like the code below works faster only for a very small UTABLE table - at full size, everything just hangs:

MERGE TABLE1 as target
USING UTABLE as source
ON target.record_id = source.record_id
  WHEN MATCHED THEN
    UPDATE SET Target.columns=source.columns

I heard that I can perform a batch MERGE by using ROWCOUNT - but I don't think it can be fast enough for a 300M row table.

Any SQL query hints that can be helpful?

Body:
Actually i've found out general recommendations for such a queries: Idea to use SQL Merge or Update is a very clever one but it fails when we need to update many records (i.e. 75M) in a big and wide table (i.e. 240M).

Looking at the query plan of the query below we can say that TABLE SCAN of TABLE1 and final MERGE are taking 90% of time.

MERGE TABLE1 as Target
USING UTABLE as source
ON Target.record_id = source.record_id
WHEN MATCHED AND (condition) THEN
    UPDATE SET Target.columns=source.columns

So in order to use MERGE we need to:

Reduce the number of rows we need to update and correctly pass this information to SQL Server. This can be done by making UTABLE smaller or specifying additional condition that narrows part to-be-merged.

Make sure that part to-be-merged fits in memory otherwise query runs way slower. Making TABLE1 twice less reduced my real query time from 11 hours to 40 minutes.

As Mark mentioned you can use UPDATE syntax and use WHERE clause to narrow part to-be-merged - this will give same results. Also please avoid indexing TABLE1 as this will cause additional work to rebuild index during MERGE


问:
I want moving test-output folder from project to other directory where should I put that moving folder code in set up or tear down?
I want to move test-output folder from project to other directory that I don't need  every time in selenium where should I put that moving folder code in set up or tear down?</p>

答:
There is couple of ways to do that :

```<code>new File("/source/directory").renameTo(new File("/target/directory"));
</code>```

And there is File.move() method which you can check oracle document too.

Fo Maven, report output directory(or similar fields) in pom.xml file change it as following :

```<code><outputDirectory>${user.home}/directory/target</outputDirectory>
</code>```

Body:
There is couple of ways to do that :

new File("/source/directory").renameTo(new File("/target/directory"));

And there is File.move() method which you can check oracle document too.

Fo Maven, report output directory(or similar fields) in pom.xml file change it as following :

<outputDirectory>${user.home}/directory/target</outputDirectory>


问:
Passing a variable into a class to determine which method to use
im not sure what im missing but it says that my class variable (var1) is not defined

```<code>Class Example(var1):
   if var1 ==1:
      def func1(var2)
         x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
         Return x
   else pass:

Example(1).func1("example")
</code>```

could be because im tired and its simple but im also kinda new to this. Any help would be great and thank you

答:
Your Syntax is very messed up, lost of mistakes, but cleaned up it would look like this:</p>

```<code>class Example():
    def __init__(self,var1):
       if var1 ==1:
          def func1(var2):
             x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
             print(var2)
             return x
       else:
           pass

#Example(1).func1("example") you can not call 'func1'. At this point it doesnt exists!!

example = Example(1)
</code>```

Body:
im not sure what im missing but it says that my class variable (var1) is not defined

Class Example(var1):
   if var1 ==1:
      def func1(var2)
         x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
         Return x
   else pass:

Example(1).func1("example")

could be because im tired and its simple but im also kinda new to this. Any help would be great and thank you

Body:
Your Syntax is very messed up, lost of mistakes, but cleaned up it would look like this:

class Example():
    def __init__(self,var1):
       if var1 ==1:
          def func1(var2):
             x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
             print(var2)
             return x
       else:
           pass

#Example(1).func1("example") you can not call 'func1'. At this point it doesnt exists!!

example = Example(1)


问:
Use "use" in ext_localconf.php in TYPO3? (Fatal error: Cannot use ... as ... because the name is already in use in)
I just had an error because of this:

```<code>Fatal error: Cannot use TYPO3\CMS\Core\Utility\GeneralUtility
as GeneralUtility because the name is already in use
in /var/www/mysite/public/typo3temp/var/cache/code/cache_core/ext_localconf_feb178af00fe22e00dc62d7dcd6d4d16f5d4fc3a.php
on line 4508
</code>```

Reason was the following line in a file ext_localconf.php of an extension:

```<code>use TYPO3\CMS\Core\Utility\GeneralUtility;
</code>```

Apparently, some extensions use "use" in ext_localconf.php on my system. As this is all concatenated into one file in the cache, this can lead to multiple use statements.

Is there still some way to use "use" without causing these errors? What is the recommended way?

Update: As stated in the answer by Rudy, since TYPO3 v11, it is possible to use "use" also in ext_localconf.php, ext_tables.php etc.

答:
Updated for TYPO3 11: With 11.4 the files ext_localconf.php and ext_tables.php are scoped into the global namespace on being warmed up from the cache. Therefore use statements can now be used inside these files.

https://docs.typo3.org/m/typo3/reference-coreapi/11.5/en-us/ExtensionArchitecture/ConfigurationFiles/Index.html

For older versions < v11:

use used for importing/aliasing namespaces in PHP can only be used in global scope, not in block scope. See https://www.php.net/manual/en/language.namespaces.importing.php#language.namespaces.importing.scope. So you shouldn't use use at all in ext_localconf.php and just use full namespaces instead.

If there are extensions that do use use in ext_localconf.php you should let the maintainers of that extension know this is wrong and can (and will) cause fatal errors.

Body:
I just had an error because of this:

Fatal error: Cannot use TYPO3\CMS\Core\Utility\GeneralUtility
as GeneralUtility because the name is already in use
in /var/www/mysite/public/typo3temp/var/cache/code/cache_core/ext_localconf_feb178af00fe22e00dc62d7dcd6d4d16f5d4fc3a.php
on line 4508

Reason was the following line in a file ext_localconf.php of an extension:

use TYPO3\CMS\Core\Utility\GeneralUtility;

Apparently, some extensions use "use" in ext_localconf.php on my system. As this is all concatenated into one file in the cache, this can lead to multiple use statements.

Is there still some way to use "use" without causing these errors? What is the recommended way?

Update: As stated in the answer by Rudy, since TYPO3 v11, it is possible to use "use" also in ext_localconf.php, ext_tables.php etc.


问:
Filling database with some data (Users, Invoices, etc...)
I would like to fill my database with some data to let frontend developers start working with my API. I don't want this data to go live in production and so, doesn't feel it falls into the category of "Seeded data". For me, seeded data is data that goes into production and needs to be in the database before my application starts. For example, list of countries, etc.

In my case, I would like to add some users, some invoices linked to the users, some products, etc. And would be nice if this is done when doing thte deployment when we are in development stage.

Any suggestion would be really appreciated.

答:
I would create DataInitializer class to seed all needed data if environment is set to "Development".

E.g. creating user:

```<code>    public static class IdentityDataInitializer
{
    private static void SeedUsers(UserManager<ApplicationUser> userManager)
    {
        if (userManager.FindByNameAsync("Admin").Result == null)
        {
            ApplicationUser admin = new ApplicationUser()
            {
                UserName = "Admin",
                Email = "Admin@admin.com",
                RegistrationDate = DateTime.Now
            };

            string password = "Admin1";

            var result = userManager.CreateAsync(admin, password);

            if (result.Result.Succeeded)
            {
                userManager.AddToRoleAsync(admin, "Admin").Wait();
            }
        }
    }
}
</code>```

Once all methods will be ready, just add this to your Startup.cs:

```<code>        public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            IdentityDataInitializer.SeedDefaultData(userManager, roleManager);
        }

        //Some methods...
    }
}
</code>```

Body:
I would create DataInitializer class to seed all needed data if environment is set to "Development".

E.g. creating user:

    public static class IdentityDataInitializer
{
    private static void SeedUsers(UserManager<ApplicationUser> userManager)
    {
        if (userManager.FindByNameAsync("Admin").Result == null)
        {
            ApplicationUser admin = new ApplicationUser()
            {
                UserName = "Admin",
                Email = "Admin@admin.com",
                RegistrationDate = DateTime.Now
            };

            string password = "Admin1";

            var result = userManager.CreateAsync(admin, password);

            if (result.Result.Succeeded)
            {
                userManager.AddToRoleAsync(admin, "Admin").Wait();
            }
        }
    }
}

Once all methods will be ready, just add this to your Startup.cs:

        public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            IdentityDataInitializer.SeedDefaultData(userManager, roleManager);
        }

        //Some methods...
    }
}


问:
For "Auto-Renewable Subscription", if I want to have more than one subscription in my product, how can I set things up?
Say I am developing a game.

I want to offer two different subscription memberships.

$5 monthly, VIP Basic: Can get 100 gems per day.
$9 monthly, VIP Advanced: Can get 300 gems per day.

Can I set up two subscription memberships?

What if the user purchase VIP Basic for 3 days and want to upgrade to VIP Advanced, does he/she have an option to upgrade or he/she has to wait for the first subscription to expire?

Thanks,

答:
You can have multiple subscription options and your users can change their subscription preferences whenever they'd like. Although there are many different tutorials on the internet some things are recommended by almost everyone:

First things first you'll need to verify the subscriptions of your users by sending a receipt data to Apple's iTunes servers. Do NOT do it on the phone or locally. Do it on a web server of your own, preferably having HTTPS certificate.

Remember to store a user's subscription either locally or on a web server since Apple Review documents requires your users to have the edit option available to them in your app.

Users should have the restore option available to them as well. So don't forget to add that to your subscription integration.

When displaying your subscription prices and details do it by fetching their info from Apple. Don't add static texts or prices since review team will reject your app because of this.

Subscription prices can be changed for each country from Appstore Connect panel. Remember to adjust the prices based on certain countries economic state.

You can't test real subscription options on development environment thus you'll need to use some sandbox environment parameters. Don't forget to remove them when you are sending an update.

Lastly here is a good tutorial with example codes on how to add auto-renewable subscriptions to an app.


问:
I can't update my string value with React hooks
Its like the simplest of cases you can think of,

I have a select which updates a string according to the value which is supposed to update a property of the select itself (its background color)

I am using React hooks and Styled Components to achieve this.

I have Redux to be able to bind it an immutable array of colors in the future.

The question is simple, why can't I update the state? I have tried to print it and it is always an empty string.

Here is my styles file

```<code>let currentColor = '';

const SelectColor = styled.div`
  select{
    background-color: ${currentColor || 'black'};
  }
  .label{
    width: 150px;
    font-size: 14px;
    text-align: left;
    margin-left: 6px;
  }
`;
</code>```

This is the component that isn't updating the selectValue for reasons I cannot grasp(I have attempted to console log it and it returns always empty string).
I have checked the documentation a couple times and it seems like its meant to be updated this way so I am clueless...

```<code>const SelectComponent = ({
  disabled,
  colorList,
  label,
  onSelect,
  ...restProps
}) => {
  const [selectValue, setSelectValue] = useState('');

  const handleChange = useCallback(
    (e) => {
      setSelectValue(e.target.value);
      console.log(selectValue);
    },colorList
  );

  return (
    <SelectColor>
      <span className='label'>{label}</span>
      <select onChange={e=>handleChange(e)}>
        {
          colorList.map(color =>
          <option key={color} value={color}>{color}</option>)
        };
      </select>
    </SelectColor>
  );
};

SelectComponent.propTypes = {
  disabled: PropTypes.bool,
  hourValue: PropTypes.number,
  projectName: PropTypes.string,
};

export default SelectComponent;
</code>```

答:
Here you have some fixes, check the comments in the code:

```<code>// SelectComponent
const SelectComponent = ({
  disabled,
  colorList,
  label,
  onSelect,
  ...restProps
}) => {
  const [selectValue, setSelectValue] = useState('');

  // Make this a function, not an arrow function.
  // It's unnecessary in this case due to not needing a binding
  function handleChange(e) {
    setSelectValue(e.target.value);
  }

  // send currentColor as a prop to your styled component and remove
  // the arrow onChange, not needed.
  return (
    <SelectColor currentColor={selectValue}>
      <span className='label'>{label}</span>
      <select onChange={handleChange}>
        {
          colorList.map(color =>
          <option key={color} value={color}>{color}</option>)
        };
      </select>
    </SelectColor>
  );
};

SelectComponent.propTypes = {
  disabled: PropTypes.bool,
  hourValue: PropTypes.number,
  projectName: PropTypes.string,
};

export default SelectComponent;
</code>```

```<code>// Your styled components receives now a prop with the name currentColor.
// Use it inside the interpolation string ${} and set the value
const SelectColor = styled.div`
  select{
    background-color: ${(props) => props.currentColor || 'black'};
  }
  .label{
    width: 150px;
    font-size: 14px;
    text-align: left;
    margin-left: 6px;
  }
`;
</code>```

Hope this helps! Ask whatever you feel necessary, I'll help if I'm available!

Body:
Its like the simplest of cases you can think of,

I have a select which updates a string according to the value which is supposed to update a property of the select itself (its background color)

I am using React hooks and Styled Components to achieve this.

I have Redux to be able to bind it an immutable array of colors in the future.

The question is simple, why can't I update the state? I have tried to print it and it is always an empty string.

Here is my styles file

let currentColor = '';

const SelectColor = styled.div`
  select{
    background-color: ${currentColor || 'black'};
  }
  .label{
    width: 150px;
    font-size: 14px;
    text-align: left;
    margin-left: 6px;
  }
`;

This is the component that isn't updating the selectValue for reasons I cannot grasp(I have attempted to console log it and it returns always empty string).
I have checked the documentation a couple times and it seems like its meant to be updated this way so I am clueless...

const SelectComponent = ({
  disabled,
  colorList,
  label,
  onSelect,
  ...restProps
}) => {
  const [selectValue, setSelectValue] = useState('');

  const handleChange = useCallback(
    (e) => {
      setSelectValue(e.target.value);
      console.log(selectValue);
    },colorList
  );

  return (
    <SelectColor>
      {label}
      <select onChange={e=>handleChange(e)}>
        {
          colorList.map(color =>
          <option key={color} value={color}>{color}</option>)
        };
      </select>
    </SelectColor>
  );
};

SelectComponent.propTypes = {
  disabled: PropTypes.bool,
  hourValue: PropTypes.number,
  projectName: PropTypes.string,
};

export default SelectComponent;

Body:
Here you have some fixes, check the comments in the code:

// SelectComponent
const SelectComponent = ({
  disabled,
  colorList,
  label,
  onSelect,
  ...restProps
}) => {
  const [selectValue, setSelectValue] = useState('');

  // Make this a function, not an arrow function.
  // It's unnecessary in this case due to not needing a binding
  function handleChange(e) {
    setSelectValue(e.target.value);
  }

  // send currentColor as a prop to your styled component and remove
  // the arrow onChange, not needed.
  return (
    <SelectColor currentColor={selectValue}>
      <span className='label'>{label}</span>
      <select onChange={handleChange}>
        {
          colorList.map(color =>
          <option key={color} value={color}>{color}</option>)
        };
      </select>
    </SelectColor>
  );
};

SelectComponent.propTypes = {
  disabled: PropTypes.bool,
  hourValue: PropTypes.number,
  projectName: PropTypes.string,
};

export default SelectComponent;

// Your styled components receives now a prop with the name currentColor.
// Use it inside the interpolation string ${} and set the value
const SelectColor = styled.div`
  select{
    background-color: ${(props) => props.currentColor || 'black'};
  }
  .label{
    width: 150px;
    font-size: 14px;
    text-align: left;
    margin-left: 6px;
  }
`;

Hope this helps! Ask whatever you feel necessary, I'll help if I'm available!


问:
Optimise Django query
I have a model in my Django project:

```<code>class AmazonSearchFrequency(models.Model):
    keyword_name = models.CharField(max_length=500)
    frequency = models.PositiveIntegerField(default=0)
</code>```

I am storing around 2 million rows of data in this table but whenever I do a search query like

```<code>AmazonSearchFrequency.objects.filter(keyword_name=keyword)
</code>```

it takes a long time to execute the query.

Is there any way in Django to optimize this query?

答:
Always index columns that you will use in filters later on. This is how databases can significantly speed up searches. Without an index, the db has to go through every single row!

In you case, this would look like this:

```<code>class AmazonSearchFrequency(models.Model):
    keyword_name = models.CharField(max_length=500)
    frequency = models.PositiveIntegerField(default=0)

    class Meta:
        indexes = [
            models.Index(fields=['keyword_name'], name='keyword_name_idx'),
        ]
</code>```

Don't forget to make migrations and migrate after adding an index.

Note: primary keys, foreign keys and fields set as unique or unique_together are indexed by default, you don't need to add those.

Title: Optimise Django query

Body:
I have a model in my Django project:

class AmazonSearchFrequency(models.Model):
    keyword_name = models.CharField(max_length=500)
    frequency = models.PositiveIntegerField(default=0)

I am storing around 2 million rows of data in this table but whenever I do a search query like

AmazonSearchFrequency.objects.filter(keyword_name=keyword)

it takes a long time to execute the query.

Is there any way in Django to optimize this query?

Body:
Always index columns that you will use in filters later on. This is how databases can significantly speed up searches. Without an index, the db has to go through every single row!

In you case, this would look like this:

class AmazonSearchFrequency(models.Model):
    keyword_name = models.CharField(max_length=500)
    frequency = models.PositiveIntegerField(default=0)

    class Meta:
        indexes = [
            models.Index(fields=['keyword_name'], name='keyword_name_idx'),
        ]

Don't forget to make migrations and migrate after adding an index.

Note: primary keys, foreign keys and fields set as unique or unique_together are indexed by default, you don't need to add those.


问:
ISNA: Return "YES", "NO" in nested formula
I'm trying to get it to return YES/NO instead of the the lookup value/#N/A by using ISNA, but I'm not sure where to place it.

Here is my formula:

```<code>=IF(AND([@Center]="London",[@Reportable]="YES"),VLOOKUP([@ID],Client!C:C,1,FALSE),"IGNORE")
</code>```

答:
try the following:

```<code>=IF(AND([@Center]="London",[@Reportable]="YES"),ISNA(VLOOKUP([@ID],Client!C:C,1,FALSE)),"IGNORE")
</code>```

You have to wrap with ISNA the desired part of the formula to be affected.

I believe this is what you are looking for.

Nevetheless, this will output TRUE/FALSE, not YES/NO.

Hope it helps.

Body:
I'm trying to get it to return YES/NO instead of the the lookup value/#N/A by using ISNA, but I'm not sure where to place it.

Here is my formula:

=IF(AND([@Center]="London",[@Reportable]="YES"),VLOOKUP([@ID],Client!C:C,1,FALSE),"IGNORE")

Body:
try the following:

=IF(AND([@Center]="London",[@Reportable]="YES"),ISNA(VLOOKUP([@ID],Client!C:C,1,FALSE)),"IGNORE")

You have to wrap with ISNA the desired part of the formula to be affected.

I believe this is what you are looking for.

Nevetheless, this will output TRUE/FALSE, not YES/NO.

Hope it helps.


问:
Why I get the error: list index out of range

def sum13(nums):
  summ = 0
  for i in range(1, len(nums)):
    if nums[i] != 13 and nums[i-1] != 13:
     summ += nums[i]
  if nums[0] != 13:
    summ += nums[0]
  return summ
```

The error is produced by the last if and I don't understand why

答:
If you use Python enumerate, rather than a loop counter, to track your position in the array you can simplify the code to have a single if statement, and eliminate the error if the length of the list is zero:

def sum13(nums):
    summ = 0
    for ix, num in enumerate(nums):
        if ix == 0 or (num != 13 and nums[ix-1] != 13):
            summ += num
    return summ
```

When nums is empty, the for loop won't execute at all.

Because Python uses 'early termination' in the evaluation of if statements, it means that as soon as it detects that ix == 0 is True, it won't evaluate nums[ix-1] when ix is 0.

Body:
def sum13(nums):
  summ = 0
  for i in range(1, len(nums)):
    if nums[i] != 13 and nums[i-1] != 13:
     summ += nums[i]
  if nums[0] != 13:
    summ += nums[0]
  return summ

The error is produced by the last if and I don't understand why

Body:
If you use Python enumerate, rather than a loop counter, to track your position in the array you can simplify the code to have a single if statement, and eliminate the error if the length of the list is zero:

def sum13(nums):
    summ = 0
    for ix, num in enumerate(nums):
        if ix == 0 or (num != 13 and nums[ix-1] != 13):
            summ += num
    return summ

When nums is empty, the for loop won't execute at all.

Because Python uses 'early termination' in the evaluation of if statements, it means that as soon as it detects that ix == 0 is True, it won't evaluate nums[ix-1] when ix is 0.


问:
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81
I am currently new to robot framework.I am currently using latest window version of chrome and chromedriver which is 80 but when i try to run the test it gives the message "SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81" in pycharm but currently beta version of 81 is only available. I have tried uninstalling everthing and reinstalling it again but nothing works can anyone help me with this.Thank you!

Screenshots below:

答:
This error message...

```<code>SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81
</code>```

...implies that the ChromeDriver v81 was unable to initiate/spawn a new Browsing Context i.e. Chrome Browser where is version is other then 81.0.

Your main issue is the incompatibility between the version of the binaries you are using as follows:

You mentioned about using chromedriver=80 and chrome=80 but somehow while your program execution ChromeDriver v 81.0 is used.

So, it's quite evident your have chromedriver=81.0 present within your system and is present within the system PATH variable which gets invoked while you:

```<code>driver = webdriver.Chrome()
</code>```

Solution

There are two solutions:

Either you upgrade chrome to Chrome Version 81.0 level. (as per ChromeDriver v81.0 release notes)

Or you can override the default chromedriver v81.0 binary location with chromedriver v80.0 binary location as follows:

```<code>from selenium import webdriver

driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
driver.get('http://google.com/')
</code>```

Reference

You can find a couple of relevant discussions in:

How to work with a specific version of ChromeDriver while Chrome Browser gets updated automatically through Python selenium

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80

Ubuntu: selenium.common.exceptions: session not created: This version of ChromeDriver only supports Chrome version 79

Body:
This error message...

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

...implies that the ChromeDriver v81 was unable to initiate/spawn a new Browsing Context i.e. Chrome Browser where is version is other then 81.0.

Your main issue is the incompatibility between the version of the binaries you are using as follows:

You mentioned about using chromedriver=80 and chrome=80 but somehow while your program execution ChromeDriver v 81.0 is used.

So, it's quite evident your have chromedriver=81.0 present within your system and is present within the system PATH variable which gets invoked while you:

driver = webdriver.Chrome()

Solution

There are two solutions:

Either you upgrade chrome to Chrome Version 81.0 level. (as per ChromeDriver v81.0 release notes)

Or you can override the default chromedriver v81.0 binary location with chromedriver v80.0 binary location as follows:

from selenium import webdriver

driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
driver.get('http://google.com/')

Reference

You can find a couple of relevant discussions in:

How to work with a specific version of ChromeDriver while Chrome Browser gets updated automatically through Python selenium

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80

Ubuntu: selenium.common.exceptions: session not created: This version of ChromeDriver only supports Chrome version 79


问:
Triangulation Three.js algorithm
I am trying to make a triangulation algorithm, following simple rules, in javascript using Three.js.

Here are the actual steps:

We start with a square and "randomly" define heights for the cells, after a symmetric division in four parts.

I intend to make the "steps" with a dat.GUI panel.

I would really appreciate if someone can help me!

答:
Just use existing lib to get TIN data. For example earcut (some THREEJS examples already uses it). You can use earcut (trianle face data) output to create mesh with custom buffer geometry.
I prefer to use PostGIS for this (server-side processing). ST_DelaunayTriangles and ST_Tesselate are perfect.</p>

Title: Triangulation Three.js algorithm


问:
How to remove last 2 months records from 2 years records based on Date?
I have a DataFrame which having 2 years data, need to sort and remove recent 2 months records.

```<code>Ship_Date        Id

2019-10-29       i1
2019-10-29       i2
2019-10-28       i3
2019-10-28       i4
....
</code>```

I tried in this way but getting KeyError:

```<code>df.index = pd.DatetimeIndex(df.pop('Ship_Date'))
df.sort_index().last('2M').drop()
</code>```

Any help please

答:
Use DataFrame.drop with DatetimeIndex:

```<code>df.index = pd.DatetimeIndex(df.pop('Ship_Date'))
df = df.drop(df.sort_index().last('2M').index)
</code>```

Body:
I have a DataFrame which having 2 years data, need to sort and remove recent 2 months records.

Ship_Date        Id

2019-10-29       i1
2019-10-29       i2
2019-10-28       i3
2019-10-28       i4
....

I tried in this way but getting KeyError:

df.index = pd.DatetimeIndex(df.pop('Ship_Date'))
df.sort_index().last('2M').drop()

Any help please

Body:
Use DataFrame.drop with DatetimeIndex:

df.index = pd.DatetimeIndex(df.pop('Ship_Date'))
df = df.drop(df.sort_index().last('2M').index)


问:
Configure Eclipse workspace automatically
I have a eclipse workspace which constitutes of 15 different java projects . To configure the eclipse workspace , every time I need to add the java projects manually and add the dependency and refrences in the java build path.
Adding all the  projects and resolving dependency every time becomes a manual and redundant task. I explored on the .classpath inside the every projects which stores the dependency and refrences information.
I would like to automate this redundant process.
Have any one tried doing that , any inputs will be helpful.

I don't need to add same project more than once , but often need to create a new eclipse workspace with new code changes and delivery (I can't take some of the changes in the current work space).In simple terms for e.g if some one need to create eclipse workspace again and again , or multiple people need to create the same workspace for their work . How can we reduce that manual effort?

答: You should really look into build tools like Maven, Ant, .... Those can generate needed classpath variables for you automatically and can do many more things as well


问:
Error in pandas multiprocessing code - dataframe is not callable
I'm trying to optimise a distance calculation over a large file using multiprocessing. I've designed the below code, but can anyone explain why it throws the error ['DataFrame' object is not callable]?

It appears to be something to do with "map" inside parallelize_dataframe, possibly caused by how I've designed test_func, but not sure how to resolve. Thanks in advance for any help.

```<code>import multiprocessing as mp

nearest_calc3 = None
nearest_calc3 = postcodes.head(1000).copy() # Test top 1000

partitions = 5
cores = mp.cpu_count()

def parallelize_dataframe(data, func):
    data_split = np.array_split(data, partitions)
    pool = mp.Pool(cores)
    data = pd.concat(pool.map(func, data_split)) # <-- Problem here?
    pool.close()
    pool.join()
    return data

def nearest(inlat1, inlon1, inlat2, inlon2, store, postcode):
    lat1 = np.radians(inlat1)
    lat2 = np.radians(inlat2)
    longdif = np.radians(inlon2 - inlon1)
    r = 6371.1009 # gives d in kilometers
    d = np.arccos(np.sin(lat1)*np.sin(lat2) + np.cos(lat1)*np.cos(lat2) * np.cos(longdif)) * r
    near = pd.DataFrame({'store': store, 'postcode': postcode, 'distance': d})
    near_min = near.loc[near['distance'].idxmin()]
    x = str(near_min['store']) + '~' + str(near_min['postcode']) + '~' + str(near_min['distance'])
    return x

def test_func(data, stores): # <-- Or maybe here?
    data['appended'] = data['lat'].apply(nearest, args=(data['long'], stores['lat'], stores['long'], stores['index'], stores['pcds']))
    data[['store','store_postcode','distance_km']] = data['appended'].str.split("~",expand=True)
    return data

if __name__ == '__main__':
    test = parallelize_dataframe(nearest_calc3, test_func(nearest_calc3, stores))
</code>```

And the full error:

```<code>---------------------------------------------------------------------------
RemoteTraceback                           Traceback (most recent call last)
RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py", line 44, in mapstar
    return list(map(*args))
TypeError: 'DataFrame' object is not callable
"""

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-21-501c0f76106a> in <module>
     32 #x = test_func(nearest_calc3, stores)
     33
---> 34 test = parallelize_dataframe(nearest_calc3, test_func(nearest_calc3, stores))

<ipython-input-21-501c0f76106a> in parallelize_dataframe(data, func)
      9     data_split = np.array_split(data, partitions)
     10     pool = mp.Pool(cores)
---> 11     data = pd.concat(pool.map(func, data_split))
     12     pool.close()
     13     pool.join()

~\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py in map(self, func, iterable, chunksize)
    266         in a list that is returned.
    267         '''
--> 268         return self._map_async(func, iterable, mapstar, chunksize).get()
    269
    270     def starmap(self, func, iterable, chunksize=None):

~\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py in get(self, timeout)
    655             return self._value
    656         else:
--> 657             raise self._value
    658
    659     def _set(self, i, obj):

TypeError: 'DataFrame' object is not callable
</code>```

答:
The problem is in the last line:

```<code>test = parallelize_dataframe(nearest_calc3, test_func(nearest_calc3, stores))
</code>```

test_func(...) will return a dataframe and you pass that into parallelize_dataframe.
But this function is expecting a callable.

You want something like this:

```<code>test = parallelize_dataframe(nearest_calc3, test_func)
</code>```

As you want to always pass stores into test_func in addition to nearest_calc3, you could use partial to do so:

```<code>test_func_with_stores = functools.partial(test_func, stores)
</code>```

test_func_with_stores is then a callable that takes a single parameter.
Unfortunately partial fills the parameters from left to right, so you would have to change test_func so that stores is the first parameter.

Body:
I'm trying to optimise a distance calculation over a large file using multiprocessing. I've designed the below code, but can anyone explain why it throws the error ['DataFrame' object is not callable]?

It appears to be something to do with "map" inside parallelize_dataframe, possibly caused by how I've designed test_func, but not sure how to resolve. Thanks in advance for any help.

import multiprocessing as mp

nearest_calc3 = None
nearest_calc3 = postcodes.head(1000).copy() # Test top 1000

partitions = 5
cores = mp.cpu_count()

def parallelize_dataframe(data, func):
    data_split = np.array_split(data, partitions)
    pool = mp.Pool(cores)
    data = pd.concat(pool.map(func, data_split)) # <-- Problem here?
    pool.close()
    pool.join()
    return data

def nearest(inlat1, inlon1, inlat2, inlon2, store, postcode):
    lat1 = np.radians(inlat1)
    lat2 = np.radians(inlat2)
    longdif = np.radians(inlon2 - inlon1)
    r = 6371.1009 # gives d in kilometers
    d = np.arccos(np.sin(lat1)*np.sin(lat2) + np.cos(lat1)*np.cos(lat2) * np.cos(longdif)) * r
    near = pd.DataFrame({'store': store, 'postcode': postcode, 'distance': d})
    near_min = near.loc[near['distance'].idxmin()]
    x = str(near_min['store']) + '~' + str(near_min['postcode']) + '~' + str(near_min['distance'])
    return x

def test_func(data, stores): # <-- Or maybe here?
    data['appended'] = data['lat'].apply(nearest, args=(data['long'], stores['lat'], stores['long'], stores['index'], stores['pcds']))
    data[['store','store_postcode','distance_km']] = data['appended'].str.split("~",expand=True)
    return data

if __name__ == '__main__':
    test = parallelize_dataframe(nearest_calc3, test_func(nearest_calc3, stores))

And the full error:

---------------------------------------------------------------------------
RemoteTraceback                           Traceback (most recent call last)
RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py", line 44, in mapstar
    return list(map(*args))
TypeError: 'DataFrame' object is not callable
"""

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-21-501c0f76106a> in <module>
     32 #x = test_func(nearest_calc3, stores)
     33
---> 34 test = parallelize_dataframe(nearest_calc3, test_func(nearest_calc3, stores))

<ipython-input-21-501c0f76106a> in parallelize_dataframe(data, func)
      9     data_split = np.array_split(data, partitions)
     10     pool = mp.Pool(cores)
---> 11     data = pd.concat(pool.map(func, data_split))
     12     pool.close()
     13     pool.join()

~\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py in map(self, func, iterable, chunksize)
    266         in a list that is returned.
    267         '''
--> 268         return self._map_async(func, iterable, mapstar, chunksize).get()
    269
    270     def starmap(self, func, iterable, chunksize=None):

~\AppData\Local\Continuum\anaconda3\lib\multiprocessing\pool.py in get(self, timeout)
    655             return self._value
    656         else:
--> 657             raise self._value
    658
    659     def _set(self, i, obj):

TypeError: 'DataFrame' object is not callable

Body:
The problem is in the last line:

test = parallelize_dataframe(nearest_calc3, test_func(nearest_calc3, stores))

test_func(...) will return a dataframe and you pass that into parallelize_dataframe.
But this function is expecting a callable.

You want something like this:

test = parallelize_dataframe(nearest_calc3, test_func)

As you want to always pass stores into test_func in addition to nearest_calc3, you could use partial to do so:

test_func_with_stores = functools.partial(test_func, stores)

test_func_with_stores is then a callable that takes a single parameter.
Unfortunately partial fills the parameters from left to right, so you would have to change test_func so that stores is the first parameter.


问:
"--watch is not supported without git/hg" with cygwin jest and git
I would really appreciate help with this.

I have cygwin installed and set up to use the PATH from windows. This has been working great for a ton of node development, but I've recently run into an issue where when I run

```<code>yarn jest --watch
</code>```

I get the following error:

```<code>--watch is not supported without git/hg, please use --watchAll
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

I have installed git and node in windows.

I have found a workaround of using the Command Prompt for running the tests, but would really like to be in one environment.

答:
npm run test -- watchAll

Please use  watchAll to serve it in a continue way. It will track your changes and re-run the test automatically.

Body:
I would really appreciate help with this.

I have cygwin installed and set up to use the PATH from windows. This has been working great for a ton of node development, but I've recently run into an issue where when I run

yarn jest --watch

I get the following error:

--watch is not supported without git/hg, please use --watchAll
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I have installed git and node in windows.

I have found a workaround of using the Command Prompt for running the tests, but would really like to be in one environment.