问:
return all possible values with which.max in R
I have the following dataset

```<code>clust       T2       n
1            a       1
1            b       3
1            c       3
2            d       5
3            a       4
3            b       3
4            b       5
4            c       8
4            t       6
4            e       7
etc..
</code>```

using the following function:

```<code>library(dplyr)
table <- data %>% group_by(clust) %>% summarise(max = max(n), name1 = T2[which.max(n)])
</code>```

I get this output

```<code>clust   max  name1
1        3    b
2        5    d
3        4    a
4        8    c
etc
</code>```

however there are cases where there are two or more T2 values corresponding to max(n). how can I record those value too?

i.e.

```<code>clust   max  name1
1        3    b,c
2        5    d
3        4    a
4        8    c
etc
</code>```

or

```<code>clust   max  name1
1        3    b
1        3    c
2        5    d
3        4    a
4        8    c
etc
</code>```

答:
We can do a == instead of which.max (that returns only the first index of max value) and paste together with toString

```<code>library(dplyr)
library(tidyr)
data %>%
    group_by(clust) %>%
    summarise(max = max(n), name1 = toString(T2[n == max(n)]))
# A tibble: 4 x 3
#  clust   max name1
#  <int> <int> <chr>
#1     1     3 b, c
#2     2     5 d
#3     3     4 a
#4     4     8 c
</code>```

and this can be expanded with separate_rows in the next step

```<code>data %>%
    group_by(clust) %>%
    summarise(max = max(n), name1 = toString(T2[n == max(n)])) %>%
    separate_rows(name1, sep=",\\s+")
# A tibble: 5 x 3
#  clust   max name1
#  <int> <int> <chr>
#1     1     3 b
#2     1     3 c
#3     2     5 d
#4     3     4 a
#5     4     8 c
</code>```

Or have a list column and then unnest

```<code>data %>%
    group_by(clust) %>%
    summarise(max = max(n), name1 = list(T2[n == max(n)]))  %>%
    unnest(c(name1))
# A tibble: 5 x 3
#  clust   max name1
#  <int> <int> <chr>
#1     1     3 b
#2     1     3 c
#3     2     5 d
#4     3     4 a
#5     4     8 c
</code>```

data

```<code>data <- structure(list(clust = c(1L, 1L, 1L, 2L, 3L, 3L, 4L, 4L, 4L,
4L), T2 = c("a", "b", "c", "d", "a", "b", "b", "c", "t", "e"),
    n = c(1L, 3L, 3L, 5L, 4L, 3L, 5L, 8L, 6L, 7L)),
    class = "data.frame", row.names = c(NA,
-10L))
</code>```

Body:
I have the following dataset

clust       T2       n
1            a       1
1            b       3
1            c       3
2            d       5
3            a       4
3            b       3
4            b       5
4            c       8
4            t       6
4            e       7
etc..

using the following function:

library(dplyr)
table <- data %>% group_by(clust) %>% summarise(max = max(n), name1 = T2[which.max(n)])

I get this output

clust   max  name1
1        3    b
2        5    d
3        4    a
4        8    c
etc

however there are cases where there are two or more T2 values corresponding to max(n). how can I record those value too?

i.e.

clust   max  name1
1        3    b,c
2        5    d
3        4    a
4        8    c
etc

or

clust   max  name1
1        3    b
1        3    c
2        5    d
3        4    a
4        8    c
etc

Body:
We can do a == instead of which.max (that returns only the first index of max value) and paste together with toString

library(dplyr)
library(tidyr)
data %>%
    group_by(clust) %>%
    summarise(max = max(n), name1 = toString(T2[n == max(n)]))
# A tibble: 4 x 3
#  clust   max name1
#  <int> <int> <chr>
#1     1     3 b, c
#2     2     5 d
#3     3     4 a
#4     4     8 c

and this can be expanded with separate_rows in the next step

data %>%
    group_by(clust) %>%
    summarise(max = max(n), name1 = toString(T2[n == max(n)])) %>%
    separate_rows(name1, sep=",\\s+")
# A tibble: 5 x 3
#  clust   max name1
#  <int> <int> <chr>
#1     1     3 b
#2     1     3 c
#3     2     5 d
#4     3     4 a
#5     4     8 c

Or have a list column and then unnest

data %>%
    group_by(clust) %>%
    summarise(max = max(n), name1 = list(T2[n == max(n)]))  %>%
    unnest(c(name1))
# A tibble: 5 x 3
#  clust   max name1
#  <int> <int> <chr>
#1     1     3 b
#2     1     3 c
#3     2     5 d
#4     3     4 a
#5     4     8 c

data

data <- structure(list(clust = c(1L, 1L, 1L, 2L, 3L, 3L, 4L, 4L, 4L,
4L), T2 = c("a", "b", "c", "d", "a", "b", "b", "c", "t", "e"),
    n = c(1L, 3L, 3L, 5L, 4L, 3L, 5L, 8L, 6L, 7L)),
    class = "data.frame", row.names = c(NA,
-10L))


来源: stackexchange

问:
Replacing one value in a time series when it appears more than once
I am trying to replace a value in a python Series, the clue here is that I want to replace it only once, for instance:

```<code>S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])
</code>```

The number 2 is repeated 3 times and I want to replace only the "second" 2 for 4,
I don't want to replace all the '2' numbers within the series.

Is there any way to do it?

Thank you in advance

答:
You can try this way:

```<code>S.loc[((S == 2).cumsum() == 2).idxmax()] = 4
print(S)
</code>```

Output:

```<code>0    0
1    1
2    2
3    3
4    4
5    5
6    2
7    6
dtype: int64
</code>```

Details, find all the places in the Series where equal to 2, then use cumsum to count those 2's, now, select the first occurrence of the count of 2 and use .loc to set the value.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to replace a value in a python Series, the clue here is that I want to replace it only once, for instance:

S = pd.Series([0, 1, 2, 3, 2, 5, 2, 6])

The number 2 is repeated 3 times and I want to replace only the "second" 2 for 4,
I don't want to replace all the '2' numbers within the series.

Is there any way to do it?

Thank you in advance

Body:
You can try this way:

S.loc[((S == 2).cumsum() == 2).idxmax()] = 4
print(S)

Output:

0    0
1    1
2    2
3    3
4    4
5    5
6    2
7    6
dtype: int64

Details, find all the places in the Series where equal to 2, then use cumsum to count those 2's, now, select the first occurrence of the count of 2 and use .loc to set the value.


问:
How to get value input form from FormGroup
Good day, guys I'd like to find the solution to solve my problem. I have a FormGroup like this :

```<code>  profileForm  = new FormGroup({
    username   : new FormControl(),
    firstname  : new FormControl(),
    lastname   : new FormControl(),
    email      : new FormControl(),
    password   : new FormControl(),
  });
</code>```

And I'd like to get the value by using :

```<code>const user = {
  firstname : this.profileForm.get('firstname').value,
  lastname  : this.profileForm.get('lastname').value,
  username  : this.profileForm.get('username').value,
  email     : this.profileForm.get('email').value,
  password  : this.profileForm.get('password').value
}
console.log(user)
</code>```

But I got null value for each input form. But the value exists in the HTML form input :

```<code><input name="username" matInput placeholder="Username" formControlName="username" [readonly]="true" value="{{details?.data.username}}" >
</code>```

Help me to fix this, thank you.

答:
I think value="{{details?.data.username}}" is not binding value back to you. It just prints the value in dom.

I assume you getting data details?.data.username in ngOnInit() ( or may be somewhere else) from there you can bind to your form like this

```<code>this.profileForm.get('firstname').setValue(details?.data.username)
</code>```

and remove this value="{{details?.data.username}}" from html.

Body:
Good day, guys I'd like to find the solution to solve my problem. I have a FormGroup like this :

  profileForm  = new FormGroup({
    username   : new FormControl(),
    firstname  : new FormControl(),
    lastname   : new FormControl(),
    email      : new FormControl(),
    password   : new FormControl(),
  });

And I'd like to get the value by using :

const user = {
  firstname : this.profileForm.get('firstname').value,
  lastname  : this.profileForm.get('lastname').value,
  username  : this.profileForm.get('username').value,
  email     : this.profileForm.get('email').value,
  password  : this.profileForm.get('password').value
}
console.log(user)

But I got null value for each input form. But the value exists in the HTML form input :

<input name="username" matInput placeholder="Username" formControlName="username" [readonly]="true" value="{{details?.data.username}}" >

Help me to fix this, thank you.

Body:
I think value="{{details?.data.username}}" is not binding value back to you. It just prints the value in dom.

I assume you getting data details?.data.username in ngOnInit() ( or may be somewhere else) from there you can bind to your form like this

this.profileForm.get('firstname').setValue(details?.data.username)

and remove this value="{{details?.data.username}}" from html.


问:
Angular Firebase Routeguard Authentication
I am actually learning Angular and firebase, I want to add a route guard to users dashboard so that only logged in users can view the page. The Authentication works fine but I am having issues restricting none logged in users to access users dashboard  This is my code below.

Authservice.service.ts

```<code>@Injectable({
      providedIn: 'root'
    })
    export class AuthServiceService {

      newUser: any;
      // passing Error message
      private eventAuthError = new BehaviorSubject<string>('');
      eventError$ = this.eventAuthError.asObservable();
      showSuccessCreated: boolean;

      constructor( private authz: AngularFireAuth, private db: AngularFirestore, private route:Router)
      { }
      // geting user details
      getUserState() {
       return this.authz.authState;
      }

      // LoggIn Users
      login(email: string , password: string ) {
        this.authz.auth.signInWithEmailAndPassword(email, password)
        .catch( error => {
          this.eventAuthError.next(error);
      }).then(userCredential => {
        if (userCredential) {
          this.route.navigate(['/dashboard']);
        }
      });
      }
</code>```

This is the Authguard service,  I try to reference the login method from my authservice.service.ts, but it still redirects to users' dashboard despite I am not Logged In.

authguard.service.ts

```<code>export class AuthguardService implements CanActivate {
  constructor(private authservice: AuthServiceService, private route: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    let isAuthenicated = !!this.authservice.login;
    if(isAuthenicated ){
     return true;
    }
    console.log('Access denied');
    this.route.navigate(['/login']);
    return false;
  }
}
</code>```

route.module.ts

```<code>const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate:[AuthguardService],
     children: [
      {path: '', redirectTo: 'employees', pathMatch: 'full'},
      {path: 'employees', component: EmployeelistComponent, resolve: {employeeList: ResolverGuardService}},
      {path: 'detail/:id', component: EmployeeDetailComponent,  canActivate: [CanActivateGuardService],

      { path: 'notfound', component: PageNotFoundComponent},

     ]
    },

];
</code>```

答:
I realized that you are calling a method called login which handles a promise into AuthGuard class.

You have to handle your login method properly in order to get the correct response and save it into isAuthenicated variable.

You maybe can do something similar to the code below.

AuthService.ts

```<code>login(): Promise<boolean> {
  // create new promise and handle our login flow
  return new Promise((resolve, reject) => {
    // get email and password somehow
    const = email = this.getEmail();
    const = password = this.getPassword();
    // call sign in with email and password
    return this.authz.auth.signInWithEmailAndPassword(email, password)
     .catch( error => {
       this.eventAuthError.next(error);
       // reject our promise on error
       reject(false);
      })
      .then(userCredential => {
       if (userCredential) {
         // resolve our login promise
         resolve(true);
       } else {
         // reject our promise on userCredential falsy value
         reject(false);
       }
     });
  });
}
</code>```

AuthGuard.ts

```<code> export class AuthguardService implements CanActivate {
      constructor(private authservice: AuthServiceService, private route: Router) { }

      async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // handling our promise properly with asnyc/await
        const isAuthenicated = await this.authservice.login();
        if(isAuthenicated ){
          // here we allow enter the page dashboard or any other
          return true;
        }
        console.log('Access denied');
        this.route.navigate(['/login']);
        return false;
      }
    }
</code>```

Body:
I am actually learning Angular and firebase, I want to add a route guard to users dashboard so that only logged in users can view the page. The Authentication works fine but I am having issues restricting none logged in users to access users dashboard  This is my code below.

Authservice.service.ts

@Injectable({
      providedIn: 'root'
    })
    export class AuthServiceService {

      newUser: any;
      // passing Error message
      private eventAuthError = new BehaviorSubject<string>('');
      eventError$ = this.eventAuthError.asObservable();
      showSuccessCreated: boolean;

      constructor( private authz: AngularFireAuth, private db: AngularFirestore, private route:Router)
      { }
      // geting user details
      getUserState() {
       return this.authz.authState;
      }

      // LoggIn Users
      login(email: string , password: string ) {
        this.authz.auth.signInWithEmailAndPassword(email, password)
        .catch( error => {
          this.eventAuthError.next(error);
      }).then(userCredential => {
        if (userCredential) {
          this.route.navigate(['/dashboard']);
        }
      });
      }

This is the Authguard service,  I try to reference the login method from my authservice.service.ts, but it still redirects to users' dashboard despite I am not Logged In.

authguard.service.ts

export class AuthguardService implements CanActivate {
  constructor(private authservice: AuthServiceService, private route: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    let isAuthenicated = !!this.authservice.login;
    if(isAuthenicated ){
     return true;
    }
    console.log('Access denied');
    this.route.navigate(['/login']);
    return false;
  }
}

route.module.ts

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate:[AuthguardService],
     children: [
      {path: '', redirectTo: 'employees', pathMatch: 'full'},
      {path: 'employees', component: EmployeelistComponent, resolve: {employeeList: ResolverGuardService}},
      {path: 'detail/:id', component: EmployeeDetailComponent,  canActivate: [CanActivateGuardService],

      { path: 'notfound', component: PageNotFoundComponent},

     ]
    },

];

Body:
I realized that you are calling a method called login which handles a promise into AuthGuard class.

You have to handle your login method properly in order to get the correct response and save it into isAuthenicated variable.

You maybe can do something similar to the code below.

AuthService.ts

login(): Promise<boolean> {
  // create new promise and handle our login flow
  return new Promise((resolve, reject) => {
    // get email and password somehow
    const = email = this.getEmail();
    const = password = this.getPassword();
    // call sign in with email and password
    return this.authz.auth.signInWithEmailAndPassword(email, password)
     .catch( error => {
       this.eventAuthError.next(error);
       // reject our promise on error
       reject(false);
      })
      .then(userCredential => {
       if (userCredential) {
         // resolve our login promise
         resolve(true);
       } else {
         // reject our promise on userCredential falsy value
         reject(false);
       }
     });
  });
}

AuthGuard.ts

 export class AuthguardService implements CanActivate {
      constructor(private authservice: AuthServiceService, private route: Router) { }

      async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // handling our promise properly with asnyc/await
        const isAuthenicated = await this.authservice.login();
        if(isAuthenicated ){
          // here we allow enter the page dashboard or any other
          return true;
        }
        console.log('Access denied');
        this.route.navigate(['/login']);
        return false;
      }
    }


问:
What is inline-view that can be used with LATERAL in Snowflake (not subquery, not table function)?
The Snowflake documentation for Lateral Join mention that in

```<code>SELECT ... FROM <left_hand_table_expression>, LATERAL ( <in_line_view> )
</code>```

The in_line_view could be:

An in-line view (a view defined within the statement, and valid only for the duration of the statement

A subquery select * from d, lateral (select * from e where e.id = d.id)

A table function (either a built-in function such as FLATTEN or a user-defined table function(UDFT)) select * from e, lateral flatten(input => e.x)

I already have used subqueries and table functions in the LATERAL(...) but I wonder what is the the other kind of <in_line_view> (and how it is different from a subquery).

答:
Their language here is a little confusing for sure. Really just remove the 1. bullet from that list and it will make more sense. From what I can tell, the only difference between an "inline view" and a "subquery" is that an inline view is a subquery that is in a specific part of the larger query. In this case, in the lateral clause. They even specify in of their examples at the bottom of that page that the FLATTEN is an inline view.

This example shows how a lateral join can use the in-line view returned by FLATTEN:

```<code>select * from table1, lateral flatten(...);
</code>```

To hopefully clarify further, a subquery in the FROM clause, for example, has to be run just once and then joined, selected, etc, and so it is treated by the optimizer in a similar way to a view. When you do this it can be referred to as an inline view. However a subquery within a SELECT clause has to be run for each record and so isn't treated by the execution plan in the same way.

A rule of thumb is if the query parser forces you to give a subquery an alias, it is probably an "inline view".

Body:
The Snowflake documentation for Lateral Join mention that in

SELECT ... FROM <left_hand_table_expression>, LATERAL ( <in_line_view> )

The in_line_view could be:

An in-line view (a view defined within the statement, and valid only for the duration of the statement

A subquery select * from d, lateral (select * from e where e.id = d.id)

A table function (either a built-in function such as FLATTEN or a user-defined table function(UDFT)) select * from e, lateral flatten(input => e.x)

I already have used subqueries and table functions in the LATERAL(...) but I wonder what is the the other kind of <in_line_view> (and how it is different from a subquery).

Body:
Their language here is a little confusing for sure. Really just remove the 1. bullet from that list and it will make more sense. From what I can tell, the only difference between an "inline view" and a "subquery" is that an inline view is a subquery that is in a specific part of the larger query. In this case, in the lateral clause. They even specify in of their examples at the bottom of that page that the FLATTEN is an inline view.

This example shows how a lateral join can use the in-line view returned by FLATTEN:

select * from table1, lateral flatten(...);

To hopefully clarify further, a subquery in the FROM clause, for example, has to be run just once and then joined, selected, etc, and so it is treated by the optimizer in a similar way to a view. When you do this it can be referred to as an inline view. However a subquery within a SELECT clause has to be run for each record and so isn't treated by the execution plan in the same way.

A rule of thumb is if the query parser forces you to give a subquery an alias, it is probably an "inline view".


问:
drag & rotate individual items
i have spent an entire day trying to figure this out but, to no avail.  i have several draggable pieces of texts on a page.  these pieces of texts are also supposed to have the ability to be rotated.  well, the draggable part is fine.  the rotate is even working.  however, it is not working for individual items - whenever i rotate 1 item, anything else w/the rotate code in it, rotates as well. </p>

答:
The problem is that you are applying style="-webkit-transform: rotate(0deg);" to the class

```<code>cc-element ui-draggable cc-active'
</code>```

That's why both element rotate. So apply style to the id rather than apply to the class.

You can have a look here

ContentLicense: CC BY-SA 3.0

Title: drag & rotate individual items

Body:
The problem is that you are applying style="-webkit-transform: rotate(0deg);" to the class

cc-element ui-draggable cc-active'

That's why both element rotate. So apply style to the id rather than apply to the class.

You can have a look here


问:
module descriptor file allowed import statements Why?
please anyone explain me module descriptor file allowed import Why?

what is the used of import statement in module descriptor file.

```<code>import java.util.*;

module superman {
}
</code>```

答:
One use would be if you were using the provides directive:

```<code>module superman {
    provides com.github.me.superhero.Superhero with com.github.me.superhero.Batman;
    provides com.github.me.superhero.Superhero with com.github.me.superhero.IronMan;
}
</code>```

Using an import would look like:

```<code>import com.github.me.superhero.*;

module superman {
    provides Superhero with Batman;
    provides Superhero with IronMan;
}
</code>```

Body:
please anyone explain me module descriptor file allowed import Why?

what is the used of import statement in module descriptor file.

import java.util.*;

module superman {
}

Body:
One use would be if you were using the provides directive:

module superman {
    provides com.github.me.superhero.Superhero with com.github.me.superhero.Batman;
    provides com.github.me.superhero.Superhero with com.github.me.superhero.IronMan;
}

Using an import would look like:

import com.github.me.superhero.*;

module superman {
    provides Superhero with Batman;
    provides Superhero with IronMan;
}


问:
AWS lambda never completes but doesn't appear to timeout either
I'm attempting to create a simple application. A user emails an attachment to a special inbox, AWS SES gets the email and stores it in S3, a lambda function is triggered and the lambda finds the email in S3, parses out the attachment (in this case a jpg) and then stores it in a different S3 bucket. Finally, the application creates a new row in an Airtable with the image as an attachment.

When I invoked this function locally using serverless, everything works fine. The email with the image are already stored in an S3 bucket so I've created a mock which passes the key explicitly to my lambda. However, when I deploy the application and send a test email, the following happens:

Email is stored in S3 bucket 'to-airtable-temp'

Lambda function is called

Before the email can be found and the attachment striped off and stored in a seperate S3 bucket the function just stops. No error message or timeout. It just stops. Cloudwatch logs look like the following:

```<code>START RequestId: 6a0364ae-0879-4ee1-9dcd-c8747de1a650 Version: $LATEST
2020-02-17T07:39:55.465Z    6a0364ae-0879-4ee1-9dcd-c8747de1a650    INFO    {
  s3SchemaVersion: '1.0',
  configurationId: 'emailtoairtable-dev-parse-224c3963d3a3f9c35018ae93a9fffea4',
  bucket: {
    name: 'to-airtable-temp',
    ownerIdentity: { principalId: 'AI5RGHFD5AFHE' },
    arn: 'arn:aws:s3:::to-airtable-temp'
  },
  object: {
    key: 'mtvuuiokqj55l2a8b0qser7tn9dhfignoh9c1vg1',
    size: 3804230,
    eTag: 'c821fb0a2a9c3b060e20e7d177f8b972',
    sequencer: '005E4A434810147365'
  }
}
2020-02-17T07:39:55.465Z    6a0364ae-0879-4ee1-9dcd-c8747de1a650    INFO    key mtvuuiokqj55l2a8b0qser7tn9dhfignoh9c1vg1
2020-02-17T07:39:55.465Z    6a0364ae-0879-4ee1-9dcd-c8747de1a650    INFO    Key pushed to list.  mtvuuiokqj55l2a8b0qser7tn9dhfignoh9c1vg1
END RequestId: 6a0364ae-0879-4ee1-9dcd-c8747de1a650
REPORT RequestId: 6a0364ae-0879-4ee1-9dcd-c8747de1a650  Duration: 1113.17 ms    Billed Duration: 1200 ms    Memory Size: 1024 MB    Max Memory Used: 114 MB Init Duration: 119.56 ms
</code>```

Here is my handler.js file:

```<code>'use strict';

module.exports.parse = async event => {
  try {
    const aws = require('aws-sdk');
    const s3 = new aws.S3();
    const simpleParser = require('mailparser').simpleParser;
    const Airtable = require('airtable');
    const dateformat = require('dateformat');
    var base = new Airtable({ apiKey: process.env.airtableApiKey}).base(process.env.airtableBaseId);
    var data = [];
    var keys = [];

    event["Records"].forEach(async record => {
      console.log(record["s3"]);
      console.log('key', record["s3"]["object"]["key"]);
      keys.push(record["s3"]["object"]["key"]);
      console.log('Key pushed to list. ', record["s3"]["object"]["key"]);  // <-- this is the last line that I am sure processes because I see it in the CloudWatch logs.
      var temp_data = await s3.getObject(
      {
        Bucket: 'to-airtable-temp',
        Key: record["s3"]["object"]["key"]
      }).promise();
      console.log('temp_data', temp_data);
      data.push(temp_data);
    });

    setTimeout( async function() {
      // console.log('data', data[0].Body.toString());
      let parsed = await simpleParser(data[0].Body.toString());
      console.log(parsed);
      // save the file to a public S3 bucket so it can be uploaded to airtable
      parsed["attachments"].forEach(function(attachment) {
        let now = new Date();
        s3.upload({
          Bucket: 'to-airtable-images',
          Key: keys[0] + dateformat(now, "yyyy-mm-dd") + '.jpg',
          Body: attachment.content,
          ContentType: "image/jpeg"
        },
        function(error, data) {
          if (error) {
            throw error;
          }
          console.log('File uploaded successfully. ' +data.Location);
          // Now upload to airtable
          base('Input').create([
            {
              "fields": {"Attachments": [
                {
                  "url": data.Location
                }
              ]}
            }
          ], function(err, records) {
            if (err) {
              console.error(err);
              return;
            }
            records.forEach(function (record) {
              console.log(record.getId());
            });
          });
        });
      });

      return {
        statusCode: 200,
        body: JSON.stringify(
          {
            message: 'Go Serverless v1.0! Your function executed successfully!',
            input: event,
            data: JSON.stringify(data),
          },
          null,
          2
        ),
      };
    }, 500);  // I've tried increasing this time but it still hangs.
  } catch (error) {
    console.error(error);
  }
};
</code>```

答:
You shouldn't use async/await with the forEach function. Using async/await with a forEach loop. Instead, use the more modern for of syntax:

```<code>for (let record of event["Records"]) {
   // you can include await calls in this block
}
</code>```

Body:
I'm attempting to create a simple application. A user emails an attachment to a special inbox, AWS SES gets the email and stores it in S3, a lambda function is triggered and the lambda finds the email in S3, parses out the attachment (in this case a jpg) and then stores it in a different S3 bucket. Finally, the application creates a new row in an Airtable with the image as an attachment.

When I invoked this function locally using serverless, everything works fine. The email with the image are already stored in an S3 bucket so I've created a mock which passes the key explicitly to my lambda. However, when I deploy the application and send a test email, the following happens:

Email is stored in S3 bucket 'to-airtable-temp'

Lambda function is called

Before the email can be found and the attachment striped off and stored in a seperate S3 bucket the function just stops. No error message or timeout. It just stops. Cloudwatch logs look like the following:

START RequestId: 6a0364ae-0879-4ee1-9dcd-c8747de1a650 Version: $LATEST
2020-02-17T07:39:55.465Z    6a0364ae-0879-4ee1-9dcd-c8747de1a650    INFO    {
  s3SchemaVersion: '1.0',
  configurationId: 'emailtoairtable-dev-parse-224c3963d3a3f9c35018ae93a9fffea4',
  bucket: {
    name: 'to-airtable-temp',
    ownerIdentity: { principalId: 'AI5RGHFD5AFHE' },
    arn: 'arn:aws:s3:::to-airtable-temp'
  },
  object: {
    key: 'mtvuuiokqj55l2a8b0qser7tn9dhfignoh9c1vg1',
    size: 3804230,
    eTag: 'c821fb0a2a9c3b060e20e7d177f8b972',
    sequencer: '005E4A434810147365'
  }
}
2020-02-17T07:39:55.465Z    6a0364ae-0879-4ee1-9dcd-c8747de1a650    INFO    key mtvuuiokqj55l2a8b0qser7tn9dhfignoh9c1vg1
2020-02-17T07:39:55.465Z    6a0364ae-0879-4ee1-9dcd-c8747de1a650    INFO    Key pushed to list.  mtvuuiokqj55l2a8b0qser7tn9dhfignoh9c1vg1
END RequestId: 6a0364ae-0879-4ee1-9dcd-c8747de1a650
REPORT RequestId: 6a0364ae-0879-4ee1-9dcd-c8747de1a650  Duration: 1113.17 ms    Billed Duration: 1200 ms    Memory Size: 1024 MB    Max Memory Used: 114 MB Init Duration: 119.56 ms

Here is my handler.js file:

'use strict';

module.exports.parse = async event => {
  try {
    const aws = require('aws-sdk');
    const s3 = new aws.S3();
    const simpleParser = require('mailparser').simpleParser;
    const Airtable = require('airtable');
    const dateformat = require('dateformat');
    var base = new Airtable({ apiKey: process.env.airtableApiKey}).base(process.env.airtableBaseId);
    var data = [];
    var keys = [];

    event["Records"].forEach(async record => {
      console.log(record["s3"]);
      console.log('key', record["s3"]["object"]["key"]);
      keys.push(record["s3"]["object"]["key"]);
      console.log('Key pushed to list. ', record["s3"]["object"]["key"]);  // <-- this is the last line that I am sure processes because I see it in the CloudWatch logs.
      var temp_data = await s3.getObject(
      {
        Bucket: 'to-airtable-temp',
        Key: record["s3"]["object"]["key"]
      }).promise();
      console.log('temp_data', temp_data);
      data.push(temp_data);
    });

    setTimeout( async function() {
      // console.log('data', data[0].Body.toString());
      let parsed = await simpleParser(data[0].Body.toString());
      console.log(parsed);
      // save the file to a public S3 bucket so it can be uploaded to airtable
      parsed["attachments"].forEach(function(attachment) {
        let now = new Date();
        s3.upload({
          Bucket: 'to-airtable-images',
          Key: keys[0] + dateformat(now, "yyyy-mm-dd") + '.jpg',
          Body: attachment.content,
          ContentType: "image/jpeg"
        },
        function(error, data) {
          if (error) {
            throw error;
          }
          console.log('File uploaded successfully. ' +data.Location);
          // Now upload to airtable
          base('Input').create([
            {
              "fields": {"Attachments": [
                {
                  "url": data.Location
                }
              ]}
            }
          ], function(err, records) {
            if (err) {
              console.error(err);
              return;
            }
            records.forEach(function (record) {
              console.log(record.getId());
            });
          });
        });
      });

      return {
        statusCode: 200,
        body: JSON.stringify(
          {
            message: 'Go Serverless v1.0! Your function executed successfully!',
            input: event,
            data: JSON.stringify(data),
          },
          null,
          2
        ),
      };
    }, 500);  // I've tried increasing this time but it still hangs.
  } catch (error) {
    console.error(error);
  }
};

Body:
You shouldn't use async/await with the forEach function. Using async/await with a forEach loop. Instead, use the more modern for of syntax:

for (let record of event["Records"]) {
   // you can include await calls in this block
}


问:
Laravel: conditional validation rules
In my laravel application I need to apply the validation rules on conditional bases. For example: In the Store method the password field is required and min chars: 6. But, in Update method password field is not required, however, if the user enters the password then it must be greater than 6 chars.

SomeController.php

```<code>private function validations($customRules = [])
{
    # variables
    $rules = [
        'contact_person' => 'required|min:2',
        'mobile_number'  => 'required|numeric',
        'pword'          => 'required|min:6',
        'email'          => 'required|email',
        'address'        => 'required',
        'status'         => 'required',
    ];
    $messages = [
        'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
        'contact_person.min'      => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',

        'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
        'mobile_number.numeric'  => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',

        'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
        'email.email'    => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',

        'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
        'pword.min'      => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',

        'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
    ];

    if(!empty($customRules))
        $rules = \array_merge($rules, $customRules);

    # returning
    return request()->validate($rules, $messages);
}
</code>```

After modifying the rules, based on the update method requirement, the pword field is validated for min chars. Which should not happen as the field was left empty.

Currently I am forced to do this.

```<code>public function update()
{
    ...

    # validating submitted data
    if(!empty(request()->pword))
        $this->validations([ 'pword' => 'min:6' ]);
    else
        $this->validations([ 'pword' => '' ]);

    ....
}
</code>```

答:
You can use nullabe instead required, Blank value converted as null if you are using eloquent, because of below middleware

```<code>    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
</code>```

So your method would be like

```<code>private function validations($request,$update = false){
    $rules = [
        'contact_person' => 'required|min:2',
        'mobile_number'  => 'required|numeric',
        'pword'          => 'nullable|min:6',
        'email'          => 'required|email',
        'address'        => 'required',
        'status'         => 'required',
    ];

}
</code>```

Title: Laravel: conditional validation rules

Body:
In my laravel application I need to apply the validation rules on conditional bases. For example: In the Store method the password field is required and min chars: 6. But, in Update method password field is not required, however, if the user enters the password then it must be greater than 6 chars.

SomeController.php

private function validations($customRules = [])
{
    # variables
    $rules = [
        'contact_person' => 'required|min:2',
        'mobile_number'  => 'required|numeric',
        'pword'          => 'required|min:6',
        'email'          => 'required|email',
        'address'        => 'required',
        'status'         => 'required',
    ];
    $messages = [
        'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
        'contact_person.min'      => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',

        'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
        'mobile_number.numeric'  => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',

        'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
        'email.email'    => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',

        'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
        'pword.min'      => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',

        'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
    ];

    if(!empty($customRules))
        $rules = \array_merge($rules, $customRules);

    # returning
    return request()->validate($rules, $messages);
}

After modifying the rules, based on the update method requirement, the pword field is validated for min chars. Which should not happen as the field was left empty.

Currently I am forced to do this.

public function update()
{
    ...

    # validating submitted data
    if(!empty(request()->pword))
        $this->validations([ 'pword' => 'min:6' ]);
    else
        $this->validations([ 'pword' => '' ]);

    ....
}

Body:
You can use nullabe instead required, Blank value converted as null if you are using eloquent, because of below middleware

    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

So your method would be like

private function validations($request,$update = false){
    $rules = [
        'contact_person' => 'required|min:2',
        'mobile_number'  => 'required|numeric',
        'pword'          => 'nullable|min:6',
        'email'          => 'required|email',
        'address'        => 'required',
        'status'         => 'required',
    ];

}


问:
How to make a function find the address of the function pointer it's been called by?
I want to implement the toString() method for a pure C struct. That can, of course, be done using a function pointer, but the catch is that I don't wan't to pass the object's location to the function and I want the function to figure it out by itself based on the function pointer in said struct. So, if we have a struct like this:

```<code>typedef struct some
{
    int32_t a;
    const char * str;
    void* (*toString)();
}Node;
</code>```

after instantiating it, I want its contents printed the same way you do it in Java, like this:

```<code>Node a;
a.toString();
</code>```

Except our toString() will print the stringized object itself and won't actually return a string.

I took my time and this is what I came up with:

```<code>#include <stdio.h>
#include <stdint.h>

typedef struct some
{
    int32_t a;
    const char * str;
    void* (*toString)();
}Node;

void f()
{
  Node *beginnning = __builtin_frame_address(1) - sizeof(Node);
  const char ** temp = (const char *) beginnning + 8;
  printf("{%d, %s}\n", *((int*)beginnning), *temp);
}

int main()
{
    Node a, b;
    a.a = 67, a.str = "alpine", a.toString = f;
    a.toString();
    b.a = 25, b.str = "hello world", b.toString = f;
    b.toString();
}
</code>```

The fundamental idea is to use this __builtin_frame_address() function, which in my case conveniently returns the last byte of my object. After getting it, obtaining the variables is relatively straight forward using pointer arithmetic and the fact that we actually know how our variables are placed inside the struct.

The problem with this solution is that it only works with only one object. First one is being printed correctly, but for the second one, we don't get the right address. So, the expected output is:

```<code>{67, alpine}
{25, hello world}
</code>```

but the real output is actually:

```<code>{67, alpine}
{67, alpine}
</code>```

Is there a way to forcefully "end" the frame, or reset in some way so that a next function call returns what we need? I believe if there were a way to do that, this problem can be solved. However, I couldn't really find anything like that in __builtin_frame_address() documentation.

The function I used from what I gathered is a part of the gcc compiler on linux. I wouldn't exactly look for it on Windows. Therefore, to save time, you might want to test it here.

答:
If you really want to do that, you will have to use wrappers. In fact it is what were the first C++ compilers: simple pre-processors that (among other things) replaced constructs like obj.method(arg, ...) with objclass_method(obj, arg, ...).

I am far from a macro specialist, but I would not be surprised if you could achieve it with a macro for trivial use cases. For more complex ones, you will have to build a true pre-processor, but the parser from Clang could be a good starting point.

That being said, I strongly advise you against that unless you have a very serious reason. Debugging will be a nightmare, because you will have to debug against the pre-processed code(*). So if you want to use C stick to C syntax and explicitely pass the object, else use an object language like C++.

In a previous life I used an Oracle SQL pre-compiler, and debugging programs was terrible...

Body:
I want to implement the toString() method for a pure C struct. That can, of course, be done using a function pointer, but the catch is that I don't wan't to pass the object's location to the function and I want the function to figure it out by itself based on the function pointer in said struct. So, if we have a struct like this:

typedef struct some
{
    int32_t a;
    const char * str;
    void* (*toString)();
}Node;

after instantiating it, I want its contents printed the same way you do it in Java, like this:

Node a;
a.toString();

Except our toString() will print the stringized object itself and won't actually return a string.

I took my time and this is what I came up with:

#include <stdio.h>
#include <stdint.h>

typedef struct some
{
    int32_t a;
    const char * str;
    void* (*toString)();
}Node;

void f()
{
  Node *beginnning = __builtin_frame_address(1) - sizeof(Node);
  const char ** temp = (const char *) beginnning + 8;
  printf("{%d, %s}\n", *((int*)beginnning), *temp);
}

int main()
{
    Node a, b;
    a.a = 67, a.str = "alpine", a.toString = f;
    a.toString();
    b.a = 25, b.str = "hello world", b.toString = f;
    b.toString();
}

The fundamental idea is to use this __builtin_frame_address() function, which in my case conveniently returns the last byte of my object. After getting it, obtaining the variables is relatively straight forward using pointer arithmetic and the fact that we actually know how our variables are placed inside the struct.

The problem with this solution is that it only works with only one object. First one is being printed correctly, but for the second one, we don't get the right address. So, the expected output is:

{67, alpine}
{25, hello world}

but the real output is actually:

{67, alpine}
{67, alpine}

Is there a way to forcefully "end" the frame, or reset in some way so that a next function call returns what we need? I believe if there were a way to do that, this problem can be solved. However, I couldn't really find anything like that in __builtin_frame_address() documentation.

The function I used from what I gathered is a part of the gcc compiler on linux. I wouldn't exactly look for it on Windows. Therefore, to save time, you might want to test it here.


问:
Calling HTML element in a CSS sheet
Hi I need to style some HTML elements in a separate CSS sheet. Below are the four options that need to be styled- how do I call them on my external style sheet?</p>

```<code><label>Select list</label>
            <select id = "myList">
               <option value = "1">Drama</option>
               <option value = "2">Thriller</option>
               <option value = "3">Comedy</option>
           <option value ="4">Horror</option>
             </select>
</code>```

答:
You can create external CSS file (mystyle.css) and add it in head section of your web page. In this you mystyle.css you can write css properties of HTML elements.

Below is the link you need to add in head file (update path of css file in href) :

```<code><link rel="stylesheet" type="text/css" href="mystyle.css">
</code>```

Title: Calling HTML element in a CSS sheet

Body:
Hi I need to style some HTML elements in a separate CSS sheet. Below are the four options that need to be styled- how do I call them on my external style sheet?

Select list
            <select id = "myList">
               <option value = "1">Drama</option>
               <option value = "2">Thriller</option>
               <option value = "3">Comedy</option>
           <option value ="4">Horror</option>
             </select>

Body:
You can create external CSS file (mystyle.css) and add it in head section of your web page. In this you mystyle.css you can write css properties of HTML elements.

Below is the link you need to add in head file (update path of css file in href) :

<link rel="stylesheet" type="text/css" href="mystyle.css">


问:
How to terminate Scanner when input is complete?
```<code>public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        try {
            while (scan.hasNextLine()){

                String line = scan.nextLine().toLowerCase();
                System.out.println(line);
            }

        } finally {
            scan.close();
        }
    }
</code>```

Just wondering how I can terminate the program after I have completed entering the inputs?
As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...
I tried:

```<code>if (scan.nextLine() == null) System.exit(0);
</code>```

and

```<code>if (scan.nextLine() == "") System.exit(0);
</code>```

They did not work.... The program continues and messes with the original intention,

答:
Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int is a double produces a double result so you can avoid some casting by declaring things carefully. Also assigning an int to something declared double also implies you want to store it as a double so no need to cast that either.

```<code>import java.util.Scanner;

public class TemperatureStats {

    final static int MAX_DAYS = 31;

    public static void main(String[] args){

        int[] dayTemps = new int[MAX_DAYS];
        double cumulativeTemp = 0.0;
        int minTemp = 1000, maxTemp = -1000;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");
        int entryCount = 0;
        while (input.hasNextInt() && entryCount < MAX_DAYS)
            dayTemps[entryCount++] = input.nextInt();

        /* Find min, max, cumulative total */
        for (int i = 0; i < entryCount; i++) {
            int temp = dayTemps[i];
            if (temp < minTemp)
                minTemp = temp;
            if (temp > maxTemp)
                maxTemp = temp;
            cumulativeTemp += temp;
        }

        System.out.println("Hi temp.   = " + maxTemp);
        System.out.println("Low temp.  = " + minTemp);
        System.out.println("Difference = " + (maxTemp - minTemp));
        System.out.println("Avg temp.  = " + cumulativeTemp / entryCount);
    }
}
</code>```

Body:
public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        try {
            while (scan.hasNextLine()){

                String line = scan.nextLine().toLowerCase();
                System.out.println(line);
            }

        } finally {
            scan.close();
        }
    }

Just wondering how I can terminate the program after I have completed entering the inputs?
As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...
I tried:

if (scan.nextLine() == null) System.exit(0);

and

if (scan.nextLine() == "") System.exit(0);

They did not work.... The program continues and messes with the original intention,

Body:
Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int is a double produces a double result so you can avoid some casting by declaring things carefully. Also assigning an int to something declared double also implies you want to store it as a double so no need to cast that either.

import java.util.Scanner;

public class TemperatureStats {

    final static int MAX_DAYS = 31;

    public static void main(String[] args){

        int[] dayTemps = new int[MAX_DAYS];
        double cumulativeTemp = 0.0;
        int minTemp = 1000, maxTemp = -1000;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");
        int entryCount = 0;
        while (input.hasNextInt() && entryCount < MAX_DAYS)
            dayTemps[entryCount++] = input.nextInt();

        /* Find min, max, cumulative total */
        for (int i = 0; i < entryCount; i++) {
            int temp = dayTemps[i];
            if (temp < minTemp)
                minTemp = temp;
            if (temp > maxTemp)
                maxTemp = temp;
            cumulativeTemp += temp;
        }

        System.out.println("Hi temp.   = " + maxTemp);
        System.out.println("Low temp.  = " + minTemp);
        System.out.println("Difference = " + (maxTemp - minTemp));
        System.out.println("Avg temp.  = " + cumulativeTemp / entryCount);
    }
}


问:
I am trying to use regular expression for extracting the Filename filed in Splunk,I have attached the same text
ID=6913&Filename=C%3A%5CUsers%5CTHanse04%5CAppData%5CRoaming%5CDocumentum%5CViewed%5C181019_ERS_321_102_500857.pdf&Download=65536&DownloadSize=79243 HTTP/1.1" 200 3 "-" "Java/1.8.0_192"

I need to extract and after extract i need Thanse04 from it
Filename=C%3A%5CUsers%5CTHanse04%5CAppData%5CRoaming%5CDocumentum%5CViewed%5C181019_ERS_321_102_500857.pdf

答:
(?:Filename=)(.*)(.pdf)(?:&)

demo

Explanation: (?:) is a matching but not capturing group. Here it matches 'Filename= but does not capture it. The regex keeps on capturing until it captures .pdf and then makes sure that the next character after that is & which it also matches but does not capture.


问:
How to run function from web app locally and not on host
I'm want to create a web app so a user can run process locally on his computer (I know that currently it doesn't have a real usage).

So I use flask to create the web app and created a button that calls function that run the process.
Issue is the func runs on the server and not on the machine the user use.

For example to be clear: Server runs on machine 1.2.3.4, a user log the web app from a different machine 5.6.7.8 and press the button, the func will run on the host (1.2.3.4) causing the process to open on the host and not locally on user computer.

```<code>from flask import Flask, render_template, request, url_for, flash, redirect
import subprocess

def runchrome():
    p = subprocess.Popen(r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")

app = Flask(__name__)

@app.route("/home", methods=["GET", "POST"])
def home():
    if request.method == "POST":
        process = request.form["process"]
        if process == "Chrome":
            runchrome()

    return render_template("Home.html")
</code>```

答:
You cannot run python code on the client's computer via a webapp in this way. Otherwise everybody could abuse this and run arbitrary code on computers that visit their websites. However, you can run javascript on the client's computer inside their browser.

For this to happen, you need to return a valid html document containing javascript. See this tutorial as a starting point: https://www.jitsejan.com/python-and-javascript-in-flask.html

Another way would be that the user installs your app on their machine.

Body:
I'm want to create a web app so a user can run process locally on his computer (I know that currently it doesn't have a real usage).

So I use flask to create the web app and created a button that calls function that run the process.
Issue is the func runs on the server and not on the machine the user use.

For example to be clear: Server runs on machine 1.2.3.4, a user log the web app from a different machine 5.6.7.8 and press the button, the func will run on the host (1.2.3.4) causing the process to open on the host and not locally on user computer.

from flask import Flask, render_template, request, url_for, flash, redirect
import subprocess

def runchrome():
    p = subprocess.Popen(r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")

app = Flask(__name__)

@app.route("/home", methods=["GET", "POST"])
def home():
    if request.method == "POST":
        process = request.form["process"]
        if process == "Chrome":
            runchrome()

    return render_template("Home.html")


问:
How do I set the class path on Linux?
I need an answer for the question in the title.

Thanks.

答:
```<code>export CLASSPATH=/your/stuff/
</code>```

or preserving system wide settings:

```<code>export CLASSPATH=$CLASSPATH:/your/addition/
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do I set the class path on Linux?

LastEditorDisplayName: Andrew Hare

Body:
export CLASSPATH=/your/stuff/

or preserving system wide settings:

export CLASSPATH=$CLASSPATH:/your/addition/


问:
$(document).ready(function(){}); vs script at the bottom of page
what is the difference / advantage / disadvantage of writing script at the bottom of the page and writing the script in </p>

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

答:
Very little in and of itself, either way the DOM will be ready for you to operate on (I was nervous about that until I read this from Google). If you use the end of page trick, your code may get called the slightest, slightest bit sooner, but nothing that will matter. But more importantly, this choice relates to where you link your JavaScript into the page.

If you include your script tag in the head and rely on ready, the browser encounters your script tag before it displays anything to the user. In the normal course of events, the browser comes to a screeching halt and goes and downloads your script, fires up the JavaScript interpreter, and hands the script to it, then waits while the interpreter processes the script (and then jQuery watches in various ways for the DOM to be ready). (I say "in the normal course of things" because some browsers support the async or defer attributes on script tags.)

If you include your script tag at the end of the body element, the browser doesn't do all of that until your page is largely already displayed to the user. This improves perceived load time for your page.

So to get the best perceived load time, put your script at the bottom of the page. (This is also the guideline from the Yahoo folks.) And if you're going to do that, then there's no need to use ready, though of course you could if you liked.

There's a price for that, though: You need to be sure that the things the user can see are ready to be interacted with. By moving the download time to after the page is largely displayed, you increase the possibility of the user starting to interact with the page before your script is loaded. That's one of the counter-arguments to putting the script tag at the end. Frequently it's not an issue, but you have to look at your page to see whether it is and, if so, how you want to deal with it. (You can put a small inline script element in the head that sets up a document-wide event handler to cope with this. That way, you get the improved load time but if they try to do something too early, you can either tell them that or, better, queue the thing they wanted to do and do it when your full script is ready.)

Body:
what is the difference / advantage / disadvantage of writing script at the bottom of the page and writing the script in

$(document).ready(function(){});


问:
Checking if item is already in database before adding it
I'm adding articles into a database. That worked fine, except, while the database doesn't let me create duplicates during a session, once I log out and log back in, it does. I didn't want duplicates, so I added these new lines:

```<code>maybe_existing_article = Article.query.filter_by(url=article.url)
if (maybe_existing_article):
    article = maybe_existing_article.url
    return "exists"
</code>```

But that didn't work, I get "print("article.id=" + str(article.id))
NameError: name 'article' is not defined".

Here is the relevant code, including the new lines.

```<code>##############################################
@app.route('/bootstrap', methods=['GET', 'POST'])
def bootstrap():
    posted = 1
    print ("bootstrap")
    global article
    if request.method == 'POST':
        if not request.form['title'] or not request.form['url'] or not request.form['image_url'] or not request.form['snippet']:
            flash('Please enter all the fields', 'error')
        else:
            article = Article(request.form['title'], request.form['url'], request.form['image_url'],
                               request.form['snippet'])
            maybe_existing_article = Article.query.filter_by(url=article.url)
            if (maybe_existing_article):
                article = maybe_existing_article.url
                return "exists"
            else:
                db.session.add(article)
                try:
                    db.session.commit()
                except exc.SQLAlchemyError:
                   flash('Article url already exists, failed to post new article')
                   posted = 0
                   #return render_template('/error.html', article_url=article.url)

                article_list = Article.query.filter_by(url=article.url)
                if posted == 1:
                    flash('Record was successfully added')
                else:
                    db.session.rollback()
                    article_list = Article.query.filter_by(url=article.url)
                    article=article_list[0]

                print ("article.id=" + str(article.id))
                import json
                print("a")
                return json.dumps(article.id)

    else:
        print("article.id=" + str(article.id))
        urlNumber = str(article.id)

        message = {'greeting':urlNumber}
        return jsonify(message)  # serialize and use JSON headers
</code>```

And here's the create_tables.py:

```<code>article_table = """CREATE TABLE IF NOT EXISTS article (
    id          INTEGER PRIMARY KEY,
    title       TEXT NOT NULL,
    url         TEXT NOT NULL,
    image_url   TEXT NOT NULL,
    snippet     TEXT NOT NULL,
    date_upload TEXT DEFAULT CURRENT_TIMESTAMP,
        CONSTRAINT article_unq UNIQUE (url)
);"""
</code>```

答:
You can use an Unique constraint at the table that you want and catch the error when you try to insert a row that was already inserted. In SQLite, you can't add this constraint after the Table is created, so you would need to create the table again.

You can also add an Unique Index to the table that works almost the same:

CREATE UNIQUE INDEX index_name ON table_name(column_name);

If you can't do that, you can always send a SELECT to that table with the ID you are trying to insert and them return an error to the user if it was already inserted, although this is hardly recommended.

Body:
I'm adding articles into a database. That worked fine, except, while the database doesn't let me create duplicates during a session, once I log out and log back in, it does. I didn't want duplicates, so I added these new lines:

maybe_existing_article = Article.query.filter_by(url=article.url)
if (maybe_existing_article):
    article = maybe_existing_article.url
    return "exists"

But that didn't work, I get "print("article.id=" + str(article.id))
NameError: name 'article' is not defined".

Here is the relevant code, including the new lines.

##############################################
@app.route('/bootstrap', methods=['GET', 'POST'])
def bootstrap():
    posted = 1
    print ("bootstrap")
    global article
    if request.method == 'POST':
        if not request.form['title'] or not request.form['url'] or not request.form['image_url'] or not request.form['snippet']:
            flash('Please enter all the fields', 'error')
        else:
            article = Article(request.form['title'], request.form['url'], request.form['image_url'],
                               request.form['snippet'])
            maybe_existing_article = Article.query.filter_by(url=article.url)
            if (maybe_existing_article):
                article = maybe_existing_article.url
                return "exists"
            else:
                db.session.add(article)
                try:
                    db.session.commit()
                except exc.SQLAlchemyError:
                   flash('Article url already exists, failed to post new article')
                   posted = 0
                   #return render_template('/error.html', article_url=article.url)

                article_list = Article.query.filter_by(url=article.url)
                if posted == 1:
                    flash('Record was successfully added')
                else:
                    db.session.rollback()
                    article_list = Article.query.filter_by(url=article.url)
                    article=article_list[0]

                print ("article.id=" + str(article.id))
                import json
                print("a")
                return json.dumps(article.id)

    else:
        print("article.id=" + str(article.id))
        urlNumber = str(article.id)

        message = {'greeting':urlNumber}
        return jsonify(message)  # serialize and use JSON headers

And here's the create_tables.py:

article_table = """CREATE TABLE IF NOT EXISTS article (
    id          INTEGER PRIMARY KEY,
    title       TEXT NOT NULL,
    url         TEXT NOT NULL,
    image_url   TEXT NOT NULL,
    snippet     TEXT NOT NULL,
    date_upload TEXT DEFAULT CURRENT_TIMESTAMP,
        CONSTRAINT article_unq UNIQUE (url)
);"""


问:
Using hasNext() Scanner method to only allow a set of X inputs
How can I use the scanner hasNext() method to ensure that the user only selects a value between 1 and 20 and then use that value as a String to return in fillSpot variable?  The code below is lacking a way to check if the input is between 1 and 20.  I am also receiving the error code fillSpot cannot be resolved to a variable on the final return line. Any help would be much appreciated!

```<code>public String giveInput() {

    Scanner in = new Scanner(System.in);
int space;

do {
        System.out.println("Enter numerical value between 1 and 20");
        while (in.hasNext()) {
            String fillSpot = in.nextLine();
            System.out.printf("\"%s\" is not a valid input.\n", fillSpot);
        }
        space = in.nextInt();
    } while (space < 1 || space < 20);

    return fillSpot;
}
</code>```

答:
You can also try this and based on your requirement you can return a String or an Integer.</p>

```<code>public static String giveInput() {

    Scanner in = new Scanner(System.in);
    String inputString;
    int inputNumber = 0;

    do {
        System.out.println("Enter numerical value between 1 and 20");
        inputString = in.nextLine();
        try {
            inputNumber = Integer.parseInt(inputString);
        } catch (NumberFormatException e) {
            System.err.println("Please enter a number");
        }

    } while (inputNumber < 1 || inputNumber > 20);

    return inputString;
}
</code>```

Body:
How can I use the scanner hasNext() method to ensure that the user only selects a value between 1 and 20 and then use that value as a String to return in fillSpot variable?  The code below is lacking a way to check if the input is between 1 and 20.  I am also receiving the error code fillSpot cannot be resolved to a variable on the final return line. Any help would be much appreciated!

public String giveInput() {

    Scanner in = new Scanner(System.in);
int space;

do {
        System.out.println("Enter numerical value between 1 and 20");
        while (in.hasNext()) {
            String fillSpot = in.nextLine();
            System.out.printf("\"%s\" is not a valid input.\n", fillSpot);
        }
        space = in.nextInt();
    } while (space < 1 || space < 20);

    return fillSpot;
}

Body:
You can also try this and based on your requirement you can return a String or an Integer.

public static String giveInput() {

    Scanner in = new Scanner(System.in);
    String inputString;
    int inputNumber = 0;

    do {
        System.out.println("Enter numerical value between 1 and 20");
        inputString = in.nextLine();
        try {
            inputNumber = Integer.parseInt(inputString);
        } catch (NumberFormatException e) {
            System.err.println("Please enter a number");
        }

    } while (inputNumber < 1 || inputNumber > 20);

    return inputString;
}


问:
How to limit teams view to just their own assignments
I have a google sheet work order page set up. The columns are:

ID No., Title, Description, Location, Crew Assigned, Date Assigned, Hours Worked, Work Description.

Crew Assigned are pulled from a dropdown populated by a second sheet. So the entry is standardized.

I want the crew, when they open up the work order sheet, to see only the rows that are assigned to them. They would then enter Hours Worked, and the Work Description. They use apple mobile devices exclusively.

Is there a best practice for this type of work delegation within sheets?

答: The best way to do this is to have one master spreadsheet and then to each team give a new spreadsheet with FILTER(IMPORTRANGE(... formula.


问:
javascript find all the object in an array and convert it into an array to array
I have a list of array with object in it like address and details

Input

```<code>var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]
</code>```

I want to iterate on this array and convert all the inner object so that it will look something like below

Expected Result

```<code>var arr = [
    {id: 1, name: "abc", street: "some text1", pin: 879888, state: "my-state1", section: "A", roll: 12, branch: "CSE"},
    {id: 2, name: "xyz", street: "some text2", pin: 879887, state: "my-state2", section: "B", roll: 13, branch: "IT"}
]
</code>```

答:
In this case, the loop processes the entire array and check if prop is not an object then copy key\value in a new object. If prop is an object just merge this object to new object. then you should return a new object.

var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]

let res = arr.map(row => {
   let newRow = {};
   for (let key in row) {
     if (row.hasOwnProperty(key)) {
        if (typeof row[key] !== 'object') {
          newRow[key] = row[key];
        } else {
          newRow = {
            ...newRow,
            ...row[key]
          }
        }
     }
   }
   return newRow;
});

console.info(res);```

Body:
I have a list of array with object in it like address and details

Input

var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]

I want to iterate on this array and convert all the inner object so that it will look something like below

Expected Result

var arr = [
    {id: 1, name: "abc", street: "some text1", pin: 879888, state: "my-state1", section: "A", roll: 12, branch: "CSE"},
    {id: 2, name: "xyz", street: "some text2", pin: 879887, state: "my-state2", section: "B", roll: 13, branch: "IT"}
]


问:
Python pandas if row contains string add to table
I have a spreadsheet that looks as follows:

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

HMI1 controls AZ1

HMI2 controls AZ2

HMI3 controls AZ3

HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

```<code>HMIX | AZX
</code>```

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

```<code>    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])
</code>```

答:
Iterate over rows first, thank over columns, if you find the x, print the row and the columns.

```<code>for i, row in dfConfig.iterrows():
    for col in dfConfig:
        if row[col] == 'x':
            print(f'HMI{row["hmi_number"]} controls {col}')
</code>```

Body:
I have a spreadsheet that looks as follows:

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

HMI1 controls AZ1

HMI2 controls AZ2

HMI3 controls AZ3

HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

HMIX | AZX

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])

Body:
Iterate over rows first, thank over columns, if you find the x, print the row and the columns.

for i, row in dfConfig.iterrows():
    for col in dfConfig:
        if row[col] == 'x':
            print(f'HMI{row["hmi_number"]} controls {col}')


问:
Angular - Get Component name from a URL
I have routes defined this way in app-routing.module.ts:

```<code>const routes: Routes = [
  {
    path: 'abc/:id', component: AbcComponent
  },
  {
    path: 'xyz/:id/tester/:mapId', component: XyzComponent
  },
  { path: '**', redirectTo: '/page-not-found', pathMatch: 'full'}
]
</code>```

I would like to get the component name based on a URL in app.component.ts

Ex: If a user navigated to http://myapp.com/abc/123 I would like to the get the component name, which in this case would be AbcComponent

If a user navigated to http://myapp.com/xyz/123/tester/456 I would like to the get the component name, which in this case would be XyzComponent

How can I get that?

I tried to use ActivatedRoute, but it doesn't seem to work, as I get Cannot read property 'component' of null.

```<code>  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
 this.checkRoute()
}

checkRoute()
{
   console.log(this.activatedRoute.routeConfig.component.name)
}
</code>```

答:
You could add the name of each component to the data object of the accordant route, like:

```<code>{
  path: 'abc/:id',
  component: AbcComponent,
  data: {
    name: 'AbcComponent'
  }
}
</code>```

And then getting its value like demonstrated here:

```<code>ngOnInit() {
  this.route.data.subscribe((data: { name: string }) => {
    console.log(data);
  });
}
</code>```

Edit:

I have created a stackblitz. Open the console and click on Catalog.

Title: Angular - Get Component name from a URL

Body:
I have routes defined this way in app-routing.module.ts:

const routes: Routes = [
  {
    path: 'abc/:id', component: AbcComponent
  },
  {
    path: 'xyz/:id/tester/:mapId', component: XyzComponent
  },
  { path: '**', redirectTo: '/page-not-found', pathMatch: 'full'}
]

I would like to get the component name based on a URL in app.component.ts

Ex: If a user navigated to http://myapp.com/abc/123 I would like to the get the component name, which in this case would be AbcComponent

If a user navigated to http://myapp.com/xyz/123/tester/456 I would like to the get the component name, which in this case would be XyzComponent

How can I get that?

I tried to use ActivatedRoute, but it doesn't seem to work, as I get Cannot read property 'component' of null.

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
 this.checkRoute()
}

checkRoute()
{
   console.log(this.activatedRoute.routeConfig.component.name)
}

Body:
You could add the name of each component to the data object of the accordant route, like:

{
  path: 'abc/:id',
  component: AbcComponent,
  data: {
    name: 'AbcComponent'
  }
}

And then getting its value like demonstrated here:

ngOnInit() {
  this.route.data.subscribe((data: { name: string }) => {
    console.log(data);
  });
}

Edit:

I have created a stackblitz. Open the console and click on Catalog.


问:
HttpParams refuse to set
Using Angular 8 I'm trying to set an HttpParam using the code below, see the result on the last line.

```<code>let newParams = new HttpParams();
newParams.set('ordering', 'name');
console.log('getting: ', newParams.get('ordering'));
// getting: null
</code>```

Using the code below i see that the param has been set as i expected:

```<code>let newParams = new HttpParams().set('ordering', 'name');
console.log('getting: ', newParams.get('ordering'));
// getting: name
</code>```

looking at the docs i cant understand why this isn't working.  Is this a bug, or am I just missing something fundamental in javascript?

答:
set returns a new instance. That is effectively being thrown away in your first example.

A long-hand version to demonstrate the problem might be

```<code>let newParams = new HttpParams();
let discardedParams = newParams.set('ordering', 'name');
console.log('getting: ', newParams.get('ordering'));
</code>```

From the docs:

set()

Returns

HttpParams: A new body with the new value.

Title: HttpParams refuse to set

Body:
Using Angular 8 I'm trying to set an HttpParam using the code below, see the result on the last line.

let newParams = new HttpParams();
newParams.set('ordering', 'name');
console.log('getting: ', newParams.get('ordering'));
// getting: null

Using the code below i see that the param has been set as i expected:

let newParams = new HttpParams().set('ordering', 'name');
console.log('getting: ', newParams.get('ordering'));
// getting: name

looking at the docs i cant understand why this isn't working.  Is this a bug, or am I just missing something fundamental in javascript?

Body:
set returns a new instance. That is effectively being thrown away in your first example.

A long-hand version to demonstrate the problem might be

let newParams = new HttpParams();
let discardedParams = newParams.set('ordering', 'name');
console.log('getting: ', newParams.get('ordering'));

From the docs:

set()

Returns

HttpParams: A new body with the new value.


问:
Why include when you can require in PHP?
What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

答:
Sometimes you are including files from libraries that you do not control or your code is being run on different environments.

It is possible that some of these aren't actually required for your script but are helper files or extras.

For instance, if your PHP is generating HTML, you might use an include to add a banner. But you wouldn't want your file to halt if for some reason that banner file was missing. You'd want to gracefully fail instead.


问:
Python "TypeError: 'bool' object is not callable" Error
I am writing a simple Tic-Tac-Toe game that is a player vs computer game, and I keep getting the "TypeError: 'bool' object is not callable" Error, and I do not understand why I am getting these errors. I have gone through both the formatting and the syntax multiple times and I can't see anything wrong with my code but I keep getting a few errors.  Here is my code. </p>

```<code>import random

def drawBoard(board):
    #This function prints out the board that it was passed.

    #board" is a list of 10 strings representing the board (ignore index 0).
    print(board[7] + '| ' + board[8] + '| ' + board[9])
    print('-+-+-')
    print(board[4] + '| ' + board[5] + '| ' + board[6])
    print('-+-+-')
    print(board[1] + '| ' + board[2] + '| ' + board[3])

def inputPlayerLetter():
    letter = ''
    while not (letter == 'X' or letter == '0'):
        print('Do you want to be X or O?')
        letter = input().upper()
    if letter == 'X':
        return ['X', '0']
    else:
        return ['0', 'X']

def whoGoesFirst():
    if random.randint(0,1) == 0:
        return ' computer'
    else:
        return ' player'

def makeMove(board, letter, move):
    board[move] = letter

def isWinner(bo, le):
    return ((bo[7] == le and bo[8] == le and bo [9] == le) or
    (bo[4] == le and bo[5] == le and bo [6] == le)
    (bo[1] == le and bo[2] == le and bo [3] == le)
    (bo[7] == le and bo[4] == le and bo [1] == le)
    (bo[8] == le and bo[5] == le and bo [2] == le)
    (bo[9] == le and bo[6] == le and bo [3] == le)
    (bo[7] == le and bo[5] == le and bo [3] == le)
    (bo[9] == le and bo[5] == le and bo [1] == le))

def getBoardCopy(board):
    boardCopy = []
    for i in board:
        boardCopy.append(i)
    return boardCopy

def isSpaceFree(board, move):
    return board[move] == ' '

def getPlayerMove(board):
    move = ' '
    while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
        print('What is your next move? (1-9)')
        move = input()
    return int(move)

def chooseRandomMoveFromList(board, movesList):
    possibleMoves = []
    for i in movesList:
        if isSpaceFree(board, i):
            possibleMoves.append(i)

    if len(possibleMoves) !=0:
        return random.choice(possibleMoves)
    else:
        return None

def getComputerMove(board, computerLetter):
    if computerLetter == 'X':
        playerLetter = '0'
    else:
        playerLetter = 'X'

    for i in range(1, 10):
        boardCopy = getBoardCopy(board)
        if isSpaceFree (boardCopy, i):
            makeMove(boardCopy, computerLetter, i)
            if isWinner(boardCopy, computerLetter):
                return i

    for i in range(1,10):
        boardCopy = getBoardCopy(board)
        if isSpaceFree(boardCopy, i):
            makeMove(boardCopy, playerLetter, i)
            if isWinner(boardCopy, playerLetter):
                return i

    move = chooseRandomMoveFromList (board, [1, 3, 7, 9])
    if move !=None:
        return move

    if isSpaceFree(board, 5):
        return 5

    return chooseRandomMoveFromList(board, [2, 4, 6, 8])

def isBoardFull(board):
    for i in range(1,10):
        if isSpaceFree(board, i):
            return False
        return True

print('Welcome to Tic-Tac-Toe!')

while True:
    theBoard = [' '] * 10
    playerLetter, computerLetter = inputPlayerLetter()
    turn = whoGoesFirst()
    print('The' +turn+ ' will go first.')
    gameIsPlaying = True

    while gameIsPlaying:
        if turn == 'player':
            drawBoard(theBoard)
            move = getPlayerMove(theBoard)
            makeMove(theBoard, playerLetter, move)

            if isWinner(theBoard, playerLetter):
                drawBoard(theBoard)
                print('Horray! You have won the game!')
                gameIsPlaying = False
            else:
                if isBoardFull(theBoard):
                    drawBoard(theBoard)
                    print('The game is a tie!')
                    break
                else:
                    turn = 'computer'

        else:
            move = getComputerMove(theBoard, computerLetter)
            makeMove(theBoard, computerLetter, move)

            if isWinner(theBoard, computerLetter):
                drawBoard(theBoard)
                print('The computer has beaten you! You lose.')
                gameIsPlaying = False
            else:
                if isBoardFull(theBoard):
                    drawBoard(theBoard)
                    print('The game is a tie!')
                    break
                else:
                    turn = 'player'

    print('Do you want to play again? (yes or no)')
    if not input().lower().startswith('y'):
        break
</code>```

答:
1) There is logical error in the return condition of function isWinner. Try to debug the function isWinner separately.

2) You can include some comments to your code to make it more readable. Include also a main function with the command:

```<code>if __name__ = "__main__":
    # main body
</code>```

to make your code run faster. As you have it now, you have many global variables that take more time to run/execute.

Body:
I am writing a simple Tic-Tac-Toe game that is a player vs computer game, and I keep getting the "TypeError: 'bool' object is not callable" Error, and I do not understand why I am getting these errors. I have gone through both the formatting and the syntax multiple times and I can't see anything wrong with my code but I keep getting a few errors.  Here is my code.

import random

def drawBoard(board):
    #This function prints out the board that it was passed.

    #board" is a list of 10 strings representing the board (ignore index 0).
    print(board[7] + '| ' + board[8] + '| ' + board[9])
    print('-+-+-')
    print(board[4] + '| ' + board[5] + '| ' + board[6])
    print('-+-+-')
    print(board[1] + '| ' + board[2] + '| ' + board[3])

def inputPlayerLetter():
    letter = ''
    while not (letter == 'X' or letter == '0'):
        print('Do you want to be X or O?')
        letter = input().upper()
    if letter == 'X':
        return ['X', '0']
    else:
        return ['0', 'X']

def whoGoesFirst():
    if random.randint(0,1) == 0:
        return ' computer'
    else:
        return ' player'

def makeMove(board, letter, move):
    board[move] = letter

def isWinner(bo, le):
    return ((bo[7] == le and bo[8] == le and bo [9] == le) or
    (bo[4] == le and bo[5] == le and bo [6] == le)
    (bo[1] == le and bo[2] == le and bo [3] == le)
    (bo[7] == le and bo[4] == le and bo [1] == le)
    (bo[8] == le and bo[5] == le and bo [2] == le)
    (bo[9] == le and bo[6] == le and bo [3] == le)
    (bo[7] == le and bo[5] == le and bo [3] == le)
    (bo[9] == le and bo[5] == le and bo [1] == le))

def getBoardCopy(board):
    boardCopy = []
    for i in board:
        boardCopy.append(i)
    return boardCopy

def isSpaceFree(board, move):
    return board[move] == ' '

def getPlayerMove(board):
    move = ' '
    while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
        print('What is your next move? (1-9)')
        move = input()
    return int(move)

def chooseRandomMoveFromList(board, movesList):
    possibleMoves = []
    for i in movesList:
        if isSpaceFree(board, i):
            possibleMoves.append(i)

    if len(possibleMoves) !=0:
        return random.choice(possibleMoves)
    else:
        return None

def getComputerMove(board, computerLetter):
    if computerLetter == 'X':
        playerLetter = '0'
    else:
        playerLetter = 'X'

    for i in range(1, 10):
        boardCopy = getBoardCopy(board)
        if isSpaceFree (boardCopy, i):
            makeMove(boardCopy, computerLetter, i)
            if isWinner(boardCopy, computerLetter):
                return i

    for i in range(1,10):
        boardCopy = getBoardCopy(board)
        if isSpaceFree(boardCopy, i):
            makeMove(boardCopy, playerLetter, i)
            if isWinner(boardCopy, playerLetter):
                return i

    move = chooseRandomMoveFromList (board, [1, 3, 7, 9])
    if move !=None:
        return move

    if isSpaceFree(board, 5):
        return 5

    return chooseRandomMoveFromList(board, [2, 4, 6, 8])

def isBoardFull(board):
    for i in range(1,10):
        if isSpaceFree(board, i):
            return False
        return True

print('Welcome to Tic-Tac-Toe!')

while True:
    theBoard = [' '] * 10
    playerLetter, computerLetter = inputPlayerLetter()
    turn = whoGoesFirst()
    print('The' +turn+ ' will go first.')
    gameIsPlaying = True

    while gameIsPlaying:
        if turn == 'player':
            drawBoard(theBoard)
            move = getPlayerMove(theBoard)
            makeMove(theBoard, playerLetter, move)

            if isWinner(theBoard, playerLetter):
                drawBoard(theBoard)
                print('Horray! You have won the game!')
                gameIsPlaying = False
            else:
                if isBoardFull(theBoard):
                    drawBoard(theBoard)
                    print('The game is a tie!')
                    break
                else:
                    turn = 'computer'

        else:
            move = getComputerMove(theBoard, computerLetter)
            makeMove(theBoard, computerLetter, move)

            if isWinner(theBoard, computerLetter):
                drawBoard(theBoard)
                print('The computer has beaten you! You lose.')
                gameIsPlaying = False
            else:
                if isBoardFull(theBoard):
                    drawBoard(theBoard)
                    print('The game is a tie!')
                    break
                else:
                    turn = 'player'

    print('Do you want to play again? (yes or no)')
    if not input().lower().startswith('y'):
        break

Body:
1) There is logical error in the return condition of function isWinner. Try to debug the function isWinner separately.

2) You can include some comments to your code to make it more readable. Include also a main function with the command:

if __name__ = "__main__":
    # main body

to make your code run faster. As you have it now, you have many global variables that take more time to run/execute.


问:
Live console input/output for a gameserver using JavaScript or PHP
General information: I have a Minecraft server running in the basement for some friends that is running for a couple months now. We were using TeamViewer to input commands into the console and view possible errors while the server was running. The console of a Minecraft server basically shows you a log of events with timestamps as well as a command input line at the bottom that enables you to execute in-game commands with administrator rights.

The console is started via a batch file:

```<code>:startup
@echo off
set v1=6
cls
Java -Xmx%v1%G -jar spigot.jar nogui
goto startup
</code>```

The spigot.jar file is the file that basically runs the server.

Because we manage multiple servers and the TeamViewer process is quite insecure and slow, i wanted to find other ways to access the console.

Target: I want to create a HTML webinterface that uses JavaScript or PHP to communicate with the server console. It should be able to show the live console log as well as being able to type commands in the browser that are then executed in the commandline on the server.

Problems:

Is there any way to send a JavaScript/PHP input to the console so that I can execute commands from a webinterface?

Can I save the live console output to a .txt file that the JavaScript/PHP script can then display live on the webinterface?

答:
I would definitely recommend moving your setup outside of a Windows environment, as you're going to have a much easier time hosting a PHP server, etc. in a Linux environment.

Admittedly, I'm not familiar with MineCraft, but it looks like the batch file you have is effectively just launching a Java JAR which can be done from any computer with the JRE installed. Java console apps read input on the STDIN of a process and output on STDOUT for any application-generated output. This is incredibly easy to pickup in a Ubuntu environment.

For example, let's say you install the standard LAMP stack on a fresh Ubuntu install. You'll have PHP for running your server-side process, and Apache for hosting any web interface you decide to build. Keeping a focus on frontend vs. backend, I'd probably try to setup an API in PHP using Slim or another lightweight framework. In the API endpoint you use to start your server, it would look something like this:

```<code>exex('screen -d -m -S ServerOne');
exec('screen -S ServerOne -p 0 -X stuff "java -Xmx%v1%G -jar spigot.jar nogui > /some_path_to_log^M"');
</code>```

The first exec() will create a screen session named "ServerOne" inside of which your server process can run. The second exec() will send the command needed to start your server process inside of the screen session. Effectively, this will run your server asynchronously to your PHP script and write the output to the specified path. Knowing where to expect the output, in the API endpoint you use to get your log, you'd have something like:

```<code>$logContent = file_get_content('/some_path_to_log');
</code>```

Finally, in the API endpoint you use to write commands to your server, you would have something that looks like:

```<code>exec('screen -S ServerOne -p 0 -X stuff "<your_command_here>^M"');
</code>```

This will write to the STDIN stream of your server's Java process which should, in turn, be interpreted as if you were actually typing at the keyboard of the console itself.

That's the basics of it, or at least where I'd get started. There are some pretty cool things that you could do with WebSockets to open a live I/O session for your server's console, but it'd be a bit more involved than this post. If you're interested, check out Ratchet for PHP or ws for Node.js.

Consider this ServerFault post for more information on sending input to screen sessions.

Body:
General information: I have a Minecraft server running in the basement for some friends that is running for a couple months now. We were using TeamViewer to input commands into the console and view possible errors while the server was running. The console of a Minecraft server basically shows you a log of events with timestamps as well as a command input line at the bottom that enables you to execute in-game commands with administrator rights.

The console is started via a batch file:

:startup
@echo off
set v1=6
cls
Java -Xmx%v1%G -jar spigot.jar nogui
goto startup

The spigot.jar file is the file that basically runs the server.

Because we manage multiple servers and the TeamViewer process is quite insecure and slow, i wanted to find other ways to access the console.

Target: I want to create a HTML webinterface that uses JavaScript or PHP to communicate with the server console. It should be able to show the live console log as well as being able to type commands in the browser that are then executed in the commandline on the server.

Problems:

Is there any way to send a JavaScript/PHP input to the console so that I can execute commands from a webinterface?

Can I save the live console output to a .txt file that the JavaScript/PHP script can then display live on the webinterface?

Body:
I would definitely recommend moving your setup outside of a Windows environment, as you're going to have a much easier time hosting a PHP server, etc. in a Linux environment.

Admittedly, I'm not familiar with MineCraft, but it looks like the batch file you have is effectively just launching a Java JAR which can be done from any computer with the JRE installed. Java console apps read input on the STDIN of a process and output on STDOUT for any application-generated output. This is incredibly easy to pickup in a Ubuntu environment.

For example, let's say you install the standard LAMP stack on a fresh Ubuntu install. You'll have PHP for running your server-side process, and Apache for hosting any web interface you decide to build. Keeping a focus on frontend vs. backend, I'd probably try to setup an API in PHP using Slim or another lightweight framework. In the API endpoint you use to start your server, it would look something like this:

exex('screen -d -m -S ServerOne');
exec('screen -S ServerOne -p 0 -X stuff "java -Xmx%v1%G -jar spigot.jar nogui > /some_path_to_log^M"');

The first exec() will create a screen session named "ServerOne" inside of which your server process can run. The second exec() will send the command needed to start your server process inside of the screen session. Effectively, this will run your server asynchronously to your PHP script and write the output to the specified path. Knowing where to expect the output, in the API endpoint you use to get your log, you'd have something like:

$logContent = file_get_content('/some_path_to_log');

Finally, in the API endpoint you use to write commands to your server, you would have something that looks like:

exec('screen -S ServerOne -p 0 -X stuff "<your_command_here>^M"');

This will write to the STDIN stream of your server's Java process which should, in turn, be interpreted as if you were actually typing at the keyboard of the console itself.

That's the basics of it, or at least where I'd get started. There are some pretty cool things that you could do with WebSockets to open a live I/O session for your server's console, but it'd be a bit more involved than this post. If you're interested, check out Ratchet for PHP or ws for Node.js.

Consider this ServerFault post for more information on sending input to screen sessions.


问:
Javascript - avoid multiple array.filters being called
I have a piece of code that looks like:

```<code>const desktop = platform.filter(el => el == "desktop").length;
const mobile = platform.filter(el => el == "mobile").length;
const android = platform.filter(el => el == "android").length;
</code>```

and so on..

Basically I have an array that contains multiple entries of those strings and I want to collect the length of each property in a variable. The above works but I was wondering if there is a cleaner way to avoid filter through the array multiple times?

答:
While it would not avoid the multiple iterations, you could write an equivalent more cleanly:

```<code>const desktop = platform .includes ("desktop")
const mobile =  platform .includes ("mobile")
const android = platform .includes ("android")
</code>```

But if the multiple iterations are a real problem, Ori Drori's technique should cover it.

Body:
I have a piece of code that looks like:

const desktop = platform.filter(el => el == "desktop").length;
const mobile = platform.filter(el => el == "mobile").length;
const android = platform.filter(el => el == "android").length;

and so on..

Basically I have an array that contains multiple entries of those strings and I want to collect the length of each property in a variable. The above works but I was wondering if there is a cleaner way to avoid filter through the array multiple times?

Body:
While it would not avoid the multiple iterations, you could write an equivalent more cleanly:

const desktop = platform .includes ("desktop")
const mobile =  platform .includes ("mobile")
const android = platform .includes ("android")

But if the multiple iterations are a real problem, Ori Drori's technique should cover it.


问:
Does it make sense to define an Interface for internal use where we know needs with change?
I am in the designing stage of a new project for internal use - the software will never be "shipped". I know with absolute certainty that we will add more functionality to the project going forward. If I were to wait then the project will never get done. I am approaching the project by designing Interfaces. I want to use interfaces in the code so I can check classes for that type and do certain things. I also want to perform operations on all classes of a certain Interface. There will be certain Interfaces where classes will have different logic to achieve the result. Interfaces make sense for this.

My two questions:

Everybody seems to say that your interface needs to be stable. If you need to add additional capabilities later on what does one typically do? Inherit a base interface and add on?

There are certain situations where (for now) an Interface will only be implemented by one class. In this case does it still make sense to use an Interface?

答:
Everybody seems to say that your interface needs to be stable. If you need to add additional capabilities later on what does one typically do? Inherit a base interface and add on?

If components which inherit a given interface are not used for an API (meaning that for e.g. a plugin must inherit this interface to communicate with your application) then modifying the interface shouldn't be a problem

In my case if I need to extend my in-house plugins without breaking compatibility of customer plugins (both of which share the same interface to work) I'd do the following:
 - Create an extending interface
 - Inherit the extending interface in the plugin class

There are certain situations where (for now) an Interface will only be implemented by one class. In this case does it still make sense to use an Interface?

You do not need an interface for everything, that is for sure; however, planing ahead what you might want to extend in the future or unit test will tell you where you definitely need one. For example you would decouple your application from specific dependencies by replacing them with interfaces and injecting the required implementations using DI.

All in all, just like @Himbrombeere says: it depends on what you are trying to achieve and you should be prepared for change in your software.

If you are talking about a simple tool which, for e.g. only reads a text file and let's say counts the words, then putting in a lot of effort in it doesn't make sense.