问:
A better/faster way to handle human names in Pandas columns?
I am dealing with a large amount of data that includes the standard five columns for human names (prefix, firstname, middlename, lastname, suffix) and I would like to merge them in a separate column as a readable name. The issue I have is with handling blank values - the issue creates spacing problems. Also, I cannot modify the original columns. My current process feels a little insane (but it works!) so I am looking for a more elegant solution.

My current code:

```<code>def add_space_prefix(x):
    x = str(x)
    if len(x) > 0:
        return x + ' '
    else:
        return x

def add_space_middle(x):
    x = str(x)
    if len(x) > 0:
        return ' ' + x
    else:
        return x

def add_space_suffix(x):
    x = str(x)
    if len(x) > 0:
        return ', ' + x
    else:
        return x`

df["middlename"] =
df["middlename"].map(lambda x: add_space_middle(x))
df["prefix"] = df["prefix"].map(lambda x: add_space_prefix(x))
df["suffix"] = df["suffix"].map(lambda x: add_space_suffix(x))
df['fullname'] = df["prefix"] + df["firstname"] + df[
        "middlename"] + ' ' + df["lastname"] + df['suffix']
</code>```

Sample Dataframe

```<code>    prefix  firstname   middlename  lastname    suffix  fullname
0           Michael                 Hobart      Jr.     Michael Jobart, Jr.
1   Mr.     Alan                    Lilt                Mr. Alan Lilt
2           Jon         A.          Smith       III     Jon A. Smith, III
3           Joe                     Miller              Joe Miller
4           Mika        Jennifer    Shabosky            Mika Jennifer Shabosky
5   Mrs.    Angela                  Calder              Mrs. Angela Calder
6           Boris       Al          Bert        Esq.    Boris Al Bert, Esq.
7   Dr.     Natasha                 Chorus              Dr. Natasha Chorus
8           Bill                    Gibbons             Bill Gibbons
</code>```

答:
Option 1

' '.join and pd.Series.str

In this solution we join the entire row by spaces.  This may lead to spaces at the beginning or end of the string or with 2 or more spaces in the middle.  We handle this by chaining string accessor methods.

```<code>df.assign(
    lastname=df.lastname + ','
).apply(' '.join, 1).str.replace('\s+', ' ').str.strip(' ,')

0       Michael Hobart, Jr.
1             Mr. Alan Lilt
2         Jon A. Smith, III
3                Joe Miller
4    Mika Jennifer Shabosky
5        Mrs. Angela Calder
6       Boris Al Bert, Esq.
7        Dr. Natasha Chorus
8              Bill Gibbons
dtype: object
</code>```

```<code>df['fullname'] = df.assign(
    lastname=df.lastname + ','
).apply(' '.join, 1).str.replace('\s+', ' ').str.strip(' ,')
df

  prefix firstname middlename  lastname suffix                fullname
0          Michael               Hobart    Jr.     Michael Hobart, Jr.
1    Mr.      Alan                 Lilt                  Mr. Alan Lilt
2              Jon         A.     Smith    III       Jon A. Smith, III
3              Joe               Miller                     Joe Miller
4             Mika   Jennifer  Shabosky         Mika Jennifer Shabosky
5   Mrs.    Angela               Calder             Mrs. Angela Calder
6            Boris         Al      Bert   Esq.     Boris Al Bert, Esq.
7    Dr.   Natasha               Chorus             Dr. Natasha Chorus
8             Bill              Gibbons                   Bill Gibbons
</code>```

Option 2

list comprehension

In this solution, we perform the same activities as with the first solution, but we bundle the string operations together and within a comprehension.

```<code>[re.sub(r'\s+', ' ', ' '.join(s)).strip(' ,')
 for s in df.assign(lastname=df.lastname + ',').values.tolist()]

['Michael Hobart, Jr.',
 'Mr. Alan Lilt',
 'Jon A. Smith, III',
 'Joe Miller',
 'Mika Jennifer Shabosky',
 'Mrs. Angela Calder',
 'Boris Al Bert, Esq.',
 'Dr. Natasha Chorus',
 'Bill Gibbons']
</code>```

```<code>df['fullname'] = [re.sub(r'\s+', ' ', ' '.join(s)).strip(' ,')
                  for s in df.assign(lastname=df.lastname + ',').values.tolist()]
df

  prefix firstname middlename  lastname suffix                fullname
0          Michael               Hobart    Jr.     Michael Hobart, Jr.
1    Mr.      Alan                 Lilt                  Mr. Alan Lilt
2              Jon         A.     Smith    III       Jon A. Smith, III
3              Joe               Miller                     Joe Miller
4             Mika   Jennifer  Shabosky         Mika Jennifer Shabosky
5   Mrs.    Angela               Calder             Mrs. Angela Calder
6            Boris         Al      Bert   Esq.     Boris Al Bert, Esq.
7    Dr.   Natasha               Chorus             Dr. Natasha Chorus
8             Bill              Gibbons                   Bill Gibbons
</code>```

Option 3

pd.replace and pd.DataFrame.stack

This one is a bit different in that we replace blanks '' with np.nan so that when we stack the np.nan are naturally dropped.  This makes for the joining with ' ' more straight forward.

```<code>df.assign(
    lastname=df.lastname + ','
).replace('', np.nan).stack().groupby(level=0).apply(' '.join).str.strip(',')

0       Michael Hobart, Jr.
1             Mr. Alan Lilt
2         Jon A. Smith, III
3                Joe Miller
4    Mika Jennifer Shabosky
5        Mrs. Angela Calder
6       Boris Al Bert, Esq.
7        Dr. Natasha Chorus
8              Bill Gibbons
dtype: object
</code>```

```<code>df['fullname'] = df.assign(
    lastname=df.lastname + ','
).replace('', np.nan).stack().groupby(level=0).apply(' '.join).str.strip(',')
df

  prefix firstname middlename  lastname suffix                fullname
0          Michael               Hobart    Jr.     Michael Hobart, Jr.
1    Mr.      Alan                 Lilt                  Mr. Alan Lilt
2              Jon         A.     Smith    III       Jon A. Smith, III
3              Joe               Miller                     Joe Miller
4             Mika   Jennifer  Shabosky         Mika Jennifer Shabosky
5   Mrs.    Angela               Calder             Mrs. Angela Calder
6            Boris         Al      Bert   Esq.     Boris Al Bert, Esq.
7    Dr.   Natasha               Chorus             Dr. Natasha Chorus
8             Bill              Gibbons                   Bill Gibbons
</code>```

Timing

bundling within a comprehension is fastest!

```<code>%timeit df.assign(fullname=df.replace('', np.nan).stack().groupby(level=0).apply(' '.join))
%timeit df.assign(fullname=df.apply(' '.join, 1).str.replace('\s+', ' ').str.strip())
%timeit df.assign(fullname=[re.sub(r'\s+', ' ', ' '.join(s)).strip() for s in df.values.tolist()])

100 loops, best of 3: 2.51 ms per loop
1000 loops, best of 3: 979 µs per loop
1000 loops, best of 3: 384 µs per loop
</code>```

Body:
I am dealing with a large amount of data that includes the standard five columns for human names (prefix, firstname, middlename, lastname, suffix) and I would like to merge them in a separate column as a readable name. The issue I have is with handling blank values - the issue creates spacing problems. Also, I cannot modify the original columns. My current process feels a little insane (but it works!) so I am looking for a more elegant solution.

My current code:

def add_space_prefix(x):
    x = str(x)
    if len(x) > 0:
        return x + ' '
    else:
        return x

def add_space_middle(x):
    x = str(x)
    if len(x) > 0:
        return ' ' + x
    else:
        return x

def add_space_suffix(x):
    x = str(x)
    if len(x) > 0:
        return ', ' + x
    else:
        return x`

df["middlename"] =
df["middlename"].map(lambda x: add_space_middle(x))
df["prefix"] = df["prefix"].map(lambda x: add_space_prefix(x))
df["suffix"] = df["suffix"].map(lambda x: add_space_suffix(x))
df['fullname'] = df["prefix"] + df["firstname"] + df[
        "middlename"] + ' ' + df["lastname"] + df['suffix']

Sample Dataframe

    prefix  firstname   middlename  lastname    suffix  fullname
0           Michael                 Hobart      Jr.     Michael Jobart, Jr.
1   Mr.     Alan                    Lilt                Mr. Alan Lilt
2           Jon         A.          Smith       III     Jon A. Smith, III
3           Joe                     Miller              Joe Miller
4           Mika        Jennifer    Shabosky            Mika Jennifer Shabosky
5   Mrs.    Angela                  Calder              Mrs. Angela Calder
6           Boris       Al          Bert        Esq.    Boris Al Bert, Esq.
7   Dr.     Natasha                 Chorus              Dr. Natasha Chorus
8           Bill                    Gibbons             Bill Gibbons

Body:
Option 1

' '.join and pd.Series.str

In this solution we join the entire row by spaces.  This may lead to spaces at the beginning or end of the string or with 2 or more spaces in the middle.  We handle this by chaining string accessor methods.

df.assign(
    lastname=df.lastname + ','
).apply(' '.join, 1).str.replace('\s+', ' ').str.strip(' ,')

0       Michael Hobart, Jr.
1             Mr. Alan Lilt
2         Jon A. Smith, III
3                Joe Miller
4    Mika Jennifer Shabosky
5        Mrs. Angela Calder
6       Boris Al Bert, Esq.
7        Dr. Natasha Chorus
8              Bill Gibbons
dtype: object

df['fullname'] = df.assign(
    lastname=df.lastname + ','
).apply(' '.join, 1).str.replace('\s+', ' ').str.strip(' ,')
df

  prefix firstname middlename  lastname suffix                fullname
0          Michael               Hobart    Jr.     Michael Hobart, Jr.
1    Mr.      Alan                 Lilt                  Mr. Alan Lilt
2              Jon         A.     Smith    III       Jon A. Smith, III
3              Joe               Miller                     Joe Miller
4             Mika   Jennifer  Shabosky         Mika Jennifer Shabosky
5   Mrs.    Angela               Calder             Mrs. Angela Calder
6            Boris         Al      Bert   Esq.     Boris Al Bert, Esq.
7    Dr.   Natasha               Chorus             Dr. Natasha Chorus
8             Bill              Gibbons                   Bill Gibbons

Option 2

list comprehension

In this solution, we perform the same activities as with the first solution, but we bundle the string operations together and within a comprehension.

[re.sub(r'\s+', ' ', ' '.join(s)).strip(' ,')
 for s in df.assign(lastname=df.lastname + ',').values.tolist()]

['Michael Hobart, Jr.',
 'Mr. Alan Lilt',
 'Jon A. Smith, III',
 'Joe Miller',
 'Mika Jennifer Shabosky',
 'Mrs. Angela Calder',
 'Boris Al Bert, Esq.',
 'Dr. Natasha Chorus',
 'Bill Gibbons']

df['fullname'] = [re.sub(r'\s+', ' ', ' '.join(s)).strip(' ,')
                  for s in df.assign(lastname=df.lastname + ',').values.tolist()]
df

  prefix firstname middlename  lastname suffix                fullname
0          Michael               Hobart    Jr.     Michael Hobart, Jr.
1    Mr.      Alan                 Lilt                  Mr. Alan Lilt
2              Jon         A.     Smith    III       Jon A. Smith, III
3              Joe               Miller                     Joe Miller
4             Mika   Jennifer  Shabosky         Mika Jennifer Shabosky
5   Mrs.    Angela               Calder             Mrs. Angela Calder
6            Boris         Al      Bert   Esq.     Boris Al Bert, Esq.
7    Dr.   Natasha               Chorus             Dr. Natasha Chorus
8             Bill              Gibbons                   Bill Gibbons

Option 3

pd.replace and pd.DataFrame.stack

This one is a bit different in that we replace blanks '' with np.nan so that when we stack the np.nan are naturally dropped.  This makes for the joining with ' ' more straight forward.

df.assign(
    lastname=df.lastname + ','
).replace('', np.nan).stack().groupby(level=0).apply(' '.join).str.strip(',')

0       Michael Hobart, Jr.
1             Mr. Alan Lilt
2         Jon A. Smith, III
3                Joe Miller
4    Mika Jennifer Shabosky
5        Mrs. Angela Calder
6       Boris Al Bert, Esq.
7        Dr. Natasha Chorus
8              Bill Gibbons
dtype: object

df['fullname'] = df.assign(
    lastname=df.lastname + ','
).replace('', np.nan).stack().groupby(level=0).apply(' '.join).str.strip(',')
df

  prefix firstname middlename  lastname suffix                fullname
0          Michael               Hobart    Jr.     Michael Hobart, Jr.
1    Mr.      Alan                 Lilt                  Mr. Alan Lilt
2              Jon         A.     Smith    III       Jon A. Smith, III
3              Joe               Miller                     Joe Miller
4             Mika   Jennifer  Shabosky         Mika Jennifer Shabosky
5   Mrs.    Angela               Calder             Mrs. Angela Calder
6            Boris         Al      Bert   Esq.     Boris Al Bert, Esq.
7    Dr.   Natasha               Chorus             Dr. Natasha Chorus
8             Bill              Gibbons                   Bill Gibbons

Timing

bundling within a comprehension is fastest!

%timeit df.assign(fullname=df.replace('', np.nan).stack().groupby(level=0).apply(' '.join))
%timeit df.assign(fullname=df.apply(' '.join, 1).str.replace('\s+', ' ').str.strip())
%timeit df.assign(fullname=[re.sub(r'\s+', ' ', ' '.join(s)).strip() for s in df.values.tolist()])

100 loops, best of 3: 2.51 ms per loop
1000 loops, best of 3: 979 µs per loop
1000 loops, best of 3: 384 µs per loop


来源: stackexchange

问:
In django prepopulated_fields = {"slug": ("title",)} doesn't show all words
I am using

```<code>prepopulated_fields = {"slug": ("title",)}
</code>```

in my django admin area and when I type certain words like

```<code> this is the first slug
</code>```

into the title field

only

```<code>first-slug
</code>```

is outputted in the slug field, and if I delete the "t"in the title field

the slug field will then output

```<code>his-first-slug
</code>```

"is" and "the" won't show up

in the slug field. Why is that? or better yet How can I fix this so that anything I type in the title field is properly displayed in the slug field

答:
There is actually a filter in action that prevents certain words from ending up in the slug or url. You can see the source of that here. What it does is that it makes sure that you don't end up with words or symbols in the slug/url that just shouldn't be there.

How to fix it? Just change the mentioned file in /django/contrib/admin/static/admin/js/urlify.py and you should be good to go.

ContentLicense: CC BY-SA 3.0

Body:
I am using

prepopulated_fields = {"slug": ("title",)}

in my django admin area and when I type certain words like

 this is the first slug

into the title field

only

first-slug

is outputted in the slug field, and if I delete the "t"in the title field

the slug field will then output

his-first-slug

"is" and "the" won't show up

in the slug field. Why is that? or better yet How can I fix this so that anything I type in the title field is properly displayed in the slug field


问:
Angular 2 - Call other component function
i'm trying to call another component function from a component. This is my constructor :

```<code>    constructor(
        private http: Http,
        private appComponent: AppComponent
        ) {
        this.setUrl();
    }

    setUrl() {
        if (this.appComponent) {
            this.Url = this.appComponent.getEnvironnement();
        } else {
            setInterval(this.setUrl, 1000);
        }
    }
</code>```

However, when I'm trying to property/function from my appComponent, I get an error saying : appComponent is undefined

Why my component is undefined, even if I initialize it on the beginning ?

答:
Assuming that the non-app component is a child of the app component you could just flow data from the app component down to the child component.  Here we have the app component contain the environmentUrl logic.  This is then saved to as environmentUrl.  This is then passed down to the my-child component's url property.  Therefore no need to have the child component access the parent component's function, instead we can just flow the data down from the parent to the child.

```<code>@Component({
  selector: 'my-app',
  template: `
    <my-child [url]="environmentUrl"></my-child>
  `
})
export class App {
  environmentUrl: string;

  constructor() {
    this.environmentUrl = getEnvironment();
  }

  getEnvironment() {
    return '/some/url';
  }
}

@Component({
  selector: 'my-child',
  template: `
    <div>
      <h2>{{url}}</h2>
    </div>
  `,
})
export class ChildComponent {

  @Input() url: string;

  constructor() {
  }
}
</code>```

Another advantage of this approach is that the ChildComponent is more reusable.  The ChildComponent doesn't know anything about the parent's method and can be used without explicitedly relying on the parent component.

Body:
i'm trying to call another component function from a component. This is my constructor :

    constructor(
        private http: Http,
        private appComponent: AppComponent
        ) {
        this.setUrl();
    }

    setUrl() {
        if (this.appComponent) {
            this.Url = this.appComponent.getEnvironnement();
        } else {
            setInterval(this.setUrl, 1000);
        }
    }

However, when I'm trying to property/function from my appComponent, I get an error saying : appComponent is undefined

Why my component is undefined, even if I initialize it on the beginning ?

Body:
Assuming that the non-app component is a child of the app component you could just flow data from the app component down to the child component.  Here we have the app component contain the environmentUrl logic.  This is then saved to as environmentUrl.  This is then passed down to the my-child component's url property.  Therefore no need to have the child component access the parent component's function, instead we can just flow the data down from the parent to the child.

@Component({
  selector: 'my-app',
  template: `
    <my-child [url]="environmentUrl"></my-child>
  `
})
export class App {
  environmentUrl: string;

  constructor() {
    this.environmentUrl = getEnvironment();
  }

  getEnvironment() {
    return '/some/url';
  }
}

@Component({
  selector: 'my-child',
  template: `
    <div>
      <h2>{{url}}</h2>
    </div>
  `,
})
export class ChildComponent {

  @Input() url: string;

  constructor() {
  }
}

Another advantage of this approach is that the ChildComponent is more reusable.  The ChildComponent doesn't know anything about the parent's method and can be used without explicitedly relying on the parent component.


问:
Typescript: "X" is not assignable to type, types of property "Y" are incompatible
Note: I am quite new to Angular2 and typescript, so I am sorry for my ignorance.

The issue:
What I'm trying to do is to subtract a start date/time from the end date/time then use that in a formula for my calculation to display as "calc". The problem is that I can give calc a static number which works, but if I try to use the math formula it gives all kinds of errors when transpiling:

1
  mock-orders.ts(4,14): error TS2322: Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order[]'.

Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order'.

Types of property 'checks' are incompatible.

Type 'string' is not assignable to type 'number'.

Below is the child component where I'm having these issues.
See line 28 this.calc:

```<code>     // order.ts
import { Component, OnInit } from '@angular/core';

export class Order {
    order_no: string;
    scheduled: string;
    lateral: string;
    start_time: string;
    checks: number;
    stop_time: string;
    status: string;
    approx_cfs: string;
    approx_hrs: string;
    approx_af: string;
    calc: number;

    constructor(data: {} = {}) {
    this.order_no = data["order_no"] || "";
    this.scheduled = data["scheduled"] || "";
    this.lateral = data["lateral"] || "";
    this.start_time = data["start_time"] || "";
    this.checks = data["checks"] || "";
    this.stop_time = data["stop_time"] || "";
    this.status = data["status"] || "";
    this.approx_cfs = data["approx_cfs"] || "";
    this.approx_hrs = data["approx_hrs"] || "";
    this.approx_af = data["approx_af"] || "";
    this.calc = (!this.stop_time ? ((new Date().getTime() - new Date(this.start_time).getTime()) / 1000.0 / 60.0 / 60.0) * this.checks * 0.0825 : ((new Date(this.stop_time).getTime() - new Date(this.start_time).getTime()) /1000.0 / 60.0 / 60.0) * this.checks * 0.0825);

    console.log(this.calc);
    };

};
</code>```

Part of the issue, I'm sure, is that I'm trying to use math operations on dates, then assign the result to a number type.

The following call this component for use in the service:

```<code>// order.service.ts
import { Injectable } from '@angular/core';

import { Order } from './order';
import { ORDERS } from './mock-orders';

@Injectable()
export class OrderService {
  getOrders(): Promise<Order[]> {
    return Promise.resolve(ORDERS);
  }
}
</code>```

The following file is the data arrays pulled each time the service runs, to depict what will be received from the database.

```<code>// mock-orders.ts
import { Order } from './order'

export const ORDERS: Order[] = [
    {order_no: '12345',
    scheduled: '08/16/16 13:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/16/16 15:45',
    checks: '23.25',
    stop_time: '08/17/16 15:30',
    status: 'Delivered',
    approx_cfs: '25.00',
    approx_hrs: '22',
    approx_af: '45.38',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    }
];
</code>```

答:
The issue is you are trying to assign string type value to checks variable which is of type number.

start_time: string;
 checks: number;
 stop_time: string;

Assigned values:-

start_time: '08/17/16 15:30',
 checks: '20.25',
 stop_time: '',

Body:
Note: I am quite new to Angular2 and typescript, so I am sorry for my ignorance.

The issue:
What I'm trying to do is to subtract a start date/time from the end date/time then use that in a formula for my calculation to display as "calc". The problem is that I can give calc a static number which works, but if I try to use the math formula it gives all kinds of errors when transpiling:

1
  mock-orders.ts(4,14): error TS2322: Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order[]'.

Type '{ order_no: string; scheduled: string; lateral: string; start_time: string; checks: string; stop_...' is not assignable to type 'Order'.

Types of property 'checks' are incompatible.

Type 'string' is not assignable to type 'number'.

Below is the child component where I'm having these issues.
See line 28 this.calc:

     // order.ts
import { Component, OnInit } from '@angular/core';

export class Order {
    order_no: string;
    scheduled: string;
    lateral: string;
    start_time: string;
    checks: number;
    stop_time: string;
    status: string;
    approx_cfs: string;
    approx_hrs: string;
    approx_af: string;
    calc: number;

    constructor(data: {} = {}) {
    this.order_no = data["order_no"] || "";
    this.scheduled = data["scheduled"] || "";
    this.lateral = data["lateral"] || "";
    this.start_time = data["start_time"] || "";
    this.checks = data["checks"] || "";
    this.stop_time = data["stop_time"] || "";
    this.status = data["status"] || "";
    this.approx_cfs = data["approx_cfs"] || "";
    this.approx_hrs = data["approx_hrs"] || "";
    this.approx_af = data["approx_af"] || "";
    this.calc = (!this.stop_time ? ((new Date().getTime() - new Date(this.start_time).getTime()) / 1000.0 / 60.0 / 60.0) * this.checks * 0.0825 : ((new Date(this.stop_time).getTime() - new Date(this.start_time).getTime()) /1000.0 / 60.0 / 60.0) * this.checks * 0.0825);

    console.log(this.calc);
    };

};

Part of the issue, I'm sure, is that I'm trying to use math operations on dates, then assign the result to a number type.

The following call this component for use in the service:

// order.service.ts
import { Injectable } from '@angular/core';

import { Order } from './order';
import { ORDERS } from './mock-orders';

@Injectable()
export class OrderService {
  getOrders(): Promise<Order[]> {
    return Promise.resolve(ORDERS);
  }
}

The following file is the data arrays pulled each time the service runs, to depict what will be received from the database.

// mock-orders.ts
import { Order } from './order'

export const ORDERS: Order[] = [
    {order_no: '12345',
    scheduled: '08/16/16 13:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/16/16 15:45',
    checks: '23.25',
    stop_time: '08/17/16 15:30',
    status: 'Delivered',
    approx_cfs: '25.00',
    approx_hrs: '22',
    approx_af: '45.38',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    },

    {order_no: '12346',
    scheduled: '08/17/16 11:45',
    lateral: 'L1-8-1-T7, L1-8-1-T6',
    start_time: '08/17/16 15:30',
    checks: '20.25',
    stop_time: '',
    status: 'Running',
    approx_cfs: '25.00',
    approx_hrs: '10',
    approx_af: '20.63',
    }
];


问:
How to return multiple values within a group of rows.
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

```<code>TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6
</code>```

I want to see the results:

```<code>ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6
</code>```

I have tried:

```<code>select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )
</code>```

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.

答:
```<code>SELECT DISTINCT ID, Location, ConfigID
FROM Table
WHERE ConfigID IS NULL
      OR ID = (SELECT ID FROM Table AS t2
                       WHERE t2.Location = Table.Location
                                          ORDER BY ConfigID DESC LIMIT 1)
ORDER BY Location
</code>```

Body:
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6

I want to see the results:

ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6

I have tried:

select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.


问:
How to put underline under button name
I have button with name "itemname", and now I want to put underline just under character "i" in "itemname", but I don't know how I should do this. Could anyone please tell me how?</p>

答:
You should add an "&" to left of the letter you want to underline. So, a button with text "&itemname" will have the "i" underlined.
and you can get focused to the button by pressing "alt+i"

ContentLicense: CC BY-SA 2.5

Title: How to put underline under button name


问:
"NameError: name [module] is not defined" when importing module in class
I have the following test code:

```<code>import sqlite3

class database:
    def __init__(self, name):
        self.name = name

    def connect(name):
        db = sqlite3.connect("%s.db" % self.name)
        c = db.cursor()

    def test(self):
        print (3)
</code>```

If I run database('name').test(), I get 3, so that works. But if I try database('name').connect(), I get, "NameError: name 'sqlite3' is not defined"

Classes are relatively new to me and I'm still trying to figure out how they work. Thanks much for any help.

EDIT: See the comments in the answer the the solution. The problem seems to be that I was importing sqlite3 in both the file and the notebook. The solution was to import the module only in the file.

答:
You may have a typo somewhere in your description, because I think you would get another error first when doing

```<code>data = database()
data.test()
data.connect('name')
</code>```

You need to add the self to the connect def to make it a proper class method. There's also a typo in the connect call. The following should work

```<code>import sqlite3

class database:
    def __init__(self, name):
        self.name = name

    def connect(self):
        db = sqlite3.connect("%s.db" % self.name)
        c = db.cursor()

    def test(self):
        print(3)
</code>```

then do

```<code>data = database('test')
data.connect()
</code>```

Body:
I have the following test code:

import sqlite3

class database:
    def __init__(self, name):
        self.name = name

    def connect(name):
        db = sqlite3.connect("%s.db" % self.name)
        c = db.cursor()

    def test(self):
        print (3)

If I run database('name').test(), I get 3, so that works. But if I try database('name').connect(), I get, "NameError: name 'sqlite3' is not defined"

Classes are relatively new to me and I'm still trying to figure out how they work. Thanks much for any help.

EDIT: See the comments in the answer the the solution. The problem seems to be that I was importing sqlite3 in both the file and the notebook. The solution was to import the module only in the file.

Body:
You may have a typo somewhere in your description, because I think you would get another error first when doing

data = database()
data.test()
data.connect('name')

You need to add the self to the connect def to make it a proper class method. There's also a typo in the connect call. The following should work

import sqlite3

class database:
    def __init__(self, name):
        self.name = name

    def connect(self):
        db = sqlite3.connect("%s.db" % self.name)
        c = db.cursor()

    def test(self):
        print(3)

then do

data = database('test')
data.connect()


问:
How to blacklist locations (in a radius of 500 feet)
EDIT: I have self-answered it below.

I have made a question on this before, however I could not properly set it up and the whole thing was broken. Below is the geolocation script. I would like to implement the blacklisting of certain areas (within a 500 foot radius if possible). Please explain to me how and where to make changes, as I am a beginner in JavaScript. thank you. (NOTE: No list or dictionary is on the page as it was part of my problem.)

current code:

```<code>if (navigator.geolocation) {
    // Locate position
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}

// Success callback function
function displayPosition(pos) {
    var mylat = pos.coords.latitude;
    var mylong = pos.coords.longitude;
    var thediv = document.getElementById('locationinfo');
    thediv.innerHTML = '<p>Your longitude is :' +
        mylong + ' and your latitide is ' + mylat + '</p>';

// Error callback function
function errorFunction(pos) {
    alert('Error!');
}
</code>```

答:
given a blacklist structure as follows (as you refuse to share anything about the blacklist data you have)

```<code>var blacklistedCoordinates = [
    { longitude: 0, latitude: 0},
    { longitude: 1, latitude: 10},
    { longitude: 2, latitude: 20},
    { longitude: 3, latitude: 30},
    { longitude: 4, latitude: 40}
];
</code>```

your code, modified

```<code>if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}

// Success callback function
function displayPosition(pos) {
    var mylat = pos.coords.latitude;
    var mylong = pos.coords.longitude;
    var thediv = document.getElementById('locationinfo');
    thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';
    // additional code to output blacklist locations within 500ft
    blacklistedCoordinates
    .filter(black => calcCrow(black, pos.coords) < 500)
    .forEach(black => { // output blacklisted locations
        thediv.innerHTML = '<p>Blacklisted longitude is :' + black.longitude + ' and latitide is ' + black.latitude + '</p>';
    });
}
// Error callback function
function errorFunction(pos) {
    alert('Error!');
}
</code>```

code from https://stackoverflow.com/a/28673693/5053002 - modified to return feet

```<code>function calcCrow(coords1, coords2) {
    const toRad = value => value * Math.PI / 180;
    const R = 20.90223164; // work in feet
    const dLat = toRad(coords2.latitude - coords1.latitude);
    const dLon = toRad(coords2.longitude - coords1.longitude);
    const lat1 = toRad(coords1.latitude);
    const lat2 = toRad(coords2.latitude);

    const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    const d = R * c;
    return d;
}
</code>```

Body:
EDIT: I have self-answered it below.

I have made a question on this before, however I could not properly set it up and the whole thing was broken. Below is the geolocation script. I would like to implement the blacklisting of certain areas (within a 500 foot radius if possible). Please explain to me how and where to make changes, as I am a beginner in JavaScript. thank you. (NOTE: No list or dictionary is on the page as it was part of my problem.)

current code:

if (navigator.geolocation) {
    // Locate position
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}

// Success callback function
function displayPosition(pos) {
    var mylat = pos.coords.latitude;
    var mylong = pos.coords.longitude;
    var thediv = document.getElementById('locationinfo');
    thediv.innerHTML = '
Your longitude is :' +
        mylong + ' and your latitide is ' + mylat + '
';

// Error callback function
function errorFunction(pos) {
    alert('Error!');
}

Body:
given a blacklist structure as follows (as you refuse to share anything about the blacklist data you have)

var blacklistedCoordinates = [
    { longitude: 0, latitude: 0},
    { longitude: 1, latitude: 10},
    { longitude: 2, latitude: 20},
    { longitude: 3, latitude: 30},
    { longitude: 4, latitude: 40}
];

your code, modified

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}

// Success callback function
function displayPosition(pos) {
    var mylat = pos.coords.latitude;
    var mylong = pos.coords.longitude;
    var thediv = document.getElementById('locationinfo');
    thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';
    // additional code to output blacklist locations within 500ft
    blacklistedCoordinates
    .filter(black => calcCrow(black, pos.coords) < 500)
    .forEach(black => { // output blacklisted locations
        thediv.innerHTML = '<p>Blacklisted longitude is :' + black.longitude + ' and latitide is ' + black.latitude + '</p>';
    });
}
// Error callback function
function errorFunction(pos) {
    alert('Error!');
}

code from https://stackoverflow.com/a/28673693/5053002 - modified to return feet

function calcCrow(coords1, coords2) {
    const toRad = value => value * Math.PI / 180;
    const R = 20.90223164; // work in feet
    const dLat = toRad(coords2.latitude - coords1.latitude);
    const dLon = toRad(coords2.longitude - coords1.longitude);
    const lat1 = toRad(coords1.latitude);
    const lat2 = toRad(coords2.latitude);

    const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    const d = R * c;
    return d;
}


问:
How to view which cluster worker responded nodejs?
How can someone view which cluster worker responds each time a request is made to the server, in the console.log? I am using express.

答: Ok got it.. simply add the console.log(process.pid) where I handle the requests and that was it :)


问:
Match "next day" using forecast() in R
I am working through the "Forecasting Using R" DataCamp course.  I have completed the entire thing except for the last part of one particular exercise (link here, if you have an account), where I'm totally lost.  The error help it's giving me isn't helping either.  I'll put the various parts of the task down with the code I'm using to solve them:

Produce time plots of only the daily demand and maximum temperatures with facetting.

```<code>autoplot(elec[, c("Demand", "Temperature")], facets = TRUE)
</code>```

Index elec accordingly to set up the matrix of regressors to include MaxTemp for the maximum temperatures, MaxTempSq which represents the squared value of the maximum temperature, and Workday, in that order.

```<code>xreg <- cbind(MaxTemp = elec[, "Temperature"],
          MaxTempSq = elec[, "Temperature"] ^2,
          Workday = elec[,"Workday"])
</code>```

Fit a dynamic regression model of the demand column with ARIMA errors and call this fit.

```<code>fit <- auto.arima(elec[,"Demand"], xreg = xreg)
</code>```

If the next day is a working day (indicator is 1) with maximum temperature forecast to be 20°C, what is the forecast demand? Fill out the appropriate values in cbind() for the xreg argument in forecast().

This is where I'm stuck.  The sample code they supply looks like this:

```<code>forecast(___, xreg = cbind(___, ___, ___))
</code>```

I have managed to work out that the first blank is fit, so I'm trying code that looks like this:

```<code>forecast(fit, xreg = cbind(elec[,"Workday"]==1, elec[, "Temperature"]==20, elec[,"Demand"]))
</code>```

But that is giving me the error hint "Make sure to forecast the next day using the inputs given in the instructions."  Which...  doesn't tell me anything useful.  Any ideas what I should be doing instead?

答:
When you are forecasting ahead of time, you use new data that was not included in elec (which is the data set you used to fit your model). The new data was given to you in the question (temperature 20C and workday 1). Therefore, you do not need elec in your forecastcall. Just use the new data to forecast ahead:

```<code>forecast(fit, xreg = cbind(20, 20^2, 1))
</code>```

Title: Match "next day" using forecast() in R

Body:
I am working through the "Forecasting Using R" DataCamp course.  I have completed the entire thing except for the last part of one particular exercise (link here, if you have an account), where I'm totally lost.  The error help it's giving me isn't helping either.  I'll put the various parts of the task down with the code I'm using to solve them:

Produce time plots of only the daily demand and maximum temperatures with facetting.

autoplot(elec[, c("Demand", "Temperature")], facets = TRUE)

Index elec accordingly to set up the matrix of regressors to include MaxTemp for the maximum temperatures, MaxTempSq which represents the squared value of the maximum temperature, and Workday, in that order.

xreg <- cbind(MaxTemp = elec[, "Temperature"],
          MaxTempSq = elec[, "Temperature"] ^2,
          Workday = elec[,"Workday"])

Fit a dynamic regression model of the demand column with ARIMA errors and call this fit.

fit <- auto.arima(elec[,"Demand"], xreg = xreg)

If the next day is a working day (indicator is 1) with maximum temperature forecast to be 20°C, what is the forecast demand? Fill out the appropriate values in cbind() for the xreg argument in forecast().

This is where I'm stuck.  The sample code they supply looks like this:

forecast(___, xreg = cbind(___, ___, ___))

I have managed to work out that the first blank is fit, so I'm trying code that looks like this:

forecast(fit, xreg = cbind(elec[,"Workday"]==1, elec[, "Temperature"]==20, elec[,"Demand"]))

But that is giving me the error hint "Make sure to forecast the next day using the inputs given in the instructions."  Which...  doesn't tell me anything useful.  Any ideas what I should be doing instead?

Body:
When you are forecasting ahead of time, you use new data that was not included in elec (which is the data set you used to fit your model). The new data was given to you in the question (temperature 20C and workday 1). Therefore, you do not need elec in your forecastcall. Just use the new data to forecast ahead:

forecast(fit, xreg = cbind(20, 20^2, 1))


问:
Common content in all views from a shared symfony base controller
I'm using ezplatform and trying to figure out how to automatically share common cms content to all pages without writing a separate controller for each view.

This is a simple extract from the  yml file:

```<code>root_folder:
    controller: "AppBundle:Homepage:homepage"
    match:
        Id\Location: 58

article_container:
  controller: "AppBundle:ArticleContainer:articleContainerChildren"
  match:
      Identifier\ContentType: "article_container"

article_one_column:
    template: "full/article_one_column.html.twig"
    match:
        Identifier\ContentType: "article_one_column"
</code>```

These are three simple matches to there own custom controllers, with the exception of the last.

The first two matches hit a controller which extends a base controller.
Within the base controller we have a standard render function which is called like this:

```<code>return $this->render(
    'full/article_container.html.twig',
    [
        'location'         => $location,
        'content'          => $currentContent,
        'articles'         => $articles,
        'articleLocations' => $locations,
    ]
);
</code>```

The said render function looks like this:

```<code>$parameters = array_merge($parameters, [
    'main_navi'         => $navigation,
    'mega_navi_data'    => $navigation,
    'quotes'            => $contentRenderer->getQuotesData(),
    'featured_articles' => $contentRenderer->getFeaturedArticles(),
    'contact_form'      => $this->getContactForm(),
]);

return parent::render($view, $parameters, $response);
</code>```

As you can see we simply merge the original params with some common data that all pages need. This data is used for the "maga navi" and the footer content.

The problem is now that when we try to load a article_one_column page,
as this is not using a custom controller it therefore doesn't load the common data
required for the header and footer which results in an twig error.

QUESTION:
How can we deliver common content to all routes without writing a custom controller for each data type?

答:
You don't have to create a controller for each Content Type. What you want, if I may, is to inject data into the view.

Using a custom controller is one of the options, for generic stuff that you want to inject you can also use https://doc.ez.no/display/DEVELOPER/Injecting+parameters+in+content+views

We have bundled this concept (among other here: https://github.com/Novactive/NovaeZExtraBundle) with a concept of ChildrenProvider.

Also, you mentioned you wanted to inject information related to the header and the footer in the view to get them in the layout. It sounds weird. With eZ but also just with Symfony you can render a controller from a view, them you can render the header and render the footer independently from the view. (that is probably what you should do)

For the children though, I like to use the listener instead of the custom controller.
It is managed in the Novactive bundle but be careful if you do it on your own, the pre_content_view listener will trigger on each view (line, full, etc..) And usually, you want to inject stuff in the view full only.

Body:
I'm using ezplatform and trying to figure out how to automatically share common cms content to all pages without writing a separate controller for each view.

This is a simple extract from the  yml file:

root_folder:
    controller: "AppBundle:Homepage:homepage"
    match:
        Id\Location: 58

article_container:
  controller: "AppBundle:ArticleContainer:articleContainerChildren"
  match:
      Identifier\ContentType: "article_container"

article_one_column:
    template: "full/article_one_column.html.twig"
    match:
        Identifier\ContentType: "article_one_column"

These are three simple matches to there own custom controllers, with the exception of the last.

The first two matches hit a controller which extends a base controller.
Within the base controller we have a standard render function which is called like this:

return $this->render(
    'full/article_container.html.twig',
    [
        'location'         => $location,
        'content'          => $currentContent,
        'articles'         => $articles,
        'articleLocations' => $locations,
    ]
);

The said render function looks like this:

$parameters = array_merge($parameters, [
    'main_navi'         => $navigation,
    'mega_navi_data'    => $navigation,
    'quotes'            => $contentRenderer->getQuotesData(),
    'featured_articles' => $contentRenderer->getFeaturedArticles(),
    'contact_form'      => $this->getContactForm(),
]);

return parent::render($view, $parameters, $response);

As you can see we simply merge the original params with some common data that all pages need. This data is used for the "maga navi" and the footer content.

The problem is now that when we try to load a article_one_column page,
as this is not using a custom controller it therefore doesn't load the common data
required for the header and footer which results in an twig error.

QUESTION:
How can we deliver common content to all routes without writing a custom controller for each data type?


问:
Dropwizard registering two classes/clients
I have two instances of clients with different configs  that I am creating (timeout, threadpool, etc...), and would like to leverage Dropwizard's metric on both of the clients.

```<code>        final JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder(environment)
            .using(configuration.getJerseyClientConfiguration());

        final Client config1Client = jerseyClientBuilder.build("config1Client");
        environment.jersey().register(config1Client);

        final Client config2Client = jerseyClientBuilder.build("config2Client");
        environment.jersey().register(config2Client);
</code>```

However, I am getting

```<code>org.glassfish.jersey.internal.Errors: The following warnings have been detected:
HINT: Cannot create new registration for component type class org.glassfish.jersey.client.JerseyClient:
Existing previous registration found for the type.
</code>```

And only one client's metric shows up.

How do I track both clients' metrics or is it not common to have 2 clients in a single dropwizard app?

答:
Never mind, turned out I was an idiot (for trying to save some resource on the ClientBuilder).

2 Things that I did wrong with my original code:
1. You don't need to register Jersey clients, just the resource is enough... somehow I missed the resource part in my code and just straight up trying to register the client
2. You need to explicitly build each JerseyClientBuilder and then build your individually configured clients, then dropwizard will fetch by each JerseyClientBuilder's metrics

In the end, I just had to change my code to the following:

```<code>    final Client config1Client = new JerseyClientBuilder(environment)
        .using(configuration.getJerseyClientConfiguration()).build("config1Client");

    final Client config2Client = new JerseyClientBuilder(environment)
        .using(configuration.getJerseyClientConfiguration()).build("config2Client");
</code>```

Doh.

Body:
I have two instances of clients with different configs  that I am creating (timeout, threadpool, etc...), and would like to leverage Dropwizard's metric on both of the clients.

        final JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder(environment)
            .using(configuration.getJerseyClientConfiguration());

        final Client config1Client = jerseyClientBuilder.build("config1Client");
        environment.jersey().register(config1Client);

        final Client config2Client = jerseyClientBuilder.build("config2Client");
        environment.jersey().register(config2Client);

However, I am getting

org.glassfish.jersey.internal.Errors: The following warnings have been detected:
HINT: Cannot create new registration for component type class org.glassfish.jersey.client.JerseyClient:
Existing previous registration found for the type.

And only one client's metric shows up.

How do I track both clients' metrics or is it not common to have 2 clients in a single dropwizard app?

Body:
Never mind, turned out I was an idiot (for trying to save some resource on the ClientBuilder).

2 Things that I did wrong with my original code:
1. You don't need to register Jersey clients, just the resource is enough... somehow I missed the resource part in my code and just straight up trying to register the client
2. You need to explicitly build each JerseyClientBuilder and then build your individually configured clients, then dropwizard will fetch by each JerseyClientBuilder's metrics

In the end, I just had to change my code to the following:

    final Client config1Client = new JerseyClientBuilder(environment)
        .using(configuration.getJerseyClientConfiguration()).build("config1Client");

    final Client config2Client = new JerseyClientBuilder(environment)
        .using(configuration.getJerseyClientConfiguration()).build("config2Client");

Doh.


问:
Use Typescript to describe a class with dynamically added properties
I'm trying to add Typescript definitions to an existing codebase which happens to use the Knockout library. The code contains a very common pattern which looks like this:

```<code>interface SomeProperties {
    // A bunch of properties
}

class ViewModel {
    // Some properties of my own...

    constructor(data: SomeProperties) {
        AddAllPropertiesToThis(data);
    }
}
</code>```

Where AddAllPropertiesToThis takes the data object and dynamically adds all of its properties to this.

I can't figure out how to express this pattern in Typescript. It makes sense to say something like

```<code>class ViewModel implements SomeProperties
</code>```

but this requires manually copying all of the properties from the interface definition into the class.

Is there any way to accomplish what I need to do here without having to type out redundant properties?

答:
You could introduce a member variable data: SomeProperties in ViewModel.

```<code>interface SomeProperties {
    // A bunch of properties
}

class ViewModel {
    data: SomeProperties;

    constructor(data: SomeProperties) {
        // deep copy the data
        this.data = { ...data };
    }
}
</code>```

To me it makes more sense to do it by way of composition as the code above rather than inheritance. The ViewModel contains (has) SomeProperties. It is not an extension of SomeProperties ("is a" relationship).

Body:
I'm trying to add Typescript definitions to an existing codebase which happens to use the Knockout library. The code contains a very common pattern which looks like this:

interface SomeProperties {
    // A bunch of properties
}

class ViewModel {
    // Some properties of my own...

    constructor(data: SomeProperties) {
        AddAllPropertiesToThis(data);
    }
}

Where AddAllPropertiesToThis takes the data object and dynamically adds all of its properties to this.

I can't figure out how to express this pattern in Typescript. It makes sense to say something like

class ViewModel implements SomeProperties

but this requires manually copying all of the properties from the interface definition into the class.

Is there any way to accomplish what I need to do here without having to type out redundant properties?

Body:
You could introduce a member variable data: SomeProperties in ViewModel.

interface SomeProperties {
    // A bunch of properties
}

class ViewModel {
    data: SomeProperties;

    constructor(data: SomeProperties) {
        // deep copy the data
        this.data = { ...data };
    }
}

To me it makes more sense to do it by way of composition as the code above rather than inheritance. The ViewModel contains (has) SomeProperties. It is not an extension of SomeProperties ("is a" relationship).


问:
Explicit vs implicit SQL joins
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

```<code>SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
</code>```

vs.

```<code>SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
</code>```

答:
On some databases (notably Oracle) the order of the joins can make a huge difference to query performance (if there are more than two tables). On one application, we had literally two orders of magnitude difference in some cases. Using the inner join syntax gives you control over this - if you use the right hints syntax.

You didn't specify which database you're using, but probability suggests SQL Server or MySQL where there it makes no real difference.

OwnerDisplayName: dmanxiii

Title: Explicit vs implicit SQL joins

Body:
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;

vs.

SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;

LastEditorDisplayName: Eric Z Beard

OwnerDisplayName: Leigh Caldwell


问:
R - Checking multiple columns for multiple values - loop
I have a data set with multiple diagnosis columns (ie. DIAG1, DIAG2, DIAG3, etc.). I am looking to create a loop that will check each column for all of my rows, but I'm looking for more than one diagnosis code within each of those columns.

For example, I want to find code xxx1 and xxx3 if present in DIAG1, DIAG2, DIAG3, etc.

My code is below where

1. df = my dataframe

2. df$illness = is the variable I want to create

3. xxxx1 = the code I'm looking for

4. [26:34, 57:72] = the columns where DIAG1, etc. exist

**EDIT:
Example data:

```<code>DIAG3  DIAG4  DIAG5  DIAG6
1231   xxx1   5468   5468
1454   2352   4542   4864
xxx2   1235   1234   3564
1234   1589   xxx1   8498
</code>```

Code I tried to perform:

```<code>for (i in 1:nrow(df)) {
df$illness[i] <- ("xxx1" %in% df[i,26:34, 57:72] | "xxx3" %in%
df[i,26:34, 57:72]}
</code>```

What I would like my loop to perform:

```<code>DIAG3  DIAG4  DIAG5  DIAG6  Illness
1231   xxx1   5468   5468   TRUE
1454   2352   4542   4864   FALSE
xxx3   1235   1234   3564   TRUE
1234   1589   xxx1   8498   TRUE
</code>```

What happens is that the code runs but never ends. I don't know where my mistake is. Thank you

答:
I'm assuming that xxxx1 is actually supposed to be a numeric value, then you could simply use an ifelse statement such as:

```<code>dat <- data.frame(DIAG3 = c(1231,1454,2222,1234),
                    DIAG4 = c(1111,2352,1235,1589),
                    DIAG5 = c(5468,4542,1234,1111),
                    DIAG6 = c(5468,4864,3564,8498))

library(dplyr)
dat %>%
    rowwise() %>%
    mutate(Illness = ifelse(DIAG3==1111 | DIAG4==1111 | DIAG5==1111 | DIAG6==1111|
                                    DIAG3==2222 | DIAG4==2222 | DIAG5==2222 | DIAG6==2222, "TRUE", "FALSE"))
</code>```

Body:
I have a data set with multiple diagnosis columns (ie. DIAG1, DIAG2, DIAG3, etc.). I am looking to create a loop that will check each column for all of my rows, but I'm looking for more than one diagnosis code within each of those columns.

For example, I want to find code xxx1 and xxx3 if present in DIAG1, DIAG2, DIAG3, etc.

My code is below where

1. df = my dataframe

2. df$illness = is the variable I want to create

3. xxxx1 = the code I'm looking for

4. [26:34, 57:72] = the columns where DIAG1, etc. exist

**EDIT:
Example data:

DIAG3  DIAG4  DIAG5  DIAG6
1231   xxx1   5468   5468
1454   2352   4542   4864
xxx2   1235   1234   3564
1234   1589   xxx1   8498

Code I tried to perform:

for (i in 1:nrow(df)) {
df$illness[i] <- ("xxx1" %in% df[i,26:34, 57:72] | "xxx3" %in%
df[i,26:34, 57:72]}

What I would like my loop to perform:

DIAG3  DIAG4  DIAG5  DIAG6  Illness
1231   xxx1   5468   5468   TRUE
1454   2352   4542   4864   FALSE
xxx3   1235   1234   3564   TRUE
1234   1589   xxx1   8498   TRUE

What happens is that the code runs but never ends. I don't know where my mistake is. Thank you

Body:
I'm assuming that xxxx1 is actually supposed to be a numeric value, then you could simply use an ifelse statement such as:

dat <- data.frame(DIAG3 = c(1231,1454,2222,1234),
                    DIAG4 = c(1111,2352,1235,1589),
                    DIAG5 = c(5468,4542,1234,1111),
                    DIAG6 = c(5468,4864,3564,8498))

library(dplyr)
dat %>%
    rowwise() %>%
    mutate(Illness = ifelse(DIAG3==1111 | DIAG4==1111 | DIAG5==1111 | DIAG6==1111|
                                    DIAG3==2222 | DIAG4==2222 | DIAG5==2222 | DIAG6==2222, "TRUE", "FALSE"))


问:
React Router multiple optional components
I have a React app that uses React Router, and my router looks something like this:

```<code><ConnectedRouter history={history}>
        <App>
            <Route
                exact
                name="Login"
                path="/login"
                component={Login}
            />
            <Route
                exact
                name="Home"
                path="/"
                component={Home}
            >
        </App>
</ConnectedRouter>
</code>```

So far so good. However, I want to have the App be able to render a sidebar on the left, based on path (not all Routes would render a sidebar). Ideally, the Route component (e.g. Home) would be able to specify its sidebar component and the App would be able to find that and render it in the appropriate place. But App just gets a bunch of children which are Route components, and as far as I can tell, there's no way to determine which route(s) have actually been rendered from within App.

Presumably, I could have separate Route components to define the sidebar components, but I would prefer to not have to duplicate Routes so that I can associate the sidebar with its component (e.g. Home would have a sidebar and it would be possible to look at the code for the Home component to see what its sidebar would look like, rather than some other completely different file).

答:
React router is pretty powerful in terms of combining your components together based on the url. In fact, you can use some "nested" routes and the library will take care of composing components for you.

Say we want to have the following:

A more or less standalone login / register page without a sidebar

A set of Product CRUD pages that share some common layout, including
the Sidebar component

To achieve that - let's consider the following Route configuration. Note that the examples I'll be using refer to react-router 3.0.2

```<code>  <Router history={this.props.history}>
    <Route path='/' component={App}>

      //NO SIDEBAR
      <Route path='login'  component={LoginForm} />

      // STUFF WITH THE SIDEBAR
      <Route path='products' component={ProductsLayout} onEnter={this.requireAuth}>
        <Route path="new"      component={ProductForm}/>
        <Route path=":id"      component={Product}/>
        <Route path=":id/edit" component={ProductForm}/>
      </Route>
    </Route>
  </Router>
</code>```

Note that the urls for the sidebar pages will look something like /products/new and products/123/edit since the path property is inherited down by the child components.

And here is what the ProductLayout component would look like. Note that I'm using some of the Bootstrap components here (Row, Col) - but those can be ignored:

```<code>import React, { Component } from 'react';
import { Row, Col }         from 'react-bootstrap';
import Sidebar              from 'components/Sidebar';

class ProductsLayout extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Row>
        <Col xs={12} sm={6} md={4} lg={3}>
          // --> THIS IS WHERE OUR SIDEBAR COMES INTO PLAY <--
          <Sidebar/>
        </Col>
        <Col xs={12} sm={6} md={8} lg={6} className="product well">
          {this.props.children}
        </Col>
        <Col xs={12} sm={0} md={0} lg={3}>
        </Col>
      </Row>
    );
  }
}

export default ProductsLayout;
</code>```

As a result - when we go to /login - there's no sidebar. And when we go to any route prefixed with /products - there is one.

Hope that makes sense

Body:
I have a React app that uses React Router, and my router looks something like this:

<ConnectedRouter history={history}>
        <App>
            <Route
                exact
                name="Login"
                path="/login"
                component={Login}
            />
            <Route
                exact
                name="Home"
                path="/"
                component={Home}
            >
        </App>
</ConnectedRouter>

So far so good. However, I want to have the App be able to render a sidebar on the left, based on path (not all Routes would render a sidebar). Ideally, the Route component (e.g. Home) would be able to specify its sidebar component and the App would be able to find that and render it in the appropriate place. But App just gets a bunch of children which are Route components, and as far as I can tell, there's no way to determine which route(s) have actually been rendered from within App.

Presumably, I could have separate Route components to define the sidebar components, but I would prefer to not have to duplicate Routes so that I can associate the sidebar with its component (e.g. Home would have a sidebar and it would be possible to look at the code for the Home component to see what its sidebar would look like, rather than some other completely different file).

Body:
React router is pretty powerful in terms of combining your components together based on the url. In fact, you can use some "nested" routes and the library will take care of composing components for you.

Say we want to have the following:

A more or less standalone login / register page without a sidebar

A set of Product CRUD pages that share some common layout, including
the Sidebar component

To achieve that - let's consider the following Route configuration. Note that the examples I'll be using refer to react-router 3.0.2

  <Router history={this.props.history}>
    <Route path='/' component={App}>

      //NO SIDEBAR
      <Route path='login'  component={LoginForm} />

      // STUFF WITH THE SIDEBAR
      <Route path='products' component={ProductsLayout} onEnter={this.requireAuth}>
        <Route path="new"      component={ProductForm}/>
        <Route path=":id"      component={Product}/>
        <Route path=":id/edit" component={ProductForm}/>
      </Route>
    </Route>
  </Router>

Note that the urls for the sidebar pages will look something like /products/new and products/123/edit since the path property is inherited down by the child components.

And here is what the ProductLayout component would look like. Note that I'm using some of the Bootstrap components here (Row, Col) - but those can be ignored:

import React, { Component } from 'react';
import { Row, Col }         from 'react-bootstrap';
import Sidebar              from 'components/Sidebar';

class ProductsLayout extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Row>
        <Col xs={12} sm={6} md={4} lg={3}>
          // --> THIS IS WHERE OUR SIDEBAR COMES INTO PLAY <--
          <Sidebar/>
        </Col>
        <Col xs={12} sm={6} md={8} lg={6} className="product well">
          {this.props.children}
        </Col>
        <Col xs={12} sm={0} md={0} lg={3}>
        </Col>
      </Row>
    );
  }
}

export default ProductsLayout;

As a result - when we go to /login - there's no sidebar. And when we go to any route prefixed with /products - there is one.

Hope that makes sense


问:
Speck Cipher - Decryption Issue in C
I'm trying to extend the following implementation of the Speck cipher (https://github.com/inmcm/Simon_Speck_Ciphers) by adding the decryption module. I implemented the decryption algorithm by following the instructions from the original paper from NSA about Speck and Simon (https://eprint.iacr.org/2013/404).

At the moment I'm kinda stuck because I can't decipher correctly the cipher text generated from the encryption routine. I already had a look at other similar questions posted here on SO to no avail.

By checking my code and the stdout, I've noticed that the value stored in x_word in the decryption phase is not correct, starting with the first iteration. Therefore, there is probably an issue with the following instruction:

```<code>x_word = rotate_left( (sub_mod((x_word ^ *(round_key_ptr + 21 - i)), y_word, 65535)), 7);
</code>```

I'm posting the relevant part of my code here:

```<code>#define rotate_left(x,n) (x >> (word_size - n)) | (x << n)
#define rotate_right(x,n) (x << (word_size - n)) | (x >> n)

void Speck_Encrypt_32(uint8_t *key_schedule, uint8_t *plaintext, uint8_t *ciphertext) {

    const uint8_t word_size = 16;
    uint16_t y_word = *(uint16_t *)plaintext;
    uint16_t x_word = *(((uint16_t *)plaintext) + 1);
    uint16_t *round_key_ptr = (uint16_t *)key_schedule;
    uint16_t * word_ptr = (uint16_t *)ciphertext;

    for(uint8_t i = 0; i < 22; i++) {  // Block size 32 has only one round number option

        x_word = ((rotate_right(x_word, 7)) + y_word) ^ *(round_key_ptr + i);
        y_word = (rotate_left(y_word, 2)) ^ x_word;

        printf("y_word - (%d) - %u\n", i, (unsigned int)y_word);
        printf("x_word - (%d) - %u\n", i, (unsigned int)x_word);
    }
    // Assemble Ciphertext Output Array
    *word_ptr = y_word;
    word_ptr += 1;
    *word_ptr = x_word;
    return;
}

static inline uint16_t sub_mod(uint16_t a, uint16_t b, uint16_t m)
{
  if ( a>=b )
    return a - b;
  else
    return m - b + a;
}

void Speck_Decrypt_32(uint8_t *key_schedule, uint8_t *plaintext, uint8_t *ciphertext) {

    const uint8_t word_size = 16;
    // Swapping cipher text words
    uint16_t y_word = *(uint16_t *)ciphertext;
    uint16_t x_word = *(((uint16_t *)ciphertext) + 1);
    uint16_t *round_key_ptr = (uint16_t *)key_schedule;
    uint16_t * word_ptr = (uint16_t *)plaintext;

    for(int i=0; i < 4; i++) {
        printf("Ciphertext Byte %02d: %02x \n",i,ciphertext[i]);
        printf("Plaintext Byte %02d: %02x \n",i,plaintext[i]);
    }

    // Reading round keys in reverse order
    for(uint8_t i = 0; i < 22; i++) {  // Block size 32 has only one round number option

        //printf("y_word - (%d) - %u\n", i, (unsigned int)y_word);
        //printf("x_word - (%d) - %u\n", i, (unsigned int)x_word);
        // Inverting rotations and using custom modular subtraction
        y_word = rotate_right((x_word ^ y_word), 2);
        x_word = rotate_left( (sub_mod((x_word ^ *(round_key_ptr + 21 - i)), y_word, 65535)), 7);

    }
    // Assemble Plaintext - Swapping plaintext words
    *word_ptr = y_word;
    word_ptr += 1;
    *word_ptr = x_word;
    return;
}
</code>```

I haven't been coding in C in awhile, there might be a few mistakes.

答:
Just do the encryption in reverse.  So if your expanded key is k_0,...,k_{21}
then you would do the following in C.

#define ROTR(x,r) (((x > > r) | (x < < (16-r))) & 0xffff)

#define ROTL(x,r) (((x< < r) | (x > > (16-r))) & 0xffff)

#define invR(x,y,k) (y=y^x, y=ROTR(y,2), x=x^k, x=(x-y) & 0xffff, x=ROTL(x,7))

Then you do something like:

for(i=21;i>=0;i--) invR(x,y,k[i])

FYI:  SIMON and SPECK are among the most highly analyzed block ciphers in recent years.  There are more than 70 "peer reviewed" papers which analyze them (as you may check by doing a search on Google Scholar) and they have a security margin similar to AES-128. On an x86 processor, SPECK128/256 has speed nearly identical to ChaCha20 (a very fast stream cipher).  A fast software implementation of SPECK128/256 on an x86 processor is about 50% slower than AES-256 using AES-NI (i.e., the hardware instruction). See https://github.com/iadgov/simon-speck-supercop for fast implementations of SIMON and SPECK compatible with the SUPERCOP benchmarking system.

Title: Speck Cipher - Decryption Issue in C

Body:
I'm trying to extend the following implementation of the Speck cipher (https://github.com/inmcm/Simon_Speck_Ciphers) by adding the decryption module. I implemented the decryption algorithm by following the instructions from the original paper from NSA about Speck and Simon (https://eprint.iacr.org/2013/404).

At the moment I'm kinda stuck because I can't decipher correctly the cipher text generated from the encryption routine. I already had a look at other similar questions posted here on SO to no avail.

By checking my code and the stdout, I've noticed that the value stored in x_word in the decryption phase is not correct, starting with the first iteration. Therefore, there is probably an issue with the following instruction:

x_word = rotate_left( (sub_mod((x_word ^ *(round_key_ptr + 21 - i)), y_word, 65535)), 7);

I'm posting the relevant part of my code here:

#define rotate_left(x,n) (x >> (word_size - n)) | (x << n)
#define rotate_right(x,n) (x << (word_size - n)) | (x >> n)

void Speck_Encrypt_32(uint8_t *key_schedule, uint8_t *plaintext, uint8_t *ciphertext) {

    const uint8_t word_size = 16;
    uint16_t y_word = *(uint16_t *)plaintext;
    uint16_t x_word = *(((uint16_t *)plaintext) + 1);
    uint16_t *round_key_ptr = (uint16_t *)key_schedule;
    uint16_t * word_ptr = (uint16_t *)ciphertext;

    for(uint8_t i = 0; i < 22; i++) {  // Block size 32 has only one round number option

        x_word = ((rotate_right(x_word, 7)) + y_word) ^ *(round_key_ptr + i);
        y_word = (rotate_left(y_word, 2)) ^ x_word;

        printf("y_word - (%d) - %u\n", i, (unsigned int)y_word);
        printf("x_word - (%d) - %u\n", i, (unsigned int)x_word);
    }
    // Assemble Ciphertext Output Array
    *word_ptr = y_word;
    word_ptr += 1;
    *word_ptr = x_word;
    return;
}

static inline uint16_t sub_mod(uint16_t a, uint16_t b, uint16_t m)
{
  if ( a>=b )
    return a - b;
  else
    return m - b + a;
}

void Speck_Decrypt_32(uint8_t *key_schedule, uint8_t *plaintext, uint8_t *ciphertext) {

    const uint8_t word_size = 16;
    // Swapping cipher text words
    uint16_t y_word = *(uint16_t *)ciphertext;
    uint16_t x_word = *(((uint16_t *)ciphertext) + 1);
    uint16_t *round_key_ptr = (uint16_t *)key_schedule;
    uint16_t * word_ptr = (uint16_t *)plaintext;

    for(int i=0; i < 4; i++) {
        printf("Ciphertext Byte %02d: %02x \n",i,ciphertext[i]);
        printf("Plaintext Byte %02d: %02x \n",i,plaintext[i]);
    }

    // Reading round keys in reverse order
    for(uint8_t i = 0; i < 22; i++) {  // Block size 32 has only one round number option

        //printf("y_word - (%d) - %u\n", i, (unsigned int)y_word);
        //printf("x_word - (%d) - %u\n", i, (unsigned int)x_word);
        // Inverting rotations and using custom modular subtraction
        y_word = rotate_right((x_word ^ y_word), 2);
        x_word = rotate_left( (sub_mod((x_word ^ *(round_key_ptr + 21 - i)), y_word, 65535)), 7);

    }
    // Assemble Plaintext - Swapping plaintext words
    *word_ptr = y_word;
    word_ptr += 1;
    *word_ptr = x_word;
    return;
}

I haven't been coding in C in awhile, there might be a few mistakes.


问:
how do i reference an id with concatenated variable in jquery appendTo()?
I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

```<code>$(... +
    '<div class="recommendations filter" id="recCards-'+ i +'">' +
    '<div><h5>Recommended Cards</h5></div>' +
        '<ul></ul>' +
    '</div>' +
  ...
 ).appendTo('.someDiv');
</code>```

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

```<code>var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('<div>'+recCardName+'</div>').appendTo(recCardsList);
</code>```

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

答:
Try this:</p>

```<code>var recCardsList = $(div).attr('id', '.recCards-'+i+' ul');
</code>```

Body:
I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

$(... +
    '
' +
    '

Recommended Cards

' +
        '

' +
    '
' +
  ...
 ).appendTo('.someDiv');

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('
'+recCardName+'
').appendTo(recCardsList);

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

Body:
Try this:

var recCardsList = $(div).attr('id', '.recCards-'+i+' ul');


问:
Common serializer for php and java Object
I'd like to serialize an object from java and to unserialize this object in PhP. I saw different classes in java that does this but they are not able to serialize not primitive object.

By the way, do you know where I can read the details of the language generated by the function 'serialize' of php?

Thank you very much

Bat

答:
What you need is to make the Java serialization produce a serialized form that PHP understands. This can be done by creating a method with the following signature:

```<code>private void writeObject(OutputStream out)
</code>```

on the Java class. This can be used to customise the serialized form of the object. Check out this excerpt from the excellent book Effective Java by Joshua Bloch that explains how to do this (you'll need to subscribe or get a free trial to read the link, but I do recommend it)

http://my.safaribooksonline.com/book/programming/java/9780137150021/serialization/ch11lev1sec2

Unfortunately, not being a PHP developer, I can't comment too much on what the form should be. Hopefully, someone else here can help you with that.

Body:
What you need is to make the Java serialization produce a serialized form that PHP understands. This can be done by creating a method with the following signature:

private void writeObject(OutputStream out)

on the Java class. This can be used to customise the serialized form of the object. Check out this excerpt from the excellent book Effective Java by Joshua Bloch that explains how to do this (you'll need to subscribe or get a free trial to read the link, but I do recommend it)

http://my.safaribooksonline.com/book/programming/java/9780137150021/serialization/ch11lev1sec2

Unfortunately, not being a PHP developer, I can't comment too much on what the form should be. Hopefully, someone else here can help you with that.


问:
jquery random element id for every loop
sorry i'm new in jquery and i need help :-(
  i want to traverse all elements on html page with class parts
then go inside to two children and pass them a random number ( the same for them both)

for every element new random number is passed ( no repeat on page)
children classes are :
anot-head
anot-body
this is a sample code:

```<code>    $(document).ready(function() {

$.each($('.parts'), function(){
var ran=Math.floor(Math.random()* 1000000);

$( ".anot-head" ).attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
$( ".anot-body" ).attr( "id","s"+ran );

});
});
</code>```

答:
$(".anot-body") does a search of the whole document, if you want to find a particular element in another element you need to do a search from that parent element.

In your case you would do a search on the particular .parts element that is currently being iterated over in your $.each() callback

```<code>$('.parts').each(function(index,element){
  var parent = $(element);
  var ran=Math.floor(Math.random()* 1000000);
  parent.find('.anot-head').attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
  parent.find('.anot-body').attr( "id","s"+ran );
});
</code>```

Title: jquery random element id for every loop

Body:
sorry i'm new in jquery and i need help :-(
  i want to traverse all elements on html page with class parts
then go inside to two children and pass them a random number ( the same for them both)

for every element new random number is passed ( no repeat on page)
children classes are :
anot-head
anot-body
this is a sample code:

    $(document).ready(function() {

$.each($('.parts'), function(){
var ran=Math.floor(Math.random()* 1000000);

$( ".anot-head" ).attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
$( ".anot-body" ).attr( "id","s"+ran );

});
});

Body:
$(".anot-body") does a search of the whole document, if you want to find a particular element in another element you need to do a search from that parent element.

In your case you would do a search on the particular .parts element that is currently being iterated over in your $.each() callback

$('.parts').each(function(index,element){
  var parent = $(element);
  var ran=Math.floor(Math.random()* 1000000);
  parent.find('.anot-head').attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
  parent.find('.anot-body').attr( "id","s"+ran );
});


问:
java.sql.SQLException: Access denied for user 'wineship'@'localhost' (using password: YES)
I've scoured similar questions looking for a solution to my problem since a lot of people are having the same issue as me. However, none of the solutions are helping, and I still have the same error stack.

This is my java code that starts the connection. The stack clearly points to the line that says conn=DriverManager.getConnection(...);:

```<code>package com.wine.plugins.managers.models;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public abstract class DatabaseModel
{
    protected static Connection conn = null;

    private static final String url = "jdbc:mysql://localhost/wineships?useSSL=false";
    private static final String username = "wineship";
    private static final String password = "password";

    public DatabaseModel()
    {
        try {
            if(conn == null)
            {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(url, username, password);
                if (conn != null) {
                    System.out.println("Connected to the database");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (InstantiationException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
}
</code>```

This is the stack:

```<code>[08:24:25 WARN]: java.sql.SQLException: Access denied for user 'wineship'@'localhost' (using password: YES)
[08:24:25 WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2194)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2225)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2024)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
[08:24:25 WARN]:        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
[08:24:25 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[08:24:25 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[08:24:25 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[08:24:25 WARN]:        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[08:24:25 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
[08:24:25 WARN]:        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
[08:24:25 WARN]:        at java.sql.DriverManager.getConnection(DriverManager.java:664)
[08:24:25 WARN]:        at java.sql.DriverManager.getConnection(DriverManager.java:247)
[08:24:25 WARN]:        at com.wine.plugins.managers.models.DatabaseModel.<init>(DatabaseModel.java:21)
[08:24:25 WARN]:        at com.wine.plugins.managers.models.ValidBlocksDatabaseModel.<init>(ValidBlocksDatabaseModel.java:10)
[08:24:25 WARN]:        at com.wine.plugins.managers.BlockValidityManager.initialize(BlockValidityManager.java:16)
[08:24:25 WARN]:        at com.wine.plugins.WineShips.onEnable(WineShips.java:12)
[08:24:25 WARN]:        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:264)
[08:24:25 WARN]:        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:337)
[08:24:25 WARN]:        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:402)
[08:24:25 WARN]:        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugin(CraftServer.java:377)
[08:24:25 WARN]:        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugins(CraftServer.java:327)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.t(MinecraftServer.java:421)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.l(MinecraftServer.java:382)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.a(MinecraftServer.java:337)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:272)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:544)
[08:24:25 WARN]:        at java.lang.Thread.run(Thread.java:748)
</code>```

The MySQL server is running on localhost:3306 on the program Xampp on Linux. The code is for a minecraft server that will request data from the SQL server.

答:
I've been tinkering with phpmyadmin, and I've found that entering in an address, instead of using '%', solved my problem. I also changed "localhost" to 127.0.0.1 @nigel ren

My code is now:

```<code>private static final String url = "jdbc:mysql://127.0.0.1/wineships";
private static final String username = "wineship";
private static final String password = "password";
</code>```

Body:
I've scoured similar questions looking for a solution to my problem since a lot of people are having the same issue as me. However, none of the solutions are helping, and I still have the same error stack.

This is my java code that starts the connection. The stack clearly points to the line that says conn=DriverManager.getConnection(...);:

package com.wine.plugins.managers.models;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public abstract class DatabaseModel
{
    protected static Connection conn = null;

    private static final String url = "jdbc:mysql://localhost/wineships?useSSL=false";
    private static final String username = "wineship";
    private static final String password = "password";

    public DatabaseModel()
    {
        try {
            if(conn == null)
            {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(url, username, password);
                if (conn != null) {
                    System.out.println("Connected to the database");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (InstantiationException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
}

This is the stack:

[08:24:25 WARN]: java.sql.SQLException: Access denied for user 'wineship'@'localhost' (using password: YES)
[08:24:25 WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
[08:24:25 WARN]:        at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2194)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2225)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2024)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
[08:24:25 WARN]:        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
[08:24:25 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[08:24:25 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[08:24:25 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[08:24:25 WARN]:        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[08:24:25 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
[08:24:25 WARN]:        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
[08:24:25 WARN]:        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
[08:24:25 WARN]:        at java.sql.DriverManager.getConnection(DriverManager.java:664)
[08:24:25 WARN]:        at java.sql.DriverManager.getConnection(DriverManager.java:247)
[08:24:25 WARN]:        at com.wine.plugins.managers.models.DatabaseModel.<init>(DatabaseModel.java:21)
[08:24:25 WARN]:        at com.wine.plugins.managers.models.ValidBlocksDatabaseModel.<init>(ValidBlocksDatabaseModel.java:10)
[08:24:25 WARN]:        at com.wine.plugins.managers.BlockValidityManager.initialize(BlockValidityManager.java:16)
[08:24:25 WARN]:        at com.wine.plugins.WineShips.onEnable(WineShips.java:12)
[08:24:25 WARN]:        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:264)
[08:24:25 WARN]:        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:337)
[08:24:25 WARN]:        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:402)
[08:24:25 WARN]:        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugin(CraftServer.java:377)
[08:24:25 WARN]:        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugins(CraftServer.java:327)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.t(MinecraftServer.java:421)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.l(MinecraftServer.java:382)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.a(MinecraftServer.java:337)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:272)
[08:24:25 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:544)
[08:24:25 WARN]:        at java.lang.Thread.run(Thread.java:748)

The MySQL server is running on localhost:3306 on the program Xampp on Linux. The code is for a minecraft server that will request data from the SQL server.

Body:
I've been tinkering with phpmyadmin, and I've found that entering in an address, instead of using '%', solved my problem. I also changed "localhost" to 127.0.0.1 @nigel ren

My code is now:

private static final String url = "jdbc:mysql://127.0.0.1/wineships";
private static final String username = "wineship";
private static final String password = "password";


问:
Warning: preg_replace_callback(): Requires argument 2
I just updated PHP on my server from php 5 to php 7 and I'm getting these warnings:

Warning: preg_replace_callback() [function.preg-replace-callback0]: Requires argument 2, 'chr(\1)', to be a valid callback

Warning: preg_replace_callback() [function.preg-replace-callback0]: Requires argument 2, 'chr(0x\1)', to be a valid callback

Warning: preg_replace_callback() [function.preg-replace-callback0]: Requires argument 2, 'chr(\1)', to be a valid callback

Warning: preg_replace_callback() [function.preg-replace-callback0]: Requires argument 2, 'chr(0x\1)', to be a valid callback

This is the PHP code:

```<code>private function _decode( $source )
{
    $source = html_entity_decode($source, ENT_QUOTES, 'UTF-8');
    $source = preg_replace_callback('/&#(\d+);/me',"chr(\\1)", $source);
    $source = preg_replace_callback('/&#x([a-f0-9]+);/mei',"chr(0x\\1)", $source);

    return $source;
}
</code>```

The Warning is come from:

```<code>$source = preg_replace_callback('/&#x([a-f0-9]+);/mei',"chr(0x\\1)", $source);
</code>```

How i can fix this?

答:
The /e modifier (PREG_REPLACE_EVAL) is no longer supported, as noted in the PHP 7.0 migration guide. You need to use a callable function, not a string that will be evaluated as a function. In your case, replace your string function -- chr(0x\\1) -- with a Closure:

```<code>$source = preg_replace_callback(
    '/&#x([a-f0-9]+);/mi',
    fn($m) => chr(hexdec('0x'.$m[1])),
    $source
);
</code>```

The inline string replacement of \\1 to yield a valid PHP hexadecimal, like 0x21, no longer works that way in the callable: you need a hexdec call to accomplish the same.

See it in action on 3v4l.org.

If you do not yet have PHP 7.4 with short closures, you need to write that as:

```<code>$source = preg_replace_callback(
    '/&#x([a-f0-9]+);/mi',
    function ($m) { return chr(hexdec('0x'.$m[1])); }, // Now a Closure
    $source
);
</code>```

Body:
I just updated PHP on my server from php 5 to php 7 and I'm getting these warnings:

Warning: preg_replace_callback() [function.preg-replace-callback0]: Requires argument 2, 'chr(\1)', to be a valid callback

Warning: preg_replace_callback() [function.preg-replace-callback0]: Requires argument 2, 'chr(0x\1)', to be a valid callback

Warning: preg_replace_callback() [function.preg-replace-callback0]: Requires argument 2, 'chr(\1)', to be a valid callback

Warning: preg_replace_callback() [function.preg-replace-callback0]: Requires argument 2, 'chr(0x\1)', to be a valid callback

This is the PHP code:

private function _decode( $source )
{
    $source = html_entity_decode($source, ENT_QUOTES, 'UTF-8');
    $source = preg_replace_callback('/&#(\d+);/me',"chr(\\1)", $source);
    $source = preg_replace_callback('/&#x([a-f0-9]+);/mei',"chr(0x\\1)", $source);

    return $source;
}

The Warning is come from:

$source = preg_replace_callback('/&#x([a-f0-9]+);/mei',"chr(0x\\1)", $source);

How i can fix this?

Body:
The /e modifier (PREG_REPLACE_EVAL) is no longer supported, as noted in the PHP 7.0 migration guide. You need to use a callable function, not a string that will be evaluated as a function. In your case, replace your string function -- chr(0x\\1) -- with a Closure:

$source = preg_replace_callback(
    '/&#x([a-f0-9]+);/mi',
    fn($m) => chr(hexdec('0x'.$m[1])),
    $source
);

The inline string replacement of \\1 to yield a valid PHP hexadecimal, like 0x21, no longer works that way in the callable: you need a hexdec call to accomplish the same.

See it in action on 3v4l.org.

If you do not yet have PHP 7.4 with short closures, you need to write that as:

$source = preg_replace_callback(
    '/&#x([a-f0-9]+);/mi',
    function ($m) { return chr(hexdec('0x'.$m[1])); }, // Now a Closure
    $source
);

ContentLicense: CC BY-SA 4.0


问:
how to measure execution time in specific part of View
I want to calculate execution time in a specific part of View in MVC asp.net
for example

```<code><p>start time is A</p>

<br />

@for (int i = 0; i < 1000000; i++)
{

        if (@i % 100000 == 0)
        {
         <p>@i</p> <br />
        }

}
 <p>End time is B</p>
<p>execution time is: C</p>
</code>```

how to calculate A, B, C in above code ?

答:
You can do it like this:

```<code>@{
    DateTime StartTime = DateTime.Now;
    System.Diagnostics.StopWatch Watch = new System.Diagnostics.StopWatch();
    @Html.Raw("<p>start time is: " + StartTime.ToString() + "</p>");
    Watch.Start();
    for (int i = 0; i < 1000000; i++)
        {

        if (i % 100000 == 0)
        {
             @Html.Raw("<p>" + i.ToString() + "i</p> <br />");
        }

    }
    Watch.Stop();
    DateTime EndTime = DateTime.Now;
    @Html.Raw("<p>End time is " + EndTime.ToString() + "</p>");
    @Html.Raw("<p>Execution time is: " + Watch.Elapsed.ToString() + "</p>");
}
</code>```

Normally, I would recommend using a StopWatch to track the elapsed time but since you want the start and end times you might as well captured two dates and display the difference to calculate the time span.

Body:
I want to calculate execution time in a specific part of View in MVC asp.net
for example

start time is A

@for (int i = 0; i < 1000000; i++)
{

        if (@i % 100000 == 0)
        {

@i

        }

}

End time is B

execution time is: C

how to calculate A, B, C in above code ?

Body:
You can do it like this:

@{
    DateTime StartTime = DateTime.Now;
    System.Diagnostics.StopWatch Watch = new System.Diagnostics.StopWatch();
    @Html.Raw("<p>start time is: " + StartTime.ToString() + "</p>");
    Watch.Start();
    for (int i = 0; i < 1000000; i++)
        {

        if (i % 100000 == 0)
        {
             @Html.Raw("<p>" + i.ToString() + "i</p> <br />");
        }

    }
    Watch.Stop();
    DateTime EndTime = DateTime.Now;
    @Html.Raw("<p>End time is " + EndTime.ToString() + "</p>");
    @Html.Raw("<p>Execution time is: " + Watch.Elapsed.ToString() + "</p>");
}

Normally, I would recommend using a StopWatch to track the elapsed time but since you want the start and end times you might as well captured two dates and display the difference to calculate the time span.