问:
Combining two form values in a loop using jquery
Hi guys I got a tricky question for me.

I have this form in which i want them to combine into one array when i looped all the form fields that is located in a table header.

This is the loop i used to get all the data of the fields

```<code>$('#filterTable').find("table select, table input").each(function(key, value) {
                var name = $(this).attr('name');
                var input = {};

                if (this.value !== ''){
                     if (name === 'filter_select') {
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.filterSelect = $(this).val();
                     } else if (name === 'froms'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.from = $(this).val();
                     } else if (name === 'to'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.to = $(this).val();
                     }

                     if(layerId == "" && input)
                        layerId = input.layer_id;
                     filterForm.push(input);

                     previous_col = $(this).data('col');
                }

            });
</code>```

This code provide me the following output

```<code>0:
col: 2
layer_id: 139
from: "100"

1:
col: 2
layer_id: 139
to: "500"
</code>```

what i want to accomplish is to combine them since they have the same col or they are located in the same table header so the output will look like this

```<code>0:
col: 2
layer_id: 139
from: "100"
to: "500"
</code>```

any idea how can I solve this one? been stuck here for such a long time. Thanks

答:
You have 2 inputs, so

```<code>$('#filterTable').find("table select, table input").each(function...
</code>```

runs twice, once for each input field, pushing input into filterForm twice. You need to push once.

Create one function, that fills input object, then push it when you are done.

Something like this:

```<code>input.col = $('#input1').data('col');
input.layer_id = $('#input1').data('layer');
input.to = $('#input1').val();
input.from = $('#input2').val();

filterForm.push(input);
</code>```

Body:
Hi guys I got a tricky question for me.

I have this form in which i want them to combine into one array when i looped all the form fields that is located in a table header.

This is the loop i used to get all the data of the fields

$('#filterTable').find("table select, table input").each(function(key, value) {
                var name = $(this).attr('name');
                var input = {};

                if (this.value !== ''){
                     if (name === 'filter_select') {
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.filterSelect = $(this).val();
                     } else if (name === 'froms'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.from = $(this).val();
                     } else if (name === 'to'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.to = $(this).val();
                     }

                     if(layerId == "" && input)
                        layerId = input.layer_id;
                     filterForm.push(input);

                     previous_col = $(this).data('col');
                }

            });

This code provide me the following output

0:
col: 2
layer_id: 139
from: "100"

1:
col: 2
layer_id: 139
to: "500"

what i want to accomplish is to combine them since they have the same col or they are located in the same table header so the output will look like this

0:
col: 2
layer_id: 139
from: "100"
to: "500"

any idea how can I solve this one? been stuck here for such a long time. Thanks

Body:
You have 2 inputs, so

$('#filterTable').find("table select, table input").each(function...

runs twice, once for each input field, pushing input into filterForm twice. You need to push once.

Create one function, that fills input object, then push it when you are done.

Something like this:

input.col = $('#input1').data('col');
input.layer_id = $('#input1').data('layer');
input.to = $('#input1').val();
input.from = $('#input2').val();

filterForm.push(input);


来源: stackexchange

问:
TextJoin: How to remove duplicate values?
I have the following table of data:

In C2, I then input the following formula =TEXTJOIN(", ",TRUE,IF($B$2:$B$7=$B2,$A$2:$A$7,"")) which returns the following:

However, I want the formula to ignore any duplicates and just return 1, 30

I've had a peruse, and looked a similarly asked questions on here, but i am unable to get anything to work

EDIT

I have partially resolved this with the following code:

=TEXTJOIN(", ",TRUE,IF($B$2:$B$13=$B2,IF(MATCH($A$2:$A$13,$A$2:$A$13,0)=ROW($A$2:$A$13)-ROW($A$2)+1,$A$2:$A$13,""),""))

However, if the ID code changes and an income code, previously populated under a different ID, appears it will just return blank:

Many thanks

答:
Applies to O365 with the UNIQUE function

try:

```<code>=TEXTJOIN(",",TRUE,UNIQUE(IF($B$2:$B$7=$B2,IF($A$2:$A$7="","",$A$2:$A$7),"")))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Applies to O365 with the UNIQUE function

try:

=TEXTJOIN(",",TRUE,UNIQUE(IF($B$2:$B$7=$B2,IF($A$2:$A$7="","",$A$2:$A$7),"")))


问:
Create a nested dictionary from pd dataframe Python
I have the following data frame like (in reality with hundreds of rows)

```<code>    Location Date       Court    Winner
0   Paris    10/2/2018  Outdoor  Flavio
1   Paris    10/2/2018  Indoor   Luca
2   Paris    10/2/2018  Indoor   Giovanni
3   Paris    10/2/2018  Indoor   Luca
</code>```

What I want to do is to get a nested dictionary that look like that:

```<code>{ 'Flavio' : { 'Outdoor' : 1 , 'Indoor' : 0 } , 'Luca' : {'Outdoor' : 0 , 'Indoor' : 2} }
</code>```

and so on. So in other words I want to determine the number of times winners won in the Outdoor and in the Indoor court.

Thank you in advance!

答:
You can do it with a pivot_table and to_dict:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Location':['France','France','France','France'],
                   'Court':['Outdoor','Indoor','Indoor','Indoor'],
                   'Winner':['Flavio','Luca','Giovanni','Luca']})
df = pd.pivot_table(df,values='Location',columns='Winner',index='Court',aggfunc='count',fill_value=0)
a = df.to_dict()
print(a)
</code>```

Output:

```<code>{'Flavio': {'Indoor': 0, 'Outdoor': 1}, 'Giovanni': {'Indoor': 1, 'Outdoor': 0}, 'Luca': {'Indoor': 2, 'Outdoor': 0}}
</code>```

Body:
I have the following data frame like (in reality with hundreds of rows)

    Location Date       Court    Winner
0   Paris    10/2/2018  Outdoor  Flavio
1   Paris    10/2/2018  Indoor   Luca
2   Paris    10/2/2018  Indoor   Giovanni
3   Paris    10/2/2018  Indoor   Luca

What I want to do is to get a nested dictionary that look like that:

{ 'Flavio' : { 'Outdoor' : 1 , 'Indoor' : 0 } , 'Luca' : {'Outdoor' : 0 , 'Indoor' : 2} }

and so on. So in other words I want to determine the number of times winners won in the Outdoor and in the Indoor court.

Thank you in advance!

Body:
You can do it with a pivot_table and to_dict:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Location':['France','France','France','France'],
                   'Court':['Outdoor','Indoor','Indoor','Indoor'],
                   'Winner':['Flavio','Luca','Giovanni','Luca']})
df = pd.pivot_table(df,values='Location',columns='Winner',index='Court',aggfunc='count',fill_value=0)
a = df.to_dict()
print(a)

Output:

{'Flavio': {'Indoor': 0, 'Outdoor': 1}, 'Giovanni': {'Indoor': 1, 'Outdoor': 0}, 'Luca': {'Indoor': 2, 'Outdoor': 0}}


问:
Java sort string both alphabetically and keep ASCII order
The list is: Arrays.asList("Za", "ab", "AB", "Sa", "1ab", "Ab", "!Ab");

If I use stream().sorted() then the order is: !Ab 1ab AB Ab Za ab --> Za should not be in front of ab.

If I use sorted(String.CASE_INSENSITIVE_ORDER) then the order is !Ab 1ab ab AB Ab Za --> This time, AB is behind ab.

Is there any way to combine the two rules so we have list sorted alphabetically and uppercase is greater than lower case?

Added Example: 1AB - A0B - AbD - aBD - abd1 - ZAB
Sorted alphabetically (Z is  never in front of a) and Number >  Uppercase > Lowercase (AbD > aBD)

答:
You can use the following code to achieve this in Java7

```<code> List<String> list = Arrays.asList("Za", "ab", "AB", "Sa", "1ab", "Ab", "!Ab");

  Comparator<String> comparator = new Comparator<String>() {

  @Override
  public int compare(String o1, String o2) {
      int compare = o1.toLowerCase().compareTo(o2.toLowerCase());
            if(compare==0)
                compare = o1.compareTo(o2);
            return compare;
      }

  };

 Collections.sort(list,comparator);
 System.out.println(list);
</code>```

In Java8 use this code

```<code>List<String> list = Arrays.asList("Za", "ab", "AB", "Sa", "1ab", "Ab", "!Ab");

Stream<String> stream = list.stream()
                             .sorted(String.CASE_INSENSITIVE_ORDER
                                  .thenComparing(Comparator.naturalOrder()));

stream.forEach(s -> System.out.print(s + " "));
</code>```

Body:
You can use the following code to achieve this in Java7

 List<String> list = Arrays.asList("Za", "ab", "AB", "Sa", "1ab", "Ab", "!Ab");

  Comparator<String> comparator = new Comparator<String>() {

  @Override
  public int compare(String o1, String o2) {
      int compare = o1.toLowerCase().compareTo(o2.toLowerCase());
            if(compare==0)
                compare = o1.compareTo(o2);
            return compare;
      }

  };

 Collections.sort(list,comparator);
 System.out.println(list);

In Java8 use this code

List<String> list = Arrays.asList("Za", "ab", "AB", "Sa", "1ab", "Ab", "!Ab");

Stream<String> stream = list.stream()
                             .sorted(String.CASE_INSENSITIVE_ORDER
                                  .thenComparing(Comparator.naturalOrder()));

stream.forEach(s -> System.out.print(s + " "));


问:
How to get Double from String based on locale?
I'm looking for a short and elegance solution, such as some method.

If it's possible to use method like this:

public Double getDoubleFromString(String string); (inside this method it's needed to get current locale because of different GroupingSeparator and DecimalSeparator in different locales)

答:
I found a solution that helped me in my case:

```<code>public double getDoubleFromString(String string) {
   NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
   Number number;
   double d;
   try {
      number = format.parse(string);
      d = number.doubleValue();
   } catch (Exception e) {
      e.printStackTrace();
      d = Double.NaN;
   }
   return d;
}
</code>```

This is what I meant and looked for. Maybe someone will come in handy.

Body:
I found a solution that helped me in my case:

public double getDoubleFromString(String string) {
   NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
   Number number;
   double d;
   try {
      number = format.parse(string);
      d = number.doubleValue();
   } catch (Exception e) {
      e.printStackTrace();
      d = Double.NaN;
   }
   return d;
}

This is what I meant and looked for. Maybe someone will come in handy.


问:
Angular Resolver Service Not Working Properly

RoleList Component:::
import { Global } from "./../../../global/serverlinks";

import { Component, OnInit, ViewChild } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Router, ActivatedRoute, ParamMap } from "@angular/router";
import { RoleserviceService } from "src/app/Service/roleservice.service";
import {BsModalComponent} from "ng2-bs3-modal"

@Component({
  selector: "app-rolelist",
  templateUrl: "./rolelist.component.html",
  styleUrls: ["./rolelist.component.css"]
})
export class RolelistComponent implements OnInit {
  public data: any;
  public error: any;
  public name: string;
  constructor(
    public http: HttpClient,
    public router: Router,
    public route: ActivatedRoute,
    public service: RoleserviceService
  ) {}

  ngOnInit() {
     this.route.data.subscribe(
      result=>this.data=result.roleList
    );

  }
  showResult() {
    console.log(
      this.http.get<Observable<any>[]>(Global.BASE_HOST_ENDPOINT).subscribe(
        data => {
          (this.data = data), console.log(data);
        },
        error => {
          (this.error = error), console.log(error);
        }
      )
    );
  }

  EditRole(id) {
    let role;
    this.service.GetRole(id).subscribe(res => {
      (role = res),
        console.log("Role found:" + role),
        this.router.navigate([
          "editrole",
          id],{queryParams:{name:role.name},skipLocationChange:true}),
      err => console.log(err);
    });

  }
  DeleteRole(id,index){
    let role;
    this.service.GetRole(id).subscribe(
      result=>{
        this.service.DeleteRole(id).subscribe(
          result=>{
            console.log(result)
            this.data.remove(index)
          },
          err=>console.log(err)
        )
      }
    )
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Resolver Service::
import { RoleserviceService } from './roleservice.service';
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Role } from '../Model/role';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Global } from '../global/serverlinks';
@Injectable()

export class RoleListResolverService implements Resolve<Role[]>{
    constructor(public service:RoleserviceService,public http:HttpClient){}

  resolve(route: ActivatedRouteSnapshot,state:RouterStateSnapshot):Observable<Role[]>{
      return this.http.get<Role[]>(Global.BASE_HOST_ENDPOINT)
  }
}</code>```

            {{role.name}}

            This is {{role.name}} role.

                    <button class="btn-primary" routerLink="/editrole/{{role.id}}"
                        (click)="EditRole(role.id)">Edit</button>

                    <button class="btn-danger" (click)="DeleteRole(role.id,1)">Delete</button>

Users

{{user.name}}

No Members Yet

                <button class="btn btn-outline-dark">Manage Users In{{role.name}} role</button>

```

I used resolver service to list the list of roles and corresponding users . The list doesn't completely fill at the beginning but as soon as I press any button it loads up. what is the issue?..
The picture seen below has the Manager Role Shown but that if only after I clicked a button. Before that the Outline box was shown but not name of the role.

enter image description here

答:
Please try this

```<code><div class="card">
<div class="card-header">Users</div>
<div class="card-body list-group pl-3">
    <div *ngIf="role.users.length>0;else elseBlock">
        <div *ngFor="let user of role.users">
            <div class="font-weight-bold">{{user.name}}</div>
        </div>
    </div>
</div>
<ng-template #elseBlock>
    <div class="font-weight-bold">No Members Yet</div>
</ng-template>
<a>
    <button class="btn btn-outline-dark">Manage Users In{{role.name}} role</button>
</a>
</code>```

Body:
RoleList Component:::
import { Global } from "./../../../global/serverlinks";

import { Component, OnInit, ViewChild } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Router, ActivatedRoute, ParamMap } from "@angular/router";
import { RoleserviceService } from "src/app/Service/roleservice.service";
import {BsModalComponent} from "ng2-bs3-modal"

@Component({
  selector: "app-rolelist",
  templateUrl: "./rolelist.component.html",
  styleUrls: ["./rolelist.component.css"]
})
export class RolelistComponent implements OnInit {
  public data: any;
  public error: any;
  public name: string;
  constructor(
    public http: HttpClient,
    public router: Router,
    public route: ActivatedRoute,
    public service: RoleserviceService
  ) {}

  ngOnInit() {
     this.route.data.subscribe(
      result=>this.data=result.roleList
    );

  }
  showResult() {
    console.log(
      this.http.get<Observable<any>[]>(Global.BASE_HOST_ENDPOINT).subscribe(
        data => {
          (this.data = data), console.log(data);
        },
        error => {
          (this.error = error), console.log(error);
        }
      )
    );
  }

  EditRole(id) {
    let role;
    this.service.GetRole(id).subscribe(res => {
      (role = res),
        console.log("Role found:" + role),
        this.router.navigate([
          "editrole",
          id],{queryParams:{name:role.name},skipLocationChange:true}),
      err => console.log(err);
    });

  }
  DeleteRole(id,index){
    let role;
    this.service.GetRole(id).subscribe(
      result=>{
        this.service.DeleteRole(id).subscribe(
          result=>{
            console.log(result)
            this.data.remove(index)
          },
          err=>console.log(err)
        )
      }
    )
  }

}

Resolver Service::
import { RoleserviceService } from './roleservice.service';
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Role } from '../Model/role';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Global } from '../global/serverlinks';
@Injectable()

export class RoleListResolverService implements Resolve<Role[]>{
    constructor(public service:RoleserviceService,public http:HttpClient){}

  resolve(route: ActivatedRouteSnapshot,state:RouterStateSnapshot):Observable<Role[]>{
      return this.http.get<Role[]>(Global.BASE_HOST_ENDPOINT)
  }
}

            {{role.name}}

            This is {{role.name}} role.

                    <button class="btn-primary" routerLink="/editrole/{{role.id}}"
                        (click)="EditRole(role.id)">Edit</button>

                    <button class="btn-danger" (click)="DeleteRole(role.id,1)">Delete</button>

Users

{{user.name}}

No Members Yet

                <button class="btn btn-outline-dark">Manage Users In{{role.name}} role</button>

I used resolver service to list the list of roles and corresponding users . The list doesn't completely fill at the beginning but as soon as I press any button it loads up. what is the issue?..
The picture seen below has the Manager Role Shown but that if only after I clicked a button. Before that the Outline box was shown but not name of the role.

enter image description here

Body:
Please try this

<div class="card">
<div class="card-header">Users</div>
<div class="card-body list-group pl-3">
    <div *ngIf="role.users.length>0;else elseBlock">
        <div *ngFor="let user of role.users">
            <div class="font-weight-bold">{{user.name}}</div>
        </div>
    </div>
</div>
<ng-template #elseBlock>
    <div class="font-weight-bold">No Members Yet</div>
</ng-template>
<a>
    <button class="btn btn-outline-dark">Manage Users In{{role.name}} role</button>
</a>


答:
Just a modification to your code to achieve what you want:

```<code>$('#filterTable').find("table select, table input").each(function(key, value) {
                var name = $(this).attr('name');
                var input = {};

                if (this.value !== ''){
                     if (name === 'filter_select') {
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.filterSelect = $(this).val();
                     } else if (name === 'froms'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.from = $(this).val();
                     } else if (name === 'to'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.to = $(this).val();
                     }

                     if(layerId == "" && input)
                        layerId = input.layer_id;
                     if (name === 'to')
                     {
                       var exist = filterForm.map(f => f.col).indexOf(input.col);
                       if(exist == -1)
                       {
                         filterForm.push(input);
                       }
                       else
                       {
                         filterForm[exist].to = $(this).val();
                       }

                    }
                    else
                    {
                       filterForm.push(input);
                    }

                     previous_col = $(this).data('col');
                }

            });
</code>```

Explanation:

Before pushing new object to array, we are checking if there is any object with same col property in array? If no, then we push it, otherwise we set to property for found object in array.

Title: Combining two form values in a loop using jquery

Body:
Just a modification to your code to achieve what you want:

$('#filterTable').find("table select, table input").each(function(key, value) {
                var name = $(this).attr('name');
                var input = {};

                if (this.value !== ''){
                     if (name === 'filter_select') {
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.filterSelect = $(this).val();
                     } else if (name === 'froms'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.from = $(this).val();
                     } else if (name === 'to'){
                         input.col = $(this).data('col');
                         input.layer_id = $(this).data('layer');
                         input.to = $(this).val();
                     }

                     if(layerId == "" && input)
                        layerId = input.layer_id;
                     if (name === 'to')
                     {
                       var exist = filterForm.map(f => f.col).indexOf(input.col);
                       if(exist == -1)
                       {
                         filterForm.push(input);
                       }
                       else
                       {
                         filterForm[exist].to = $(this).val();
                       }

                    }
                    else
                    {
                       filterForm.push(input);
                    }

                     previous_col = $(this).data('col');
                }

            });

Explanation:

Before pushing new object to array, we are checking if there is any object with same col property in array? If no, then we push it, otherwise we set to property for found object in array.


问:
How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

For Example in the below code plus button works and able to update
the text but the minus button does not.

But if we press FloatingActionButton then the State is refreshed .

The minus button is changing the value of the variable but not
updating the state of parent widget .

here is code .....

```<code>import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

int number;

EdgeInsets globalMargin = const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0);
TextStyle textStyle = const TextStyle(
  fontSize: 100.0,
  color: Colors.black,
);

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    number = number ?? 0;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Column(
        children: <Widget>[
          new Text(
            number.toString(),
            style: textStyle,
          ),
          new GridView.count(
            crossAxisCount: 2,
            shrinkWrap: true,
            scrollDirection: Axis.vertical,
            children: <Widget>[
              new InkResponse(
                child: new Container(
                    margin: globalMargin,
                    color: Colors.green,
                    child: new Center(
                      child: new Text(
                        "+",
                        style: textStyle,
                      ),
                    )),
                onTap: () {
                  setState(() {
                    number = number + 1;
                  });
                },
              ),
              new Sub(),
            ],
          ),
        ],
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {
          setState(() {});
        },
        child: new Icon(Icons.update),
      ),
    );
  }
}

class Sub extends StatefulWidget {
  @override
  _SubState createState() => new _SubState();
}

class _SubState extends State<Sub> {
  @override
  Widget build(BuildContext context) {
    return new InkResponse(
      child: new Container(
          margin: globalMargin,
          color: Colors.red,
          child: new Center(
            child: new Text(
              "-",
              style: textStyle,
            ),
          )),
      onTap: () {
        setState(() {
          number = number - 1;
        });
      },
    );
  }
}
</code>```

答:
Although most of these previous answers will work, I suggest you explore the provider or BloC architectures, both of which have been recommended by Google.

In short, the latter will create a stream that reports to widgets in the widget tree whenever a change in the state happens and it updates all relevant views regardless of where it is updated from.

Here is a good overview you can read to learn more about the subject: https://bloclibrary.dev/#/

Body:
For Example in the below code plus button works and able to update
the text but the minus button does not.

But if we press FloatingActionButton then the State is refreshed .

The minus button is changing the value of the variable but not
updating the state of parent widget .

here is code .....

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

int number;

EdgeInsets globalMargin = const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0);
TextStyle textStyle = const TextStyle(
  fontSize: 100.0,
  color: Colors.black,
);

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    number = number ?? 0;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Column(
        children: <Widget>[
          new Text(
            number.toString(),
            style: textStyle,
          ),
          new GridView.count(
            crossAxisCount: 2,
            shrinkWrap: true,
            scrollDirection: Axis.vertical,
            children: <Widget>[
              new InkResponse(
                child: new Container(
                    margin: globalMargin,
                    color: Colors.green,
                    child: new Center(
                      child: new Text(
                        "+",
                        style: textStyle,
                      ),
                    )),
                onTap: () {
                  setState(() {
                    number = number + 1;
                  });
                },
              ),
              new Sub(),
            ],
          ),
        ],
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {
          setState(() {});
        },
        child: new Icon(Icons.update),
      ),
    );
  }
}

class Sub extends StatefulWidget {
  @override
  _SubState createState() => new _SubState();
}

class _SubState extends State {
  @override
  Widget build(BuildContext context) {
    return new InkResponse(
      child: new Container(
          margin: globalMargin,
          color: Colors.red,
          child: new Center(
            child: new Text(
              "-",
              style: textStyle,
            ),
          )),
      onTap: () {
        setState(() {
          number = number - 1;
        });
      },
    );
  }
}


问:
Excel-DNA: Unregister methods in a running instance of Excel
Is it possible to unregister methods that I previously registered via ExcelIntegration.RegisterMethods without restarting Excel?

Basically, I'm looking for the opposite of ExcelIntegration.RegisterMethods.

答:
Excel-DNA does not currently let you unregister methods in a loaded add-in. This is just a limitation of the implementation, and how exported functions are hooked up to the native exports of the .xll. You an however unload an entire Excel-DNA add-in, (from another add-in) as long as it only exports UDFs and not ribbons, an RTD server or other COM features.

Another workaround is to re-register the function as "hidden". The new registration will take up another slot in the (fixed-size) .xll export table, but will at least not appear in the worksheet function completion list anymore.


问:
Show image on SCNPlane in Scene kit & AR kit in swift iOS
I followed this raywenderlich tutorial to detect image using AR and Scene Kit. In this example they showed displaying video on top of detected image.

https://www.raywenderlich.com/6957-building-a-museum-app-with-arkit-2

I want to display image on top of detected image. Please help me how can I add childNode to SCNNode so that I can display image on top of it.

Here is the code which I tried it's not working  showing a blank white screen.

```<code>                            DispatchQueue.main.async {

                        let size = imageAnchor.referenceImage.physicalSize

                        let imageView = UIImageView(image: UIImage(named: "BG.png")!)

                        let imgMaterial = SCNMaterial()
                        imgMaterial.diffuse.contents = imageView

                        let imgPlane = SCNPlane(width: size.width, height: size.height)
                        imgPlane.materials = [imgMaterial]

                        let imgNode = SCNNode(geometry: imgPlane)
                        imgNode.eulerAngles.x = -.pi / 2

                        node.addChildNode(imgNode)
                         node.opacity = 1

                        }
</code>```

Please help to show image on top of detected image. Thanks in advance.

I'm able to show image on top of detected image but it takes lot of memory what is wrong in that code.

And same as image view I'm displaying gif play on top of detected image with the below code.

```<code>                                let size = imageAnchor.referenceImage.physicalSize

                            let imgNameFromDoc = person["actionToTake"] as! String

                            let documentsPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first

                            let imgpath = documentsPathURL?.appendingPathComponent("/Packages/\(self.selectedDatasetName)/3DScenes/\(imgNameFromDoc)")

                            let imageData = try! Data(contentsOf: URL(fileURLWithPath: imgpath!.path))

                            let imageURL = UIImage.gifImageWithData(imageData)

                            self.gifImgView = UIImageView(image: imageURL)

                            let imgMaterial = SCNMaterial()
                            imgMaterial.diffuse.contents = self.gifImgView

                            let imgPlane = SCNPlane(width: CGFloat(scaleActionSize(wid: Float(size.width), hei:Float(size.height))[0]), height: CGFloat(scaleActionSize(wid: Float(size.width), hei:Float(size.height))[1]))

                            imgPlane.materials = [imgMaterial]

                            let imgNode = SCNNode(geometry: imgPlane)
                            imgNode.eulerAngles.x = -.pi / 2

                            node.addChildNode(imgNode)
                            node.opacity = 1
</code>```

With the help of image extension I'm showing GIF on image view on top of detected image.
https://github.com/kiritmodi2702/GIF-Swift/blob/master/GIF-Swift/iOSDevCenters%2BGIF.swift

How to load GIF image in Swift?

I dragged iOSDevCenters+GIF.swift class inside app and displayed gif.

When I use this gif image viewto display gif and image view to display image it takes more than 800 MB memory in Xcode running with iPad.

can somebody help me to find any memory leaks(tried with instruments not able to fix) or anything wrong in this code.

答:
Displaying UIKit views as material property contents is not supported.
Instead of a UIImageView you should directly use the UIImage or even better just a String or URL that points to the image on disk. This way the image won't be loaded twice in memory (in SceneKit and UIKit).

Body:
I followed this raywenderlich tutorial to detect image using AR and Scene Kit. In this example they showed displaying video on top of detected image.

https://www.raywenderlich.com/6957-building-a-museum-app-with-arkit-2

I want to display image on top of detected image. Please help me how can I add childNode to SCNNode so that I can display image on top of it.

Here is the code which I tried it's not working  showing a blank white screen.

                            DispatchQueue.main.async {

                        let size = imageAnchor.referenceImage.physicalSize

                        let imageView = UIImageView(image: UIImage(named: "BG.png")!)

                        let imgMaterial = SCNMaterial()
                        imgMaterial.diffuse.contents = imageView

                        let imgPlane = SCNPlane(width: size.width, height: size.height)
                        imgPlane.materials = [imgMaterial]

                        let imgNode = SCNNode(geometry: imgPlane)
                        imgNode.eulerAngles.x = -.pi / 2

                        node.addChildNode(imgNode)
                         node.opacity = 1

                        }

Please help to show image on top of detected image. Thanks in advance.

I'm able to show image on top of detected image but it takes lot of memory what is wrong in that code.

And same as image view I'm displaying gif play on top of detected image with the below code.

                                let size = imageAnchor.referenceImage.physicalSize

                            let imgNameFromDoc = person["actionToTake"] as! String

                            let documentsPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first

                            let imgpath = documentsPathURL?.appendingPathComponent("/Packages/\(self.selectedDatasetName)/3DScenes/\(imgNameFromDoc)")

                            let imageData = try! Data(contentsOf: URL(fileURLWithPath: imgpath!.path))

                            let imageURL = UIImage.gifImageWithData(imageData)

                            self.gifImgView = UIImageView(image: imageURL)

                            let imgMaterial = SCNMaterial()
                            imgMaterial.diffuse.contents = self.gifImgView

                            let imgPlane = SCNPlane(width: CGFloat(scaleActionSize(wid: Float(size.width), hei:Float(size.height))[0]), height: CGFloat(scaleActionSize(wid: Float(size.width), hei:Float(size.height))[1]))

                            imgPlane.materials = [imgMaterial]

                            let imgNode = SCNNode(geometry: imgPlane)
                            imgNode.eulerAngles.x = -.pi / 2

                            node.addChildNode(imgNode)
                            node.opacity = 1

With the help of image extension I'm showing GIF on image view on top of detected image.
https://github.com/kiritmodi2702/GIF-Swift/blob/master/GIF-Swift/iOSDevCenters%2BGIF.swift

How to load GIF image in Swift?

I dragged iOSDevCenters+GIF.swift class inside app and displayed gif.

When I use this gif image viewto display gif and image view to display image it takes more than 800 MB memory in Xcode running with iPad.

can somebody help me to find any memory leaks(tried with instruments not able to fix) or anything wrong in this code.


问:
How to handle Imbalanced Datatset and outliers in python?
I have 2 doubts :

If we have a classification problem with a dataframe that  has large no of features (columns > 100) and if say 20/30 of them are highly correlated  and the target columns (y)  is very skewed towards one class ;
should we first remove the imbalance using Imblearn or should we drop the highly correlated columns ?

In a classification problem should we first standardise the data or handle the outliers ?

答:
There is no "true" answer to your questions - the approach to take highly depends on your setting, the models you apply and the goals at hand.

The topic of class imbalance has been discussed elsewhere (for example here and here).

A valid reason for oversampling/undersampling your positive or negative class training examples could be the knowledge that the true incidence of positive instances is higher (lower) than your training data suggests. Then you might want to apply sampling techniques to achieve a positive/negative class balance that matches that prior knowledge.

While not really dealing with imbalance in your label distribution, your specific setting may warrant assigning different costs to false positives and false negatives (e.g. the cost of misclassifying a cancer patient as healthy may be higher than vice versa). This you can deal with by e.g. adapting your cost function (e.g. a false negative incurring higher cost than a false negative) or by performing some kind of threshold optimization after training (to e.g. reach a certain precision/recall in cross-validation).

The problem of highly correlated features occurs with models that assume that there is no correlation between features. For example, if you have an issue with multicollinearity in your feature space, parameter estimates in logistic regressions may be off. Whether or not there is multicollinearity you can for example check using the variance inflation factor (VIF). However, not all models carry such an assumption, so you might be save disregarding the issue depending on your setting.

Same goes for standardisation: This may not be necessary (e.g. tree classifiers), but other method may require it (e.g. PCA).

Whether or not to handle outliers is a difficult question. First you would have to define what an outlier is - are they e.g. a result of human error? Do you expect seeing similar instances out in the wild? If you can establish that your model performs better if you train it with outliers removed (on a holdout validation or test set), then: sure, go for it. But keep potential outliers in for validation if you plan to apply your model on streams of data which may produce similar outliers.


答:
Assuming the values are only 'Yes' and 'No':

```<code>select name
from t
group by name
having min(paid) = max(paid) and min(paid) = 'No';
</code>```

Title: Postgresql - How to get record from the same table that doesn't occur specific data

Body:
In PostgreSQL, if i have this kind of record :

|---------------------|------------------|
|      Name           |     Paid         |
|---------------------|------------------|
|        Teddy        |        No        |
|---------------------|------------------|
|        Andy         |        No        |
|---------------------|------------------|
|        Andy         |        Yes       |
|---------------------|------------------|
|        Sarah        |        Yes       |
|---------------------|------------------|
|        Michael      |        No        |
|---------------------|------------------|
|        Michael      |        Yes       |
|---------------------|------------------|

How do i get Names that don't have 'Yes' occurence in the table?

In this example the result should be : Teddy.

Thanks !

Body:
Assuming the values are only 'Yes' and 'No':

select name
from t
group by name
having min(paid) = max(paid) and min(paid) = 'No';


问:
Same-origin policy blocking API request on remote
The "on remote" section is why I am confused on this. I am trying to do a POST request to https://api.smarkets.com/v3/sessions. The route is to create a session token for subsequent requests to the API.

If I do this request on my local machine, it works fine. I get a 2xx response. However, if I try on a remote machine (DO box I spun up last night), I get a '503 Service Temporarily Unavailable' response.

I attempted to login via the browser & I got the same response. I raised this question to Smarkets & they eluded to the fact it might be due to the same-origin policy imposed by Smarkets.

After some time, I managed to login via Chrome by disabling the same-origin policy. The API request still failed.

From my limited knowledge of the same-origin policy (please correct me if I'm wrong), it specifies what resources are allowed to be returned from certain origins. Similar to CORS issues. Why would I have to explicitly disable web security on a remote browser to get it to login to smarkets.com but my browser on my local machine can login just fine without being modified?

The question I highlighted above shows what methods I have tried to get this to work. No matter what request headers I attempt to set, the response headers are always the same with X-Frame-Options response header always set to SAMEORIGIN which, again from what I understand, only allows resources to be sent to the same origin of the sender. I.e. resources sent from smarkets.com can only be accessed by requests from smarkets.com.

My current request attempt is (with httpie):

```<code>http POST https://api.smarkets.com/v3/sessions/ 'Access-Control-Request-Headers: Content-Type, Accept, Host, Origin' 'Access-Control-Request-Methods: POST, OPTIONS' 'Origin: https://smarkets.com' username=<username> password=<password> --print=Hh
</code>```

The request & response headers are:

I'm really looking for;

Clarity on what the same-origin policy is imposing

Why does this request succeed on my local machine but not a remote DO box

How can I get this request to succeed?

The user at Smarkets seems like this is a same-origin issue but it might not be.

EDIT:

It's not a firewall issue as I disabled Ubuntu's built-in firewall. I am doing other requests over http(s) from the same origin so I can't figure out what is different about this one

EDIT 2:

Below is an example of successful request/response headers:

I'm able to make other API calls from the same box to different origins, including:

https://api.betdaq.com

https://api.betfair.com

https://api.matchbook.com

I have added no configurations specifically around any origins on the box so am really unsure as to what this issue is. I have added all the possible CORS request headers that I can think of & still no luck.

EDIT 3:

Annoyingly, this has been fixed now as the vendors API blacklists DigitalOcean IPs by default...

答: Cors is more or less always a server side thing. If the vendor is exposing some api to hit then they should make sure that cors is disabled. Other than talking to them about it, you really can do nothing else from your side. Having to disable cors from chrome is a bad idea.</p>

Body:
The "on remote" section is why I am confused on this. I am trying to do a POST request to https://api.smarkets.com/v3/sessions. The route is to create a session token for subsequent requests to the API.

If I do this request on my local machine, it works fine. I get a 2xx response. However, if I try on a remote machine (DO box I spun up last night), I get a '503 Service Temporarily Unavailable' response.

I attempted to login via the browser & I got the same response. I raised this question to Smarkets & they eluded to the fact it might be due to the same-origin policy imposed by Smarkets.

After some time, I managed to login via Chrome by disabling the same-origin policy. The API request still failed.

From my limited knowledge of the same-origin policy (please correct me if I'm wrong), it specifies what resources are allowed to be returned from certain origins. Similar to CORS issues. Why would I have to explicitly disable web security on a remote browser to get it to login to smarkets.com but my browser on my local machine can login just fine without being modified?

The question I highlighted above shows what methods I have tried to get this to work. No matter what request headers I attempt to set, the response headers are always the same with X-Frame-Options response header always set to SAMEORIGIN which, again from what I understand, only allows resources to be sent to the same origin of the sender. I.e. resources sent from smarkets.com can only be accessed by requests from smarkets.com.

My current request attempt is (with httpie):

http POST https://api.smarkets.com/v3/sessions/ 'Access-Control-Request-Headers: Content-Type, Accept, Host, Origin' 'Access-Control-Request-Methods: POST, OPTIONS' 'Origin: https://smarkets.com' username=<username> password=<password> --print=Hh

The request & response headers are:

I'm really looking for;

Clarity on what the same-origin policy is imposing

Why does this request succeed on my local machine but not a remote DO box

How can I get this request to succeed?

The user at Smarkets seems like this is a same-origin issue but it might not be.

EDIT:

It's not a firewall issue as I disabled Ubuntu's built-in firewall. I am doing other requests over http(s) from the same origin so I can't figure out what is different about this one

EDIT 2:

Below is an example of successful request/response headers:

I'm able to make other API calls from the same box to different origins, including:

https://api.betdaq.com

https://api.betfair.com

https://api.matchbook.com

I have added no configurations specifically around any origins on the box so am really unsure as to what this issue is. I have added all the possible CORS request headers that I can think of & still no luck.

EDIT 3:

Annoyingly, this has been fixed now as the vendors API blacklists DigitalOcean IPs by default...


答:
You can use $.extend to combine multiple objects with arbitrary properties.

Example code (without html inputs, which you can fit in inside the 'iteration' part)

var filterForm = [];

// previous iterations of the input loop popuplate filterForm array
filterForm.push({
  col: 2,
  layer_id: 139,
  from: "100"
});

// this iteration gets data from inputs (hardcoded here for simplicity/demo)
var input = {
  col: 2,
  layer_id: 139,
  to: "500"
};

// find if it's already in the array
var existing = filterForm.find(function(e) {
    return e.col == input.col && e.layer_id == input.layer_id;
});
// update existing item or add as a new item
if (existing != null)
    $.extend(existing, input);
else
    filterForm.push(input);

console.log(filterForm);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
You can use $.extend to combine multiple objects with arbitrary properties.

Example code (without html inputs, which you can fit in inside the 'iteration' part)

var filterForm = [];

// previous iterations of the input loop popuplate filterForm array
filterForm.push({
  col: 2,
  layer_id: 139,
  from: "100"
});

// this iteration gets data from inputs (hardcoded here for simplicity/demo)
var input = {
  col: 2,
  layer_id: 139,
  to: "500"
};

// find if it's already in the array
var existing = filterForm.find(function(e) {
    return e.col == input.col && e.layer_id == input.layer_id;
});
// update existing item or add as a new item
if (existing != null)
    $.extend(existing, input);
else
    filterForm.push(input);

console.log(filterForm);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Webhook call failed
I have created new agent and enables the fulfillment for Default Welcome Intent and also enabled the inline editor but when I invoked my welcome intent in simulator then it gives me default response instead of fulfillment response.

Am I doing something wrong?

this is my code

```<code>'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {

  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I'm sorry, can you try again?`);
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  agent.handleRequest(intentMap);

});
</code>```

答:
I have changed my code and now it's working

this is my new code

```<code>'use strict';
const functions = require('firebase-functions');
const {dialogflow} = require ('actions-on-google');
const {Suggestions} = require ('actions-on-google');
const WELCOME_INTENT = 'Default Welcome Intent';
const FALLBACK_INTENT = 'Default Fallback Intent';

const app = dialogflow();

app.intent(FALLBACK_INTENT, (conv) => {
    conv.ask("Sorry! Could you please repeat that?");
});

app.intent(WELCOME_INTENT, (conv) => {
    conv.ask("Hello!");
    conv.ask("What you would like to do?");
});

exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
</code>```

Title: Webhook call failed

Body:
I have created new agent and enables the fulfillment for Default Welcome Intent and also enabled the inline editor but when I invoked my welcome intent in simulator then it gives me default response instead of fulfillment response.

Am I doing something wrong?

this is my code

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {

  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I'm sorry, can you try again?`);
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  agent.handleRequest(intentMap);

});

Body:
I have changed my code and now it's working

this is my new code

'use strict';
const functions = require('firebase-functions');
const {dialogflow} = require ('actions-on-google');
const {Suggestions} = require ('actions-on-google');
const WELCOME_INTENT = 'Default Welcome Intent';
const FALLBACK_INTENT = 'Default Fallback Intent';

const app = dialogflow();

app.intent(FALLBACK_INTENT, (conv) => {
    conv.ask("Sorry! Could you please repeat that?");
});

app.intent(WELCOME_INTENT, (conv) => {
    conv.ask("Hello!");
    conv.ask("What you would like to do?");
});

exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);


问:
Do I use stacks or do I make isolated APIs and Frontends?
I have been making Web apps for a while now. Mostly frontends.

I have always wanted to make fully functioning websites, and therefore, my question.

The question might be dumb, so please bear with me...

I have realized that there are two ways I can develop web apps:

```<code>  1. I initialize/work with stacks (MERN, LAMP). Everything inside one folder. The
     backend throws the HTML code (as far as I understand).

                       -----or-----

  2. I make a Frontend service (localhost:3000 for React (for example)) and I create
     a RESTful API (with its own endpoint, say localhost/somethingBackend or
     something like localhost:8000).
</code>```

My question is:

Did I understand this right ? Is this how webdev works ?

And the more important one, WHEN TO USE WHAT ?
What is faster or better ?

Normally I'd google something like this, but there's either not much Information about this, or more probable, I'm searching the wrong thing.

Please help me clear my concepts.
Thank you for reading this long post :)

答:
Both are correct approaches.
But the first one is a more traditional approach towards web app but it comes with the difficulty of writing sensible, reusable code in it compared to writing random-looking nonsense which happens to work, along with performance and reliability issues.

Writing code with a RESTful approach is what I personally prefer. The majority of frameworks use this approach. Maintaining code between teams is easy.

Modern backends like nodejs can also throw HTML as a response(see templating engines) but as I said option 2 is always preferred.

Body:
I have been making Web apps for a while now. Mostly frontends.

I have always wanted to make fully functioning websites, and therefore, my question.

The question might be dumb, so please bear with me...

I have realized that there are two ways I can develop web apps:

  1. I initialize/work with stacks (MERN, LAMP). Everything inside one folder. The
     backend throws the HTML code (as far as I understand).

                       -----or-----

  2. I make a Frontend service (localhost:3000 for React (for example)) and I create
     a RESTful API (with its own endpoint, say localhost/somethingBackend or
     something like localhost:8000).

My question is:

Did I understand this right ? Is this how webdev works ?

And the more important one, WHEN TO USE WHAT ?
What is faster or better ?

Normally I'd google something like this, but there's either not much Information about this, or more probable, I'm searching the wrong thing.

Please help me clear my concepts.
Thank you for reading this long post :)


答:
Another alternative:

```<code>select name
from yourtable
group by name
having count (*) filter (where paid = 'Yes') = 0
</code>```

This will do at most a single scan of the table, which may be helpful if your table is large.

Body:
Another alternative:

select name
from yourtable
group by name
having count (*) filter (where paid = 'Yes') = 0

This will do at most a single scan of the table, which may be helpful if your table is large.


问:
How can I import from the standard library, when my project has a module with the same name? (How can I control where Python looks for modules?)
There is a module in my project folder called calendar. Elsewhere in the code, I would like to use the standard library Calendar class. But when I try to import this class, using from calendar import Calendar, this imports from my own module instead, causing errors later.

How can I avoid this? Do I have to rename the module?

答:
The only way to solve this problem is to hijack the internal import machinery yourself. This is not easy, and fraught with peril. You should avoid the grail shaped beacon at all costs because the peril is too perilous.

Rename your module instead.

If you want to learn how to hijack the internal import machinery, here is where you would go about finding out how to do this:

The Importing Modules section of the Python 2.7 documentation

The Importing Modules section of the Python 3.2 documentation

PEP 302 - New Import Hooks

There are sometimes good reasons to get into this peril. The reason you give is not among them. Rename your module.

If you take the perilous path, one problem you will encounter is that when you load a module it ends up with an 'official name' so that Python can avoid ever having to parse the contents of that module ever again. A mapping of the 'official name' of a module to the module object itself can be found in sys.modules.

This means that if you import calendar in one place, whatever module is imported will be thought of as the module with the official name calendar and all other attempts to import calendar anywhere else, including in other code that's part of the main Python library, will get that calendar.

It might be possible to design a customer importer using the imputil module in Python 2.x that caused modules loaded from certain paths to look up the modules they were importing in something other than sys.modules first or something like that. But that's an extremely hairy thing to be doing, and it won't work in Python 3.x anyway.

There is an extremely ugly and horrible thing you can do that does not involve hooking the import mechanism. This is something you should probably not do, but it will likely work. It turns your calendar module into a hybrid of the system calendar module and your calendar module. Thanks to Boaz Yaniv for the skeleton of the function I use. Put this at the beginning of your calendar.py file:

```<code>import sys

def copy_in_standard_module_symbols(name, local_module):
    import imp

    for i in range(0, 100):
        random_name = 'random_name_%d' % (i,)
        if random_name not in sys.modules:
            break
        else:
            random_name = None
    if random_name is None:
        raise RuntimeError("Couldn't manufacture an unused module name.")
    f, pathname, desc = imp.find_module(name, sys.path[1:])
    module = imp.load_module(random_name, f, pathname, desc)
    f.close()
    del sys.modules[random_name]
    for key in module.__dict__:
        if not hasattr(local_module, key):
            setattr(local_module, key, getattr(module, key))

copy_in_standard_module_symbols('calendar', sys.modules[copy_in_standard_module_symbols.__module__])
</code>```

Body:
The only way to solve this problem is to hijack the internal import machinery yourself. This is not easy, and fraught with peril. You should avoid the grail shaped beacon at all costs because the peril is too perilous.

Rename your module instead.

If you want to learn how to hijack the internal import machinery, here is where you would go about finding out how to do this:

The Importing Modules section of the Python 2.7 documentation

The Importing Modules section of the Python 3.2 documentation

PEP 302 - New Import Hooks

There are sometimes good reasons to get into this peril. The reason you give is not among them. Rename your module.

If you take the perilous path, one problem you will encounter is that when you load a module it ends up with an 'official name' so that Python can avoid ever having to parse the contents of that module ever again. A mapping of the 'official name' of a module to the module object itself can be found in sys.modules.

This means that if you import calendar in one place, whatever module is imported will be thought of as the module with the official name calendar and all other attempts to import calendar anywhere else, including in other code that's part of the main Python library, will get that calendar.

It might be possible to design a customer importer using the imputil module in Python 2.x that caused modules loaded from certain paths to look up the modules they were importing in something other than sys.modules first or something like that. But that's an extremely hairy thing to be doing, and it won't work in Python 3.x anyway.

There is an extremely ugly and horrible thing you can do that does not involve hooking the import mechanism. This is something you should probably not do, but it will likely work. It turns your calendar module into a hybrid of the system calendar module and your calendar module. Thanks to Boaz Yaniv for the skeleton of the function I use. Put this at the beginning of your calendar.py file:

import sys

def copy_in_standard_module_symbols(name, local_module):
    import imp

    for i in range(0, 100):
        random_name = 'random_name_%d' % (i,)
        if random_name not in sys.modules:
            break
        else:
            random_name = None
    if random_name is None:
        raise RuntimeError("Couldn't manufacture an unused module name.")
    f, pathname, desc = imp.find_module(name, sys.path[1:])
    module = imp.load_module(random_name, f, pathname, desc)
    f.close()
    del sys.modules[random_name]
    for key in module.__dict__:
        if not hasattr(local_module, key):
            setattr(local_module, key, getattr(module, key))

copy_in_standard_module_symbols('calendar', sys.modules[copy_in_standard_module_symbols.__module__])

ContentLicense: CC BY-SA 3.0


问:
sd function returns NA when using group_by() and summarise() in dplyr (no NA values in df)
I've got a df with a binary numeric response variable (0 or 1) and several response variables. I am trying to create a table that groups by type (a 3 level variable) and step (7 levels). I want the mean response and standard deviation for each type at each step. The output table should have 21 rows with 4 variables: type, step, mean and sd.

My code looks like this:

```<code>data <- data %>% group_by(step, type) %>% summarise(Response = mean(Response), dev = sd(Response))
</code>```

The output table correctly generates the mean values, but returns NA for all sd values. I tried using 'na.rm=TRUE' to remove NA values but there aren't any in the original df for response. Any ideas?

答:
From ?sd:

The standard deviation of a length-one or zero-length vector is ‘NA’.

It's likely that your dplyr query results in length 1 or length 0 output.

Body:
I've got a df with a binary numeric response variable (0 or 1) and several response variables. I am trying to create a table that groups by type (a 3 level variable) and step (7 levels). I want the mean response and standard deviation for each type at each step. The output table should have 21 rows with 4 variables: type, step, mean and sd.

My code looks like this:

data <- data %>% group_by(step, type) %>% summarise(Response = mean(Response), dev = sd(Response))

The output table correctly generates the mean values, but returns NA for all sd values. I tried using 'na.rm=TRUE' to remove NA values but there aren't any in the original df for response. Any ideas?


问:
Finding if a property inside a list inside a list doesnt contain a specific string
I have a huge product database im working with threw a api

The API returns a Product those Products have MetaData which are stuff like minQuantities Maxes ect

Now I noticed some products dont have "variation_maximum_allowed_quantity" or " maximum_allowed_quantity"

So for every Product I have to look threw That Products meta data to so something like

```<code> foreach (var item in VarProduct)
 {
   foreach (var metaItem in item.meta_data)
    {

    }

 }
</code>```

The issue is meta_data have Key's Id's and value's I need to check against every key inside of every meta_data inside of every Product if that makes sense? Im wrecking my brain atm, Anyone know how I can check against all of those to see if those 2 Strings are missing? I need to be able to do something like

```<code>if(mdDoesntcontain)
{
 //This means stock is Unlimiteed so need to set a value for stock
   item.stockquantity = 9999999; (or int.maxValue())
}

</code>```

Little tricky Posting this as a Block but:

```<code>
-item.meta_data count = w.e
 -[0]
   -base
     -id = 101231
     -key = "min_max_rules"
     -value = "no"

 -[1]
   -base
     -id = 123131
     -key = "variation_minimum_allowed_quantity"
     -value = ""(this means 1 usually)

</code>```

```<code>public class MetaData
{
    private object preValue;

    [DataMember (EmitDefaultValue = false)]
    public int? id {
        get;
        set;
    }

    [DataMember (EmitDefaultValue = false)]
    public string key {
        get;
        set;
    }

    [DataMember (EmitDefaultValue = false)]
    public object value {
        get;
        set;
    }
</code>```

答:
```<code>foreach (var item in VarProduct)
{
    hasQuantity = false;
    foreach (var metaItem in item.meta_data)
    {
        if (metaItem.id == "variation_maximum_allowed_quantity" || metaItem.id == "maximum_allowed_quantity") {
            hasQuantity = true;
            break;
        }
    }
    if (!hasQuantity) {
        item.stockQuantity = int.MaxValue;
    }
}
</code>```

Body:
I have a huge product database im working with threw a api

The API returns a Product those Products have MetaData which are stuff like minQuantities Maxes ect

Now I noticed some products dont have "variation_maximum_allowed_quantity" or " maximum_allowed_quantity"

So for every Product I have to look threw That Products meta data to so something like

 foreach (var item in VarProduct)
 {
   foreach (var metaItem in item.meta_data)
    {

    }

 }

The issue is meta_data have Key's Id's and value's I need to check against every key inside of every meta_data inside of every Product if that makes sense? Im wrecking my brain atm, Anyone know how I can check against all of those to see if those 2 Strings are missing? I need to be able to do something like

if(mdDoesntcontain)
{
 //This means stock is Unlimiteed so need to set a value for stock
   item.stockquantity = 9999999; (or int.maxValue())
}

Little tricky Posting this as a Block but:

-item.meta_data count = w.e
 -[0]
   -base
     -id = 101231
     -key = "min_max_rules"
     -value = "no"

 -[1]
   -base
     -id = 123131
     -key = "variation_minimum_allowed_quantity"
     -value = ""(this means 1 usually)

public class MetaData
{
    private object preValue;

    [DataMember (EmitDefaultValue = false)]
    public int? id {
        get;
        set;
    }

    [DataMember (EmitDefaultValue = false)]
    public string key {
        get;
        set;
    }

    [DataMember (EmitDefaultValue = false)]
    public object value {
        get;
        set;
    }


问:
Is it dangerous to name a protobuf field message?
Consider the following protobuf:

```<code>message SendRequest {
  /** The raw text of the message that the caller wishes to send. */
  optional string message = 1;
}
</code>```

Note that the string message is being used as a field name. The protobuf compilers seems to be fine with this, even though message is the protobuf keyword.

Is this usage kosher in the sense that keywords are defined by some standard to be ignored in field names, or could this break my application in the future?

答: Yes, it is possible because in runtime a proto field is identified by their id (in your case 1) and not with their name.</p>

Body:
Consider the following protobuf:

message SendRequest {
  /** The raw text of the message that the caller wishes to send. */
  optional string message = 1;
}

Note that the string message is being used as a field name. The protobuf compilers seems to be fine with this, even though message is the protobuf keyword.

Is this usage kosher in the sense that keywords are defined by some standard to be ignored in field names, or could this break my application in the future?


问:
Angular 9: i18n in TypeScript
I studied the new i18n feature in Angular 9. https://angular.io/guide/i18n

How to translate text in TypeScript, e.g. SnackBar messages?

答:
Check this blog https://blog.ninja-squad.com/2019/12/10/angular-localize/

UPDATE FOR 2022

From Offical Doc: https://angular.io/api/localize

```<code>@Component({
  template: '{{ title }}'
})
export class HomeComponent {
  title = $localize`You have 10 users`;
}
</code>```

And

You have to manually add it to your messages.fr.xlf

```<code><trans-unit id="6480943972743237078">
  <source>You have 10 users</source>
  <target>Vous avez 10 utilisateurs</target>
</trans-unit>
</code>```

don't forgot re serve your angular application.

UPDATE FOR ID

```<code>@Component({
  template: '{{ title }}'
})
export class HomeComponent {
  title = $localize`:@@6480943972743237078:`;
}
</code>```

https://github.com/angular/angular/blob/252966bcca91ea4deb0e52f1f1d0d3f103f84ccd/packages/localize/init/index.ts#L31

Title: Angular 9: i18n in TypeScript

Body:
Check this blog https://blog.ninja-squad.com/2019/12/10/angular-localize/

UPDATE FOR 2022

From Offical Doc: https://angular.io/api/localize

@Component({
  template: '{{ title }}'
})
export class HomeComponent {
  title = $localize`You have 10 users`;
}

And

You have to manually add it to your messages.fr.xlf

<trans-unit id="6480943972743237078">
  <source>You have 10 users</source>
  <target>Vous avez 10 utilisateurs</target>
</trans-unit>

don't forgot re serve your angular application.

UPDATE FOR ID

@Component({
  template: '{{ title }}'
})
export class HomeComponent {
  title = $localize`:@@6480943972743237078:`;
}

https://github.com/angular/angular/blob/252966bcca91ea4deb0e52f1f1d0d3f103f84ccd/packages/localize/init/index.ts#L31


问:
Convert strings from horizontal to vertical
I'd like to know the process of turning the following strings:

```<code>Hi
Hello
Goodbye
</code>```

To look something like this:

```<code>    e
    y
  o b
  l d
  l o
i e o
H H G
</code>```

So that the horizontal string is converted to vertical, however starts at a floor, rather than a ceiling.

If anyone could provide some advice to help me get to the right functions or commands then I would appreciate it. I would also like to know how to do this for a list of strings of length x, where x is any number greater than zero. I have experimented with a for x in list(): function, however cannot seem to produce the above output.

Thanks in advance!

答:
You can get it done using Pandas, Python3. It might not suitable for production codebase, but it works.

```<code>import pandas as pd

input_value = """Hi
Hello
Goodbye
"""

list_of_chars = list(map(lambda x: [*x], input_value.split("\n")))

df = pd.DataFrame(list_of_chars)
df = df.T[::-1].fillna(value=' ')

for index, row in df.iterrows():
    print(" ".join(row.values))
</code>```

Body:
I'd like to know the process of turning the following strings:

Hi
Hello
Goodbye

To look something like this:

    e
    y
  o b
  l d
  l o
i e o
H H G

So that the horizontal string is converted to vertical, however starts at a floor, rather than a ceiling.

If anyone could provide some advice to help me get to the right functions or commands then I would appreciate it. I would also like to know how to do this for a list of strings of length x, where x is any number greater than zero. I have experimented with a for x in list(): function, however cannot seem to produce the above output.

Thanks in advance!

Body:
You can get it done using Pandas, Python3. It might not suitable for production codebase, but it works.

import pandas as pd

input_value = """Hi
Hello
Goodbye
"""

list_of_chars = list(map(lambda x: [*x], input_value.split("\n")))

df = pd.DataFrame(list_of_chars)
df = df.T[::-1].fillna(value=' ')

for index, row in df.iterrows():
    print(" ".join(row.values))


问:
ASP.NET Core WebAPI: Bearer error="invalid_token", error_description="The signature key was not found"
I'm building ASP .NET Core WebAPI application and trying to provide Token authentication to my app:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services
                .AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

                })
                .AddJwtBearer("Bearer", jwtBearerOptions =>
                {
                    jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                    {
                        //ValidIssuer = "Issuer"
                        ValidateIssuer = false,

                                    ////ValidAudience = "WishlistAppClient",
                                    //ValidateAudience = false,

                                    ////ClockSkew = TimeSpan.FromSeconds(5),
                                    //ValidateLifetime = false,
                                    //RequireExpirationTime = false,
                                    //RequireSignedTokens = false,
                                };
                });

            services.AddMvc().AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver()
                    {
                        NamingStrategy = new SnakeCaseNamingStrategy()
                    };
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                });

            services.AddDbContext<SchemaContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("DefaultConnection"), optionBuilder => optionBuilder.MigrationsAssembly("EventManager.DAL")
                        ));

            new DALRegistration().ConfigureServices(services);

            var mappingConfig = new MapperConfiguration(configuration =>
            {
                configuration.AddProfile(new MappingProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);

            services
                .AddIdentity<SystemUser, SystemRole>()
                .AddEntityFrameworkStores<SchemaContext>()
                .AddDefaultTokenProviders();

            services.AddScoped<IUserManager, UserManager>();
            services.AddScoped<ILoginProvider, LoginProvider>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
                c.DescribeAllEnumsAsStrings();
            });
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            var todayDate = DateTime.Now.ToShortDateString().Replace('/', '.');

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.DocExpansion(DocExpansion.None);
            });

            loggerFactory.AddFile(Path.Combine(Directory.GetCurrentDirectory(), "LogInformation", $"{DateTime.Now.ToShortDateString().Replace('/','.')}.txt"));
            var logger = loggerFactory.CreateLogger("New Logger");

            app.Use(async (context, next) =>
            {
                logger.LogTrace("Processing request {0}", context.Request.Path);
                await next.Invoke();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";
                spa.Options.StartupTimeout = new TimeSpan(0, 2, 0);
                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

        }
    }
```

API Code is protected by [Authorize(AuthenticationSchemes = "Bearer")]
When I send request with any token, I always receive 401. The trouble is, that i turned off all token validation, but it does not help.

There is a picture of request in Postman

Response body is empty.
Response headers(if you can't load image):

HTTP/1.1 401 Unauthorized

Server: Kestrel

WWW-Authenticate: Bearer error="invalid_token", error_description="The signature key was not found"

X-SourceFiles: =?UTF-8?B?RDpcUmVsZWFzZVxldmVudG1hbmFnZXJcRXZlbnRNYW5hZ2VyXEV2ZW50TWFuYWdlclxhcGlccGFydGljaXBhbnRz?=

X-Powered-By: ASP.NET

Date: Thu, 20 Feb 2020 11:47:54 GMT

Connection: close

Content-Length: 0

Request:

GET

https://localhost:44372/api/participants?pageSize=30&page=1 HTTP/1.1

Host: localhost:44372

Accept: application/json

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.eNvdqZ4NbLXesaJOV-a1CzbJh_QbfTdtqwZmrFI2MLY

User-Agent: PostmanRuntime/7.22.0

Cache-Control: no-cache

Postman-Token: dcf57c4f-b08a-43e0-8d15-85a49e9de795

Accept-Encoding: gzip, deflate, br

Connection: close

答:
Here is an example to of how I've implemented

```<code>    services.AddAuthentication()
        .AddCookie()
        .AddJwtBearer(cfg =>
        {
            cfg.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidIssuer = Configuration["Tokens:Issuer"],
                ValidAudience = Configuration["Tokens:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
            };
        });
</code>```

and on the controller, similar to yours

```<code>    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
</code>```

In the authentication controller, which is called by Login page with credentials. You have to implement the below code after checking if the username and password is correct

```<code>    var claims = new[]
                    {
                      new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                    };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(
                      _config["Tokens:Issuer"],
                      _config["Tokens:Audience"],
                      claims,
                      expires: DateTime.Now.AddMinutes(30),
                      signingCredentials: creds);

                    var results = new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo
                    };
</code>```

Body:
I'm building ASP .NET Core WebAPI application and trying to provide Token authentication to my app:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services
                .AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

                })
                .AddJwtBearer("Bearer", jwtBearerOptions =>
                {
                    jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                    {
                        //ValidIssuer = "Issuer"
                        ValidateIssuer = false,

                                    ////ValidAudience = "WishlistAppClient",
                                    //ValidateAudience = false,

                                    ////ClockSkew = TimeSpan.FromSeconds(5),
                                    //ValidateLifetime = false,
                                    //RequireExpirationTime = false,
                                    //RequireSignedTokens = false,
                                };
                });

            services.AddMvc().AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver()
                    {
                        NamingStrategy = new SnakeCaseNamingStrategy()
                    };
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                });

            services.AddDbContext<SchemaContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("DefaultConnection"), optionBuilder => optionBuilder.MigrationsAssembly("EventManager.DAL")
                        ));

            new DALRegistration().ConfigureServices(services);

            var mappingConfig = new MapperConfiguration(configuration =>
            {
                configuration.AddProfile(new MappingProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);

            services
                .AddIdentity<SystemUser, SystemRole>()
                .AddEntityFrameworkStores<SchemaContext>()
                .AddDefaultTokenProviders();

            services.AddScoped<IUserManager, UserManager>();
            services.AddScoped<ILoginProvider, LoginProvider>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
                c.DescribeAllEnumsAsStrings();
            });
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            var todayDate = DateTime.Now.ToShortDateString().Replace('/', '.');

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.DocExpansion(DocExpansion.None);
            });

            loggerFactory.AddFile(Path.Combine(Directory.GetCurrentDirectory(), "LogInformation", $"{DateTime.Now.ToShortDateString().Replace('/','.')}.txt"));
            var logger = loggerFactory.CreateLogger("New Logger");

            app.Use(async (context, next) =>
            {
                logger.LogTrace("Processing request {0}", context.Request.Path);
                await next.Invoke();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";
                spa.Options.StartupTimeout = new TimeSpan(0, 2, 0);
                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

        }
    }

API Code is protected by [Authorize(AuthenticationSchemes = "Bearer")]
When I send request with any token, I always receive 401. The trouble is, that i turned off all token validation, but it does not help.

There is a picture of request in Postman

Response body is empty.
Response headers(if you can't load image):

HTTP/1.1 401 Unauthorized

Server: Kestrel

WWW-Authenticate: Bearer error="invalid_token", error_description="The signature key was not found"

X-SourceFiles: =?UTF-8?B?RDpcUmVsZWFzZVxldmVudG1hbmFnZXJcRXZlbnRNYW5hZ2VyXEV2ZW50TWFuYWdlclxhcGlccGFydGljaXBhbnRz?=

X-Powered-By: ASP.NET

Date: Thu, 20 Feb 2020 11:47:54 GMT

Connection: close

Content-Length: 0

Request:

GET

https://localhost:44372/api/participants?pageSize=30&page=1 HTTP/1.1

Host: localhost:44372

Accept: application/json

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.eNvdqZ4NbLXesaJOV-a1CzbJh_QbfTdtqwZmrFI2MLY

User-Agent: PostmanRuntime/7.22.0

Cache-Control: no-cache

Postman-Token: dcf57c4f-b08a-43e0-8d15-85a49e9de795

Accept-Encoding: gzip, deflate, br

Connection: close

Body:
Here is an example to of how I've implemented

    services.AddAuthentication()
        .AddCookie()
        .AddJwtBearer(cfg =>
        {
            cfg.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidIssuer = Configuration["Tokens:Issuer"],
                ValidAudience = Configuration["Tokens:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
            };
        });

and on the controller, similar to yours

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

In the authentication controller, which is called by Login page with credentials. You have to implement the below code after checking if the username and password is correct

    var claims = new[]
                    {
                      new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                    };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(
                      _config["Tokens:Issuer"],
                      _config["Tokens:Audience"],
                      claims,
                      expires: DateTime.Now.AddMinutes(30),
                      signingCredentials: creds);

                    var results = new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo
                    };


问:
Remove comma only from number separators (regular expression grouping)
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

```<code>Hello, world! -> Hello, world!
</code>```

but

```<code>Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337
</code>```

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

答:
Using @uingtea regex, but for pandas dataframe, you can do in this way:

```<code>import pandas as pd
import re

df = pd.DataFrame({'col':['Hello, world!', 'Warhammer 40,000', 'Codename 1,337']})
df['col'] = df['col'].apply(lambda x: re.sub(r'(\d+),(\d+)', r'\1\2', x))
</code>```

Body:
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

Hello, world! -> Hello, world!

but

Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

Body:
Using @uingtea regex, but for pandas dataframe, you can do in this way:

import pandas as pd
import re

df = pd.DataFrame({'col':['Hello, world!', 'Warhammer 40,000', 'Codename 1,337']})
df['col'] = df['col'].apply(lambda x: re.sub(r'(\d+),(\d+)', r'\1\2', x))


问:
Why must I import my delegate header files?
I am always finding that if I create a delegate and then assign a class to conform to it I have to explicitly import the delegate .h file into that class otherwise I get an error stating the protocol cannot be found?

Am I missing a global setting somewhere that allows my project to find my delegate?

Thanks

答: That is normal and expected. Otherwise that compiler would ALWAYS have to parse all headers prior to being able to compile code possibly totally unrelated to most header files.</p>


问:
Scrape an aspx site using BeautifulSoup
I would like scrape this page:

https://bakalar.vos-sosmost.cz:8080/rozvrh.aspx

I want to fill the form, with this data:

třída=1.E

Is there some easy way to fill the form and scrape site with BeautifulSoup?

答:
I suppose beautifulsoup will not help you to fill the form data

$('#combotrida_I').value = "1.E"

This is what you are supposed to do to fill the data but in this case, to automate the process you should look at using selenium to fill the data and you could use beautifulsoup to find out the elements class name which you want to fill the data to.

Here is a website that could help you get started -> https://www.guru99.com/select-option-dropdown-selenium-webdriver.html

Title: Scrape an aspx site using BeautifulSoup


问:
Angular; is this use of pipe, map and catchError useful?
I'm modifying the Angular 8 code of another developer and found this method:

```<code>retrieveByExperience(experienceId: number): Observable<any[]> {
    return this.http.get<OrganisationCode[]>(environment.serverUrl + `api/expert/experiences/${experienceId}/organisationTypes`)
        .pipe(
            map((data: OrganisationCode[]) => {
                return data;
            }),
            catchError(err =>
                throwError(err)
            )
        );
}
</code>```

The pipe seems to just return the same data obtained from the backend or rethrow the same error it caught... Can it be safely removed?

Here is an example without the pipe, that seems to behave the same way:

```<code>retrieveByExperience(experienceId: number): Observable<any[]> {
    return this.http.get<OrganisationCode[]>(environment.serverUrl + `api/expert/experiences/${experienceId}/organisationTypes`);
}
</code>```

答:
Yes, both are perfectly redundant.

Maybe they're some forgotten TODOs: "to implement some processing", "to implement custom error handler".

Body:
I'm modifying the Angular 8 code of another developer and found this method:

retrieveByExperience(experienceId: number): Observable<any[]> {
    return this.http.get<OrganisationCode[]>(environment.serverUrl + `api/expert/experiences/${experienceId}/organisationTypes`)
        .pipe(
            map((data: OrganisationCode[]) => {
                return data;
            }),
            catchError(err =>
                throwError(err)
            )
        );
}

The pipe seems to just return the same data obtained from the backend or rethrow the same error it caught... Can it be safely removed?

Here is an example without the pipe, that seems to behave the same way:

retrieveByExperience(experienceId: number): Observable<any[]> {
    return this.http.get<OrganisationCode[]>(environment.serverUrl + `api/expert/experiences/${experienceId}/organisationTypes`);
}


问:
Find all matching ids in an array of objects
We have two arrays of objects:

First:

```<code>const allUsers = [
  {
    id: 49,
    name: 'William'
  },
  {
    id: 82,
    name: 'Michael'
  },
]
</code>```

Second:

```<code>const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]
</code>```

[QUESTION]:

How can I return an array of all the users that were INACTIVE for the last 3 months? (William's)

答:
Try this

const allUsers = [
  {
    id: 49,
    name: 'William'
  },
  {
    id: 82,
    name: 'Michael'
  },
];

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
];

function isInactiveSince(lastActivity, inactiveSince) {
  let la = new Date(lastActivity);
  let s = new Date().setMonth(inactiveSince)
  return la <= s
}

function play () {
    const all = [];
 usersWithActivity.map((ua, i) => {
      if(isInactiveSince(ua.last_activity, -3)) {
        const user = allUsers.find(u => u.id == ua.id)
        all.push(user);
      }
    })
    console.log(all)
}

play()```

Body:
We have two arrays of objects:

First:

const allUsers = [
  {
    id: 49,
    name: 'William'
  },
  {
    id: 82,
    name: 'Michael'
  },
]

Second:

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]

[QUESTION]:

How can I return an array of all the users that were INACTIVE for the last 3 months? (William's)


问:
How do I set attributes for an XML element with Python?
I am using ElementTree to build an XML file.

When I try to set an element's attribute with ET.SubElement().__setattr__(), I get the error AttributeError: __setattr__.

import xml.etree.cElementTree as ET
summary = open(Summary.xml, 'w')
root = ET.Element('Summary')
ET.SubElement(root, 'TextSummary')
ET.SubElement(root,'TextSummary').__setattr__('Status','Completed') # Error occurs here
tree = ET.ElementTree(root)
tree.write(summary)
summary.close()
```

<p>After code execution, my XML should resemble the following:</p>

<pre class="lang-xml prettyprint-override"><code><Summary>
    <TextSummary Status = 'Completed'/>
</Summary>
</code>```

How do I add attributes to an XML element with Python using xml.etree.cElementTree?

答:
The best way to set multiple attributes in single line is below.
I wrote this code for SVG XML creation:</p>

```<code>from xml.etree import ElementTree as ET

svg = ET.Element('svg', attrib={'height':'210','width':'500'})
g = ET.SubElement(svg,'g', attrib={'x':'10', 'y':'12','id':'groupName'})
line = ET.SubElement(g, 'line', attrib={'x1':'0','y1':'0','x2':'200','y2':'200','stroke':'red'})

print(ET.tostring(svg, encoding="us-ascii", method="xml"))
</code>```

Body:
I am using ElementTree to build an XML file.

When I try to set an element's attribute with ET.SubElement().__setattr__(), I get the error AttributeError: __setattr__.

import xml.etree.cElementTree as ET
summary = open(Summary.xml, 'w')
root = ET.Element('Summary')
ET.SubElement(root, 'TextSummary')
ET.SubElement(root,'TextSummary').__setattr__('Status','Completed') # Error occurs here
tree = ET.ElementTree(root)
tree.write(summary)
summary.close()

After code execution, my XML should resemble the following:

    <TextSummary Status = 'Completed'/>

How do I add attributes to an XML element with Python using xml.etree.cElementTree?

Body:
The best way to set multiple attributes in single line is below.
I wrote this code for SVG XML creation:

from xml.etree import ElementTree as ET

svg = ET.Element('svg', attrib={'height':'210','width':'500'})
g = ET.SubElement(svg,'g', attrib={'x':'10', 'y':'12','id':'groupName'})
line = ET.SubElement(g, 'line', attrib={'x1':'0','y1':'0','x2':'200','y2':'200','stroke':'red'})

print(ET.tostring(svg, encoding="us-ascii", method="xml"))


问:
What tool do you use for developing and administrating your database?
I have always used TOAD by Quest to do my development and administration work in Oracle and MS SQL Server. However, I am trying not to be myopic in my choices. Are there other tools that you would recommend that will allow me to connect to the database(s) and perform my development and administrative duties?</p>

答: I personally like MS SQL Server Management Studio to SQL Sever. SSMS 2008 is a very good improvement over SSMS 2005.</p>

OwnerDisplayName: Ascalonian

ContentLicense: CC BY-SA 2.5