问:
How to sort a list in python based on another list
I have a python list with user ids
data = [123,456,789]
and I want to sort this list based on how many points they have (calculated by points[userid]). I have tried SortedData = sorted(data,key=points,reverse=True) to no avail. Is there any way to do this?

Thanks.
Evan

答:
You need to epxlicit it in a lambda.  You could di points[x] but points.get(x,0) may be safer here

```<code>data = [123,456,789]
points = {123:20, 456:10, 789:15}
sortedData = sorted(data, key=lambda x:points.get(x,0), reverse=True)
print(sortedData)
</code>```

If you're ok of letting None as default value instead of a number, you can reduce to

```<code>sortedData = sorted(data, key=points.get, reverse=True) # use the method itself
</code>```

Body:
You need to epxlicit it in a lambda.  You could di points[x] but points.get(x,0) may be safer here

data = [123,456,789]
points = {123:20, 456:10, 789:15}
sortedData = sorted(data, key=lambda x:points.get(x,0), reverse=True)
print(sortedData)

If you're ok of letting None as default value instead of a number, you can reduce to

sortedData = sorted(data, key=points.get, reverse=True) # use the method itself


来源: stackexchange

问:
Can we model multiple inheritance with Grakn?
In RDF/OWL we can have a class with many superclasses either assigned or inferred through multiple inheritance. Many reference ontologies require the support of multiple inheritance.

However, Grakn only supports single type inheritance, how to use Grakn for this.

For example, can this example be modelled in Grakn?

```<code>company      rdf:type         rdfs:Class
government   rdf:type         rdfs:Class

employer     rdf:type         rdfs:Class
employer     rdfs:subClassOf  government
employer     rdfs:subClassOf  government
</code>```

答:
The example posted in the question models an employer as both of class company and government. However, although this may look correct, the problem is that often multiple inheritance, as a modelling concept, is not used in the right way. Multiple inheritance should group things, and not subclass "types", where each type is a definition of something else. In other words, we don't want to represent instances of data. This is a common mistake.

Instead of multiple inheritance, we should assign roles, which allow us to model any type of domain. A role defines the behaviour and aspect of a thing in the context of a relation, and we can assign multiple roles to a thing (note that roles are inherited when types subclass another).

For example, a government can employ a person, and a company can employ a person. One might suggest to then create a class that inherits both government and company which can employ a person, and end up with an employer class that subclasses both (as shown in the example above).

However, this is an abuse of inheritance. In this case, we should create a role employer, which relates to an employment relation and contextualises how a company or government is involved in that relation (by playing the role of employer).

```<code>company sub entity,
    plays employer;

government sub entity,
    plays employer;

employment sub relation,
    relates employer;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In RDF/OWL we can have a class with many superclasses either assigned or inferred through multiple inheritance. Many reference ontologies require the support of multiple inheritance.

However, Grakn only supports single type inheritance, how to use Grakn for this.

For example, can this example be modelled in Grakn?

company      rdf:type         rdfs:Class
government   rdf:type         rdfs:Class

employer     rdf:type         rdfs:Class
employer     rdfs:subClassOf  government
employer     rdfs:subClassOf  government

Body:
The example posted in the question models an employer as both of class company and government. However, although this may look correct, the problem is that often multiple inheritance, as a modelling concept, is not used in the right way. Multiple inheritance should group things, and not subclass "types", where each type is a definition of something else. In other words, we don't want to represent instances of data. This is a common mistake.

Instead of multiple inheritance, we should assign roles, which allow us to model any type of domain. A role defines the behaviour and aspect of a thing in the context of a relation, and we can assign multiple roles to a thing (note that roles are inherited when types subclass another).

For example, a government can employ a person, and a company can employ a person. One might suggest to then create a class that inherits both government and company which can employ a person, and end up with an employer class that subclasses both (as shown in the example above).

However, this is an abuse of inheritance. In this case, we should create a role employer, which relates to an employment relation and contextualises how a company or government is involved in that relation (by playing the role of employer).

company sub entity,
    plays employer;

government sub entity,
    plays employer;

employment sub relation,
    relates employer;


问:
principal class of NSBundle
Plz help me to understand what is principalClass used for?what is the syntax of it. i understand tat it is in NSBundle Class,but can we create it for any bundles of is it specific only for laodable bundles? plz help me to know the concept of principalClass.

Thanking You.

答:
I will give you an example of how you can create and load a bundle as plugin. Hope that this will help you a lot. I must say that I agree with the other 2 (so far) answers. So...

Create an Xcode project as "Bundle" (in Xcode 3.2.6 is in New Project->Framework & Library-> select "Bundle"). Create the following files...

PClass.h

```<code>#import <Foundation/Foundation.h>
@interface PClass : NSObject {

}

- (NSString*) stringMessage;

@end
</code>```

PClass.m

```<code>- (NSString*) stringMessage {
    return @"Hallo from plugin";
}
</code>```

in the projects .plist file add the following two entries:

"Bundle display name"    "MyPlugin"

"Principal class"    "PClass"

Then compile the project and move the binary (.../build/Debug/yourPlugin.bundle) to a folder you like to keep your plugins of a project of yours (may be copied into aProject.app/Plugins/ with a little extra care).

Then to an already Xcode project add the following:

```<code>- (void) loadPlugin {

    id bundle = [NSBundle bundleWithPath:@"the path you/placed/yourPlugin.bundle"];

    NSLog(@"%@", [[bundle infoDictionary] valueForKey:@"CFBundleDisplayName"]);
    // Here you can preview your plugins names without loading them if you don't need to or just to
    // display it to GUI, etc

    NSError *err;
    if(![bundle loadAndReturnError:&err]) {
        // err
    } else {
        // bundle loaded
        Class PluginClass = [bundle principalClass]; // here is where you need your principal class!
        // OR...
        //Class someClass = [bundle classNamed:@"KillerAppController"];

        id instance = [[PluginClass alloc] init];

        NSLog(@"%@", [instance stringMessage]);

        [instance release];  // If required
    [bundle unload]; // If required
}
</code>```

}

You have just loaded a bundle via its Principal Class as a plugin of an application.

ContentLicense: CC BY-SA 2.5

Title: principal class of NSBundle

Body:
I will give you an example of how you can create and load a bundle as plugin. Hope that this will help you a lot. I must say that I agree with the other 2 (so far) answers. So...

Create an Xcode project as "Bundle" (in Xcode 3.2.6 is in New Project->Framework & Library-> select "Bundle"). Create the following files...

PClass.h

#import <Foundation/Foundation.h>
@interface PClass : NSObject {

}

- (NSString*) stringMessage;

@end

PClass.m

- (NSString*) stringMessage {
    return @"Hallo from plugin";
}

in the projects .plist file add the following two entries:

"Bundle display name"    "MyPlugin"

"Principal class"    "PClass"

Then compile the project and move the binary (.../build/Debug/yourPlugin.bundle) to a folder you like to keep your plugins of a project of yours (may be copied into aProject.app/Plugins/ with a little extra care).

Then to an already Xcode project add the following:

- (void) loadPlugin {

    id bundle = [NSBundle bundleWithPath:@"the path you/placed/yourPlugin.bundle"];

    NSLog(@"%@", [[bundle infoDictionary] valueForKey:@"CFBundleDisplayName"]);
    // Here you can preview your plugins names without loading them if you don't need to or just to
    // display it to GUI, etc

    NSError *err;
    if(![bundle loadAndReturnError:&err]) {
        // err
    } else {
        // bundle loaded
        Class PluginClass = [bundle principalClass]; // here is where you need your principal class!
        // OR...
        //Class someClass = [bundle classNamed:@"KillerAppController"];

        id instance = [[PluginClass alloc] init];

        NSLog(@"%@", [instance stringMessage]);

        [instance release];  // If required
    [bundle unload]; // If required
}

}

You have just loaded a bundle via its Principal Class as a plugin of an application.

ContentLicense: CC BY-SA 3.0


问:
Angular CDK Overlay Module: CanDeactivateGuard should launch custom modal
UPDATE:

I've refactored based on @Blind Despair's answer below. It now uses the Overlay Module from Angular CDK. Here's the code for the Guard:

```<code>@Injectable({
  providedIn: 'root',
})
export class PendingChangesGuard
  implements CanDeactivate<ComponentCanDeactivate> {
  content = 'A simple string content modal overlay';
  constructor(private overlayService: OverlayService) {}

  canDeactivate(
    component: ComponentCanDeactivate
  ): boolean | Observable<boolean> {
    return component.canDeactivate()
      ? true
      : this.openConfirmDialog(this.content);
  }

  openConfirmDialog(content: TemplateRef<any> | ComponentType<any> |
string) {
    const ref = this.overlayService.open(this.content, null);

    return ref.afterClosed$.subscribe((res) => {});
  }
}
</code>```

The problem is this line is returning a subscription and my guard has to return either a boolean or Observable:

```<code> return ref.afterClosed$.subscribe((res) => {});
</code>```

Here is the OverlayService class:

```<code>@Injectable({
  providedIn: 'root',
})
export class OverlayService {
  constructor(private overlay: Overlay, private injector: Injector) {}

  open<R = any, T = any>(
    content: string | TemplateRef<any> | Type<any>,
    data: T
  ): OverlayRef<R> {
    const configs = new OverlayConfig({
      hasBackdrop: true,
      panelClass: ['modal', 'is-active'],
      backdropClass: 'modal-background',
    });

    const overlayRef = this.overlay.create(configs);

    const myOverlayRef = new OverlayRef<R, T>(overlayRef, content,
data);

    const injector = this.createInjector(myOverlayRef, this.injector);
    overlayRef.attach(new ComponentPortal(OverlayComponent, null,
injector));

    return myOverlayRef;
  }

  createInjector(ref: OverlayRef, inj: Injector) {
    const injectorTokens = new WeakMap([[RaOverlayRef, ref]]);
    return new PortalInjector(inj, injectorTokens);
  }
}
</code>```

And here's the Overlay class:

```<code>export interface OverlayCloseEvent<R> {
  type: 'backdropClick' | 'close';
  data: R;
}

// R = Response Data Type, T = Data passed to Modal Type
export class OverlayRef<R = any, T = any> {
  afterClosed$ = new Subject<OverlayCloseEvent<R>>();

  constructor(
    public overlay: OverlayRef,
    public content: string | TemplateRef<any> | Type<any>,
    public data: T // pass data to modal i.e. FormData
  ) {
    overlay.backdropClick().subscribe(() =>
this._close('backdropClick', null));
  }

  close(data?: R) {
    this._close('close', data);
  }

  private _close(type: 'backdropClick' | 'close', data: R) {
    this.overlay.dispose();
    this.afterClosed$.next({
      type,
      data,
    });

    this.afterClosed$.complete();
  }
}
</code>```

Any tips for how to refactor the openConfirmDialog() to return what I need?

答:
Can you just slighty refactor to something like...</p>

```<code>canDeactivate(
    component: ComponentCanDeactivate
  ): boolean | Observable<boolean> {
    const _v = component.canDeactivate();
    if (!_v) {
      this.openConfirmDialog();
    }
    return _v;
  }
</code>```

Body:
UPDATE:

I've refactored based on @Blind Despair's answer below. It now uses the Overlay Module from Angular CDK. Here's the code for the Guard:

@Injectable({
  providedIn: 'root',
})
export class PendingChangesGuard
  implements CanDeactivate<ComponentCanDeactivate> {
  content = 'A simple string content modal overlay';
  constructor(private overlayService: OverlayService) {}

  canDeactivate(
    component: ComponentCanDeactivate
  ): boolean | Observable<boolean> {
    return component.canDeactivate()
      ? true
      : this.openConfirmDialog(this.content);
  }

  openConfirmDialog(content: TemplateRef<any> | ComponentType<any> |
string) {
    const ref = this.overlayService.open(this.content, null);

    return ref.afterClosed$.subscribe((res) => {});
  }
}

The problem is this line is returning a subscription and my guard has to return either a boolean or Observable:

 return ref.afterClosed$.subscribe((res) => {});

Here is the OverlayService class:

@Injectable({
  providedIn: 'root',
})
export class OverlayService {
  constructor(private overlay: Overlay, private injector: Injector) {}

  open<R = any, T = any>(
    content: string | TemplateRef<any> | Type<any>,
    data: T
  ): OverlayRef<R> {
    const configs = new OverlayConfig({
      hasBackdrop: true,
      panelClass: ['modal', 'is-active'],
      backdropClass: 'modal-background',
    });

    const overlayRef = this.overlay.create(configs);

    const myOverlayRef = new OverlayRef<R, T>(overlayRef, content,
data);

    const injector = this.createInjector(myOverlayRef, this.injector);
    overlayRef.attach(new ComponentPortal(OverlayComponent, null,
injector));

    return myOverlayRef;
  }

  createInjector(ref: OverlayRef, inj: Injector) {
    const injectorTokens = new WeakMap([[RaOverlayRef, ref]]);
    return new PortalInjector(inj, injectorTokens);
  }
}

And here's the Overlay class:

export interface OverlayCloseEvent<R> {
  type: 'backdropClick' | 'close';
  data: R;
}

// R = Response Data Type, T = Data passed to Modal Type
export class OverlayRef<R = any, T = any> {
  afterClosed$ = new Subject<OverlayCloseEvent<R>>();

  constructor(
    public overlay: OverlayRef,
    public content: string | TemplateRef<any> | Type<any>,
    public data: T // pass data to modal i.e. FormData
  ) {
    overlay.backdropClick().subscribe(() =>
this._close('backdropClick', null));
  }

  close(data?: R) {
    this._close('close', data);
  }

  private _close(type: 'backdropClick' | 'close', data: R) {
    this.overlay.dispose();
    this.afterClosed$.next({
      type,
      data,
    });

    this.afterClosed$.complete();
  }
}

Any tips for how to refactor the openConfirmDialog() to return what I need?

Body:
Can you just slighty refactor to something like...

canDeactivate(
    component: ComponentCanDeactivate
  ): boolean | Observable<boolean> {
    const _v = component.canDeactivate();
    if (!_v) {
      this.openConfirmDialog();
    }
    return _v;
  }


问:
Is there an R function for checking if a value is a legal index in a vector or list?
There are several ways to index i R e.g. by selecting using positive integers, by excluding using negative integers, by selecting using logicals/conditions, by selecting using names (character-vectors) in a named vector or list, and probably a lot of other ways than that.
What I want is a function taking two inputs ix and lst that tells me if ix makes sense as an index of lst, i.e. that lst[ix] makes sense.

I already know you can do something like

is.index <- function(ix,lst){
  ans = FALSE
  try({ans=all(!is.na(lst[ix]))},silent = TRUE)
  return(ans)
}
```

But I want it to work when the list contains NAs, and when it's lst is a list it works differently. Both of these cases I could probably easily take care of as special cases, but I feel that I don't know all the possible ways to index, and all the intricacies of these, so I have no way of knowing if I have nailed all the special cases.

I know the "make sense" term isn't well defined, but it would seem reasonable to me, that there exist a function or at least a somewhat easy way of telling if an index is reasonable.

So is there a function or a simple way to do that, preferable not something requiring a try or a try catch statement?

EDIT: I realize that I haven't been clear in the statement of my question. Even if ix is a vector I want to know if lst[ix] makes sense, and not a vector telling me if lst[ix[i]] makes sense for the different possible values of i. Preferably we should have that no matter the type of ix and lst the function should always be able to return one logical value i.e. a TRUE or a FALSE. For example if lst = 1:5 and ix = c(-1,2) should return FALSE and not c(TRUE,TRUE).

Further clarification: Personally I don't like the partial matching or that it makes sense to index by non-integer doubles (I like even less that it just uses the integer part (rather that e.g. rounding to closest integer (useful for small precision errors) or taking the floor (makes lst[x/y] = lst[x%/%y]))); but since it makes sense to R I think it should be up to the preferences of the answerer whether to return TRUE or FALSE in these situations. The same goes for lst[0] and lst[NA], whereas since list("Cheese" = 4)["Che"] gives NA I don't think that partial matching should be accepted.

But seeing that (at least I think) requiring the answerer to make their own choices is bad practice; if I were to choose I think that all these (except partial matching) should be accepted and returned as TRUE.

答:
Something like the following seems to do the job. It uses partial matching to match character ix with the vector or list names.

```<code>is.index <- function(X, ix){
  if(is.character(ix)){
    if(is.null(names(X))) FALSE
    !is.na(pmatch(ix, names(X)))
  }else{
    abs(ix) <= length(X)
  }
}
</code>```

Test with vectors.

```<code>x <- 1:6
y <- setNames(x, letters[x])
is.index(x, 2)
is.index(x, 7)
is.index(x, -3)
is.index(y, 'a')
is.index(y, 'z')
</code>```

And now with lists.

```<code>lst <- list(1:6, letters[1:4])
is.index(lst, 3)
is.index(lst, "a")
is.index(lst, -1)
</code>```

But there are problems, partial matching only works with the $ extractor function, it doesn't work with [[, not even with [.

```<code>lst2 <- setNames(lst, c("A", "2nd"))
is.index(lst2, "A")

is.index(lst2, "2n")
lst2$`2n`              # works
lst[['2n']]            # fails
</code>```

Body:
There are several ways to index i R e.g. by selecting using positive integers, by excluding using negative integers, by selecting using logicals/conditions, by selecting using names (character-vectors) in a named vector or list, and probably a lot of other ways than that.
What I want is a function taking two inputs ix and lst that tells me if ix makes sense as an index of lst, i.e. that lst[ix] makes sense.

I already know you can do something like

is.index <- function(ix,lst){
  ans = FALSE
  try({ans=all(!is.na(lst[ix]))},silent = TRUE)
  return(ans)
}

But I want it to work when the list contains NAs, and when it's lst is a list it works differently. Both of these cases I could probably easily take care of as special cases, but I feel that I don't know all the possible ways to index, and all the intricacies of these, so I have no way of knowing if I have nailed all the special cases.

I know the "make sense" term isn't well defined, but it would seem reasonable to me, that there exist a function or at least a somewhat easy way of telling if an index is reasonable.

So is there a function or a simple way to do that, preferable not something requiring a try or a try catch statement?

EDIT: I realize that I haven't been clear in the statement of my question. Even if ix is a vector I want to know if lst[ix] makes sense, and not a vector telling me if lst[ix[i]] makes sense for the different possible values of i. Preferably we should have that no matter the type of ix and lst the function should always be able to return one logical value i.e. a TRUE or a FALSE. For example if lst = 1:5 and ix = c(-1,2) should return FALSE and not c(TRUE,TRUE).

Further clarification: Personally I don't like the partial matching or that it makes sense to index by non-integer doubles (I like even less that it just uses the integer part (rather that e.g. rounding to closest integer (useful for small precision errors) or taking the floor (makes lst[x/y] = lst[x%/%y]))); but since it makes sense to R I think it should be up to the preferences of the answerer whether to return TRUE or FALSE in these situations. The same goes for lst[0] and lst[NA], whereas since list("Cheese" = 4)["Che"] gives NA I don't think that partial matching should be accepted.

But seeing that (at least I think) requiring the answerer to make their own choices is bad practice; if I were to choose I think that all these (except partial matching) should be accepted and returned as TRUE.

Body:
Something like the following seems to do the job. It uses partial matching to match character ix with the vector or list names.

is.index <- function(X, ix){
  if(is.character(ix)){
    if(is.null(names(X))) FALSE
    !is.na(pmatch(ix, names(X)))
  }else{
    abs(ix) <= length(X)
  }
}

Test with vectors.

x <- 1:6
y <- setNames(x, letters[x])
is.index(x, 2)
is.index(x, 7)
is.index(x, -3)
is.index(y, 'a')
is.index(y, 'z')

And now with lists.

lst <- list(1:6, letters[1:4])
is.index(lst, 3)
is.index(lst, "a")
is.index(lst, -1)

But there are problems, partial matching only works with the $ extractor function, it doesn't work with [[, not even with [.

lst2 <- setNames(lst, c("A", "2nd"))
is.index(lst2, "A")

is.index(lst2, "2n")
lst2$`2n`              # works
lst[['2n']]            # fails


问:
Dynamics CRM Error : The object cannot be updated because it is read-only when closing a Phone Call

User closes an active/open phone call and gets the error on the image.

答:
The error message: Cannot Update Closed or Cancelled Activity is expected when some script or code piece trying to update the activity (phonecall, task, etc) but the record is marked already as completed/closed/cancelled status.

Check if any javascript is triggered on onSave, onChange, onLoad events

Check if any custom action, plugin, Workflow triggers

From the screenshot the record has unsaved changes and showing still "open" in bottom right/left corners. Quite not sure if any other pre-update plugins triggering or some other operation trying to update another activity record (which is different from this current record).


答:
key also accepts a function.

Try this:

sorted_list = list(sorted(data, key= lambda userid: points[userid], reverse=True))
```

Title: How to sort a list in python based on another list

Body:
I have a python list with user ids
data = [123,456,789]
and I want to sort this list based on how many points they have (calculated by points[userid]). I have tried SortedData = sorted(data,key=points,reverse=True) to no avail. Is there any way to do this?

Thanks.
Evan


问:
Secure authentication structure in a React Webapp
I am currently learning React and worked through some courses but still haven't completely understood how to create a proper structure for a secure web app.

For the sign in, sign up flow I use the firebase SDK. Once logged in, a user gets redirected to a private route. Right now I only have 2 user roles. Guests and signed in Users. This enables me to create private routes by using an inbuild firebase function. This is the first problem as it is not scalable once I add different roles as it would force me to send a request to the backend to check what role the user is and thus which pages he can acces.

```<code>if (firebase.auth().currentUser === null) {
        console.log("not logged in")
        return     (<Redirect
            to={{
              pathname: "/signin",
              state: {
                from: props.location
              }
            }}
          />);

    }
</code>```

So I thought that the easiest option would be to use Context, which did work. Once a user loggs in, the server sends a user object which the app refers to for the rest of the session. I followed a bunch of tutorials and they all had the same problem that when using chrome developer tools with the react features, you could just edit the state of the user and bypass the private routes etc.

Second Try:

```<code><UserContext.Consumer>{(context)=>{
          const {isLoggedIn} = context
          return(
        <Route
          {...rest}
          render={props => {

        if (isLoggedIn) {
            console.log("not logged in")
            return     (<Redirect
                to={{
                  pathname: "/signin",
                  state: {
                    from: props.location
                  }
                }}
              />);
</code>```

I'd be grateful if somebody could point me in a direction as it seems like I am missing something important.

EDIT 1: Or is it simply that once you build the app, you can no longer access these states and it's considered safe?

答:
I think what you are doing on the frontend site is good, but you would also need logic in the backend to protect your routes. This means that an user may be able to circumvent your route protection via dev tools on the frontend, but your backend would only send error messages to him, as it recognizes that he has no allowance.

You could do this with Higher Order Functions like this one:

```<code>const authenticationWrapper = createResolver(
  async ( models, session, SALT ) => {
    try {
      if (!session) {
        throw new Error("No valid credentials!");
      }

      const { id } = verify(session.token, salt);

      const valid = databasecall //

      if (!valid) {
        throw new Error("No valid user!");
      }

      return true
    } catch (error) {
      session.destroy((err) => {
        if (err) {
          console.error(err);
        }
      });
    }
  }
);
</code>```

All private backend functions would be wrapped into and authentication of the user would be checked every time.

The principle to check in Front- and Backend is called dual authentication. You can read more about it here.

Body:
I am currently learning React and worked through some courses but still haven't completely understood how to create a proper structure for a secure web app.

For the sign in, sign up flow I use the firebase SDK. Once logged in, a user gets redirected to a private route. Right now I only have 2 user roles. Guests and signed in Users. This enables me to create private routes by using an inbuild firebase function. This is the first problem as it is not scalable once I add different roles as it would force me to send a request to the backend to check what role the user is and thus which pages he can acces.

if (firebase.auth().currentUser === null) {
        console.log("not logged in")
        return     (<Redirect
            to={{
              pathname: "/signin",
              state: {
                from: props.location
              }
            }}
          />);

    }

So I thought that the easiest option would be to use Context, which did work. Once a user loggs in, the server sends a user object which the app refers to for the rest of the session. I followed a bunch of tutorials and they all had the same problem that when using chrome developer tools with the react features, you could just edit the state of the user and bypass the private routes etc.

Second Try:

<UserContext.Consumer>{(context)=>{
          const {isLoggedIn} = context
          return(
        <Route
          {...rest}
          render={props => {

        if (isLoggedIn) {
            console.log("not logged in")
            return     (<Redirect
                to={{
                  pathname: "/signin",
                  state: {
                    from: props.location
                  }
                }}
              />);

I'd be grateful if somebody could point me in a direction as it seems like I am missing something important.

EDIT 1: Or is it simply that once you build the app, you can no longer access these states and it's considered safe?

Body:
I think what you are doing on the frontend site is good, but you would also need logic in the backend to protect your routes. This means that an user may be able to circumvent your route protection via dev tools on the frontend, but your backend would only send error messages to him, as it recognizes that he has no allowance.

You could do this with Higher Order Functions like this one:

const authenticationWrapper = createResolver(
  async ( models, session, SALT ) => {
    try {
      if (!session) {
        throw new Error("No valid credentials!");
      }

      const { id } = verify(session.token, salt);

      const valid = databasecall //

      if (!valid) {
        throw new Error("No valid user!");
      }

      return true
    } catch (error) {
      session.destroy((err) => {
        if (err) {
          console.error(err);
        }
      });
    }
  }
);

All private backend functions would be wrapped into and authentication of the user would be checked every time.

The principle to check in Front- and Backend is called dual authentication. You can read more about it <a href="http://I%20think%20what%20you%20are%20doing%20on%20the%20frontend%20site%20is%20good,%20but%20you%20would%20also%20need%20logic%20in%20the%20backend%20to%20protect%20your%20routes.%20Meaning%20that%20an%20user%20may%20be%20able%20to%20circumvent%20your%20route%20protection%20via%20dev%20tools,%20but%20your%20backend%20would%20only%20send%20error%20messages%20to%20him,%20as%20it%20recognizes%20that%20he%20has%20no%20allowance.%20This%20is%20called%20dual%20authentication.%20You%20can%20read%20more%20about%20it%20here." rel="nofollow noreferrer">here.


问:
Multi-dimensional numpy array into a variable number of several one dimensional arrays for function scipy function argument
I am working on a large gene array where a single gene is represented by multiple probes, any where from 2 to 20. I basically want to do a kruskal-wallace test (non-parametric anova) to determine if the probes on a single gene give essentially the same info. SO I have written the following code, let genes be a (1 x m) array where m is the number of probes. Let X be a (n x m) numpy array).

```<code>ugenes=np.unique(genes)
for i in range(genes.size):
    gene=ugenes[i]
    idx=np.where(genes==gene)[0]
    % the length of idx is variable and can be anywhere from 2 to twenty so Xd is of
    % variable size
    Xd=X[:,idx]
    [h,p]=kruskal(Xd)
</code>```

the problem I run into is that kruskal only takes one dimensional arrays with multiple arrays as arguments. Since Xd is variable I do not how many single arrays I would have to break it up into and the number of unique genes is on the order of 20000 so doing it manually is not an option. Is there anyway to break up Xd such that it can be sent into to kruskal as

```<code>kruskal(Xd[:,0],Xd[:,1],...Xd[:,z])
</code>```

(where z is the number of total columns of Xd) on the fly without doing the number of columns of Xd?

答:
You can try converting columns to list and passing it to kruskal:</p>

```<code>Xd=list(X[:,idx].T)
[h,p]=kruskal(*Xd)
</code>```

Body:
I am working on a large gene array where a single gene is represented by multiple probes, any where from 2 to 20. I basically want to do a kruskal-wallace test (non-parametric anova) to determine if the probes on a single gene give essentially the same info. SO I have written the following code, let genes be a (1 x m) array where m is the number of probes. Let X be a (n x m) numpy array).

ugenes=np.unique(genes)
for i in range(genes.size):
    gene=ugenes[i]
    idx=np.where(genes==gene)[0]
    % the length of idx is variable and can be anywhere from 2 to twenty so Xd is of
    % variable size
    Xd=X[:,idx]
    [h,p]=kruskal(Xd)

the problem I run into is that kruskal only takes one dimensional arrays with multiple arrays as arguments. Since Xd is variable I do not how many single arrays I would have to break it up into and the number of unique genes is on the order of 20000 so doing it manually is not an option. Is there anyway to break up Xd such that it can be sent into to kruskal as

kruskal(Xd[:,0],Xd[:,1],...Xd[:,z])

(where z is the number of total columns of Xd) on the fly without doing the number of columns of Xd?

Body:
You can try converting columns to list and passing it to kruskal:

Xd=list(X[:,idx].T)
[h,p]=kruskal(*Xd)


问:
Why do the IF statements cause batch file to exit?
I have tried to make the code pick a random number 1-5 and it would then choose a random area in the game. The problem is that it keeps exiting whenever it executes. It ignores also the x between the %place% variable.

```<code>pause
set place=%random% %% 5
timeout 1
if x%place%x==1 goto cave
if x%place%x==2 goto plains
if x%place%x==3 goto swamp
if x%place%x==4 goto volcano
if x%place%x==5 goto fail
:cave
echo You went for a crusade and ended up in a cave.
pause
:plains
echo You went for a crusade and found a plains biome.
pause
:swamp
echo You went for a crusade and ventured into a swamp.
pause
:volcano
echo You went for a crusade and somehow ended up on a volcano.
pause
:fail
echo Your boat sank and you survived. You lost 5 coins.
pause
</code>```

答:
Your set statement needs the /a switch because you are trying to do math.  Also you need to add one to the result, because right now you are getting a random number in the range of 0-4, and your if statements are numbered 1-5.  Also I know you said to ignore the x's, but they need to go if you want your program to work.  Here is an edited copy of your program:

```<code>set /a place = %RANDOM% %% 5 + 1
timeout 1
if %place% equ 1 goto cave
if %place% equ 2 goto plains
if %place% equ 3 goto swamp
if %place% equ 4 goto volcano
if %place% equ 5 goto fail
:cave
echo You went for a crusade and ended up in a cave.
pause
:plains
echo You went for a crusade and found a plains biome.
pause
:swamp
echo You went for a crusade and ventured into a swamp.
pause
:volcano
echo You went for a crusade and somehow ended up on a volcano.
pause
:fail
echo Your boat sank and you survived. You lost 5 coins.
pause
</code>```

Body:
I have tried to make the code pick a random number 1-5 and it would then choose a random area in the game. The problem is that it keeps exiting whenever it executes. It ignores also the x between the %place% variable.

pause
set place=%random% %% 5
timeout 1
if x%place%x==1 goto cave
if x%place%x==2 goto plains
if x%place%x==3 goto swamp
if x%place%x==4 goto volcano
if x%place%x==5 goto fail
:cave
echo You went for a crusade and ended up in a cave.
pause
:plains
echo You went for a crusade and found a plains biome.
pause
:swamp
echo You went for a crusade and ventured into a swamp.
pause
:volcano
echo You went for a crusade and somehow ended up on a volcano.
pause
:fail
echo Your boat sank and you survived. You lost 5 coins.
pause

Body:
Your set statement needs the /a switch because you are trying to do math.  Also you need to add one to the result, because right now you are getting a random number in the range of 0-4, and your if statements are numbered 1-5.  Also I know you said to ignore the x's, but they need to go if you want your program to work.  Here is an edited copy of your program:

set /a place = %RANDOM% %% 5 + 1
timeout 1
if %place% equ 1 goto cave
if %place% equ 2 goto plains
if %place% equ 3 goto swamp
if %place% equ 4 goto volcano
if %place% equ 5 goto fail
:cave
echo You went for a crusade and ended up in a cave.
pause
:plains
echo You went for a crusade and found a plains biome.
pause
:swamp
echo You went for a crusade and ventured into a swamp.
pause
:volcano
echo You went for a crusade and somehow ended up on a volcano.
pause
:fail
echo Your boat sank and you survived. You lost 5 coins.
pause


问:
How to deploy express.js server to Netlify
I am attempting to deploy a Vue.js, Node, Express, MongoDB (MEVN) stack application to Netlify. I successfully deployed the front end of the application to Netlify, and am now attempting to deploy the express server, based on the following serverless-http example: https://github.com/neverendingqs/netlify-express/blob/master/express/server.js

I configured my server to include the serverless-http package:

server.js

```<code>const express = require('express');
const app = express();
const serverless = require('serverless-http');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');
const postRoute = require('./routes');

mongoose.connect(config.DB, { useNewUrlParser: true, useUnifiedTopology: true }).then(
  () => { console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use('/messages', postRoute);

app.use('/.netlify/functions/server', router);  // path must route to lambda
app.use('/', (req, res) => res.sendFile(path.join(__dirname, '../public/index.html')));

module.exports = app;
module.exports.handler = serverless(app);

</code>```

routes.js

```<code>const express = require('express');
const postRoutes = express.Router();

// Require Post model in our routes module
let Post = require('./post.model');

// Defined store route
postRoutes.route('/add').post(function (req, res) {
  let post = new Post(req.body);
  post.save()
    .then(() => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(() => {
      res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
    Post.find(function(err, posts){
    if(err){
      res.json(err);
    }
    else {
      res.json(posts);
    }
  });
});

module.exports = postRoutes;

</code>```

I then re-deployed my application to Netlify, but the server does not seem to run in Netlify. This server is in a folder in project root of my vue.js app. Should I instead run the server as a separate site in Netlify? If not, what should I do in order to get the server to run when deployed in Netlify?

答:
It's been a while, but here goes.

Netlify hosting is for the Jamstack, as they say, i.e. only static files, no processing on the server. The idea is to make use of other mechanisms to get your data dynamically, such as APIs hosted elsewhere, which you query straight from the browser, or when you build your site.

Most likely you actually had to deploy your express.js app as a Netlify Function, instead. Check Netlify's blog post on running express apps on their functions.

Body:
I am attempting to deploy a Vue.js, Node, Express, MongoDB (MEVN) stack application to Netlify. I successfully deployed the front end of the application to Netlify, and am now attempting to deploy the express server, based on the following serverless-http example: https://github.com/neverendingqs/netlify-express/blob/master/express/server.js

I configured my server to include the serverless-http package:

server.js

const express = require('express');
const app = express();
const serverless = require('serverless-http');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');
const postRoute = require('./routes');

mongoose.connect(config.DB, { useNewUrlParser: true, useUnifiedTopology: true }).then(
  () => { console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use('/messages', postRoute);

app.use('/.netlify/functions/server', router);  // path must route to lambda
app.use('/', (req, res) => res.sendFile(path.join(__dirname, '../public/index.html')));

module.exports = app;
module.exports.handler = serverless(app);

routes.js

const express = require('express');
const postRoutes = express.Router();

// Require Post model in our routes module
let Post = require('./post.model');

// Defined store route
postRoutes.route('/add').post(function (req, res) {
  let post = new Post(req.body);
  post.save()
    .then(() => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(() => {
      res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
    Post.find(function(err, posts){
    if(err){
      res.json(err);
    }
    else {
      res.json(posts);
    }
  });
});

module.exports = postRoutes;

I then re-deployed my application to Netlify, but the server does not seem to run in Netlify. This server is in a folder in project root of my vue.js app. Should I instead run the server as a separate site in Netlify? If not, what should I do in order to get the server to run when deployed in Netlify?


问:
Can I insert a List of doubles or Strings in sqlite table in flutter?
I want to insert two lists in my sqlite table in flutter, one containing names and other containing doubles. Is there a way I can achieve this?</p>

答:
There is no datatype in sqlite that accepts lists. But you can still do this using json encoding. Have a look at the official docs here : https://flutter.dev/docs/development/data-and-backend/json

You basically encode your data into json, save it as a String to sqlite, and then decode it again when you pull it out of sqlite.


问:
How to get the source of images inside div react native
I have regular expression for extracting the source of images in html string coming from json api in react native app.
The output is in array:

```<code>var m,
array= [],
str = '<img class="d-block mx-auto" src="http://www.website.com/759x493.jpg" />,
rex = /<img[^>]+src="?([^"\s]+)"?\s*\alt="First slide">/g;
      while ( m = rex.exec( str ) ) {
          array.push( m[1] );
      }
console.log(array);  // ["http://www.website.com/66189-759x493.jpg",...]
</code>```

However I want rex that gets only the source of images inside specific class carousel-item :

```<code>str = '<div class="carousel-item"> <img class="d-block mx-auto" src="http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg" />';
</code>```

I can not use DOMParser like other solutions.

答:
UPDATE 2020-06-04: This code snipped is updated based on new info on source string:

This regex populates an array with image links within carousel-item divs:

var imageUrls = [];
var str = '
\n' +
  '
\n' +
  '
\n' +
  '      \n' +
  '
\n' +
  '
\n' +
  '      \n' +
  '
\n' +
  '
\n' +
  '
';
var re = /
]*>\s*]+? src="?([^"\s]+)/g;
str.replace(re, function(m, p1) {
  imageUrls.push(p1);
});
console.log('result: ' + imageUrls.join(', '));```

Note: The parenthesis in ([^"\s]+) capture the image URL, which is passed on by p1 parameter in the replacement function.

Body:
I have regular expression for extracting the source of images in html string coming from json api in react native app.
The output is in array:

var m,
array= [],
str = ',
rex = /]+src="?([^"\s]+)"?\s*\alt="First slide">/g;
      while ( m = rex.exec( str ) ) {
          array.push( m[1] );
      }
console.log(array);  // ["http://www.website.com/66189-759x493.jpg",...]

However I want rex that gets only the source of images inside specific class carousel-item :

str = '
 ';

I can not use DOMParser like other solutions.

Body:
UPDATE 2020-06-04: This code snipped is updated based on new info on source string:

This regex populates an array with image links within carousel-item divs:

var imageUrls = [];
var str = '<div class="carousel slide">\n' +
  '  <div class="carousel-inner">\n' +
  '    <div class="carousel-item active">\n' +
  '      <img class="d-block mx-auto" src="http://www.example.com/wp-content/uploads/2020/05/66189-759x493.jpg" />\n' +
  '    </div>\n' +
  '    <div class="carousel-item">\n' +
  '      <img class="d-block mx-auto" src="http://www.example.com/wp-content/uploads/2020/05/66174-1-778x493.jpg" />\n' +
  '    </div>\n' +
  '  </div>\n' +
  '</div>';
var re = /<div class="?carousel-item"?[^>]*>\s*<img [^>]+? src="?([^"\s]+)/g;
str.replace(re, function(m, p1) {
  imageUrls.push(p1);
});
console.log('result: ' + imageUrls.join(', '));

Note: The parenthesis in ([^"\s]+) capture the image URL, which is passed on by p1 parameter in the replacement function.


问:
database clean up in acceptance tests with specflow
I am a newbie in tdd. I have watched Brandon Satrom's videos. I am trying to implement tests like them ,outer loop for acceptance tests and inner loop for unit tests. I have thought acceptance test was againist to Database ,too.So i expect to find examples about [BeginScenario/AfterScenario] events for database clean up in Specflow.It is said to be used for database Clean up. But None of the examples i saw do it.

Am i misundestanding the acceptance test concept? Doesn't it cover the database too? Should we use mock objects there like we did in unit tests?

答:
At last i am convinced that i must use the real database in my acceptance tests. I have to see some examples, and read it from several resources before i settle it in my mind.

Now i am using acceptence test as supposed for testing the flow of my user interfaces and database.
i wrote a happy path scenerio for my registration page to design page flow. then i wrote some test for logic that kept in my stored procedures in database. Other logic is on controllers and model classes. So for them i used unit tests. Now it makes more sense to me, until my next confusion about tdd :).

As for clean up process, i use  [BeginScenario/AfterScenario]  events. At BeginScenario i use a global varible to keep a DateTime.Now.Ticks value and merge it in beginnigs of the values that i sent to db. Then i find the records that start with this  DateTime.Now.Ticks value when i making the clean up for that scenario at AfterScenario event. So it helped me to make unique values that doesnt interfere with other records. It seemed to work by now.


问:
Hugo Docsy image path referencing with multiple languages
I am the static site generator Hugo with the theme Docsy, but I am having difficulty providing the correct path so Hugo can find my images?

I read Hugo's content organization will search for an image either in the Page Bundle or in the project's static directory.  See Hugo Directory Structure: static.

I am using the Page Bundle organization for the images in my project.

The path to my images is:
My_Hugo_Docsy_Project/content/en/docs/My_Page_Bundle/assets/image_file.jpg

I am using regular markdown to include the images, but this does not work:

![Image1](/assets/image_file.jpg)

I believe Docsy's multiple language feature (internationalization) is causing the hangup, which nests the content directory structure by language.

答:
Docsy's default config.toml, sets contentDir = "content/en".

Setting contentDir effectively changes the "site root" for Page Bundled resources like images.  The "site root" directory is where Hugo would start to look for image_file.jpg.

```<code>#Hugo root directory when contentDir = "content/en"
`My_Hugo_Docsy_Project/content/en/

#Hugo root directory when contentDir = “content”
My_Hugo_Docsy_Project/content
</code>```

So the image path in the markdown would be:

![Image1](/docs/My_Page_Bundle/assets/image_file.jpg)

Body:
Docsy's default config.toml, sets contentDir = "content/en".

Setting contentDir effectively changes the "site root" for Page Bundled resources like images.  The "site root" directory is where Hugo would start to look for image_file.jpg.

#Hugo root directory when contentDir = "content/en"
`My_Hugo_Docsy_Project/content/en/

#Hugo root directory when contentDir = “content”
My_Hugo_Docsy_Project/content

So the image path in the markdown would be:

![Image1](/docs/My_Page_Bundle/assets/image_file.jpg)


问:
Customize AWS ElasticBeanstalk NodeJS Install (use yarn)
Isit possible to configure EBS to install my NodeJS application using yarn package manager instead of NPM? </p>

答:
Had to revisit this as we couldn't figure out why we were stuck on node 8 even though we set it to node 12 in the EB UI. Seems that if you install a global node it overrides the version setting. Instead of installing a global node, this uses the Elastic Beanstalk node install and adds it to the path. You have to add the PATH in again at the start of your yarn install script but it seems to be the least invasive way to use yarn.</p>

```<code>content: |
  #!/usr/bin/env bash
  set -euxo pipefail

  EB_NODE_VERSION=$(/opt/elasticbeanstalk/bin/get-config optionsettings -n aws:elasticbeanstalk:container:nodejs -o NodeVersion)
  echo "EB node version: $(EB_NODE_VERSION)"

  # Make sure Node binaries can be found (required to run npm).
  # And this lets us invoke npm more simply too.
  export PATH=/opt/elasticbeanstalk/node-install/node-v$EB_NODE_VERSION-linux-x64/bin:$PATH

  if yarn -v; then
    echo 'Yarn already installed.'
  else
    echo 'Installing yarn...'
    npm install yarn -g
  fi
</code>```

Body:
Had to revisit this as we couldn't figure out why we were stuck on node 8 even though we set it to node 12 in the EB UI. Seems that if you install a global node it overrides the version setting. Instead of installing a global node, this uses the Elastic Beanstalk node install and adds it to the path. You have to add the PATH in again at the start of your yarn install script but it seems to be the least invasive way to use yarn.

content: |
  #!/usr/bin/env bash
  set -euxo pipefail

  EB_NODE_VERSION=$(/opt/elasticbeanstalk/bin/get-config optionsettings -n aws:elasticbeanstalk:container:nodejs -o NodeVersion)
  echo "EB node version: $(EB_NODE_VERSION)"

  # Make sure Node binaries can be found (required to run npm).
  # And this lets us invoke npm more simply too.
  export PATH=/opt/elasticbeanstalk/node-install/node-v$EB_NODE_VERSION-linux-x64/bin:$PATH

  if yarn -v; then
    echo 'Yarn already installed.'
  else
    echo 'Installing yarn...'
    npm install yarn -g
  fi


答: You cannot return a boolean in that guard, because opening modal is not enough to define the outcome it should give. You have to wait for user input, which means that your guard canDeactivate should either return a Promise or an Observable. Unfortunately your current modal dialog is too simple to support that use case. Basically you want to have something like .afterClosed() which returns Promise<boolean> or Observable<boolean> then when your user clicks yes/no you have to resolve a promise or emit a value into a subject and complete it. Then you can easily just return the result of .afterClosed() from your guard. But you would need to refactor your service and your modal for that. Of course you can have afterClosed() as a method on the modal component, but you don't want to expose all its methods to the guard or whatever would use it, so a good practice would be to introduce a DialogRef which would only expose what you want to be exposed. But why reinvent the wheel if this has been already solved? There is an amazing angular module called @angular/cdk which you can use to create a very smart modal dialog with low effort. You can check this article.

Title: Angular CDK Overlay Module: CanDeactivateGuard should launch custom modal


问:
python - is there a way to use list comprehension to create a list based on the extracted common indexes of sublists?
I am trying to figure out a clean way to get the elements at the same index of each sublist and create a new list based on those extracted elements, so first I would like a sublist containing element 0 of each earlier sublist, then same the same for element 1, 2 etc. At the moment I am using the following code to get the results I want:

```<code>lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
approach_1 = []

for i, item in enumerate(lst[0]):
    approach_1.append([item, lst[1][i], lst[2][i], lst[3][i]])
</code>```

which gives me

```<code>approach_1 = [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]
</code>```

The results are what I am looking for but is there a way for me to achieve this in one line? I am able to use the following for one element:

```<code>approach_2 = [x[0] for x in lst]
</code>```

Is there anything similar to this that would return the same results as approach_1?

答:
```<code>list( zip( lst[0], lst[1], lst[2], lst[3] ) )
</code>```

or if you want each element to be a list instead of a tuple, you can do this

```<code>result = [ list(x) for x in list( zip( lst[0], lst[1], lst[2], lst[3] ) ) ]
</code>```

Body:
I am trying to figure out a clean way to get the elements at the same index of each sublist and create a new list based on those extracted elements, so first I would like a sublist containing element 0 of each earlier sublist, then same the same for element 1, 2 etc. At the moment I am using the following code to get the results I want:

lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
approach_1 = []

for i, item in enumerate(lst[0]):
    approach_1.append([item, lst[1][i], lst[2][i], lst[3][i]])

which gives me

approach_1 = [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]

The results are what I am looking for but is there a way for me to achieve this in one line? I am able to use the following for one element:

approach_2 = [x[0] for x in lst]

Is there anything similar to this that would return the same results as approach_1?

Body:
list( zip( lst[0], lst[1], lst[2], lst[3] ) )

or if you want each element to be a list instead of a tuple, you can do this

result = [ list(x) for x in list( zip( lst[0], lst[1], lst[2], lst[3] ) ) ]


问:
Python Web Framework for Small Team
I have 4 days off and I will use this time to rewrite our RoR (Ruby on Rails) Application in a python web framework just for fun ;-] (and why not make the switch, RoR is great but keep changing all the time, can be exhausting.)

I don't know the python web framework very well, I've glad web.py, django, cherry.py, pylons/pyramid and few others. Our requirements are (put everything can be irrelevant) :

MVC (Strict or not)

Small Team (2-3 people included one designer)

Fun to use

REST support

Multilevel caching (DB query, page cache)

Nginx Support (X-Accel-Redirect File Download)

Heavy traffic (1,200,000 ~ views)

Urls rewrting (Multi-domains support not only subdomain)

Not a problem if it's not hype

Not a problem if there is no plugins

Either SQL or NOSQL (can be fun to try NOSQL)

So what you would advise ?

答: I don't think you can go wrong with any of the major web frameworks. Personally I've used Django the most and would lean that way, the ORM is really great and it's philosophies/design are closely aligned with my own personal preference. However, if you wanted to go a different route, bottle is a really fun lightweight microframework, I've found it a pleasure to develop with. If you want to go the NoSQL route, MongoDB has great Python support. PyMongo is excellent (and the recommended way to use MongoDB from Python), MongoEngine is a nice little ORM (if you care for that sort of thing).</p>

Title: Python Web Framework for Small Team


问:
React Native - React Navigation Deep Link Does not work on Android
currently i'm working on React Native Android Project, I want to use deep link on some page.
But somehow the link always redirect to login page instead of signup page.

already tried adb shell am start -W -a android.intent.action.VIEW -d "myapp://mobile/signup"

i am afraid incorrect in nested navigation.

or should I put path on all screen?  because i dont put it all

"react-navigation": "^3.11.1"
"react-native": "0.60.4"

router.js

```<code>const prefix = 'myapp://'
<Navigation ref={(comp) => (this.navigator = comp)} uriPrefix={prefix} />
</code>```

navigation/index.js

```<code>const LoginStack = createStackNavigator(
    {
      LoginScreen: { screen: LoginScreen },
      SignUpScreen: {
        screen: SignUpScreen,
        path: 'signup',
       },
      ForgotPasswordScreen: { screen: ForgotPasswordScreen },
    },
    {
      navigationOptions: { tabBarVisible: false },
    },
    {
      mode: "modal",
      header: null,
      transitionConfig: () => TransitionConfig,
    }
);

const AppNavigator = createBottomTabNavigator(
    {
      Default: {
        screen: HomeStack,
        navigationOptions: {
          tabBarIcon: ({ tintColor }) => (
            <TabBarIcon icon={Images.Icon} tintColor={tintColor} />
          ),
        },
      },
      LoginStack: {
        screen: LoginStack,
        path: 'login',
      },
    },
    {
      initialRouteName: 'Default',
      tabBarComponent: TabBar,
      tabBarPosition: "bottom",
      swipeEnabled: false,
      animationEnabled: false,
      tabBarOptions: {
        showIcon: true,
        showLabel: true,
        activeTintColor: Color.tabbarTint,
        inactiveTintColor: Color.tabbarColor,
      },
      lazy: true,
      navigationOptions: {
        gestureDirection: I18nManager.isRTL ? "inverted" : "default",
      },
    }
);

const AuthNavigator = createStackNavigator(
  {
    LoginScreen: { screen: LoginScreen },
    SignUpScreen: {
      screen: SignUpScreen,
      path: 'signup',
    },
  },
  {
    mode: "modal",
    header: null,
    transitionConfig: () => TransitionConfig,
  }
);

export default createAppContainer(
  Config.Login.RequiredLogin
    ? createSwitchNavigator(
        {
          AuthLoading: AuthLoadingScreen,
          App: AppNavigator,
          Auth: AuthNavigator,
        },
        {
          initialRouteName: "AuthLoading",
        }
      )
    : AppNavigator
);
</code>```

AndroidManifest.xml

```<code><activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:exported="true"
        android:launchMode="singleTask"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myapp" android:host="mobile" />
        </intent-filter>
      </activity>
</code>```

any help would be appreciated :)

答:
I had the same problem with react-navigation 4.x. so I ended up first navigate to screen that I wanted to open in deep linking then open url. In your case if you want to go to specific url page in login and after some process navigate to sign up, you should first navigate to SignUp then go to url. The code bellow shows my button which open url

```<code>const goToWebPage = () => {
    props.navigation.navigate('SignUp');
    Linking.canOpenURL(`${paymentUrl}\/${id}`).then(supported => {
        if (supported) {
           Linking.openURL(`${paymentUrl}\/${id}`);
        }
    });
 }
</code>```

the main problem I think is in createSwitchNavigator.
before using my approch, use https://medium.com/react-native-training/deep-linking-your-react-native-app-d87c39a1ad5e approch and disable deep linking by adding enableURLHandling={false} to Navigator and remove uriPrefix={prefix} so if it wont work, use my approch.

Body:
currently i'm working on React Native Android Project, I want to use deep link on some page.
But somehow the link always redirect to login page instead of signup page.

already tried adb shell am start -W -a android.intent.action.VIEW -d "myapp://mobile/signup"

i am afraid incorrect in nested navigation.

or should I put path on all screen?  because i dont put it all

"react-navigation": "^3.11.1"
"react-native": "0.60.4"

router.js

const prefix = 'myapp://'
<Navigation ref={(comp) => (this.navigator = comp)} uriPrefix={prefix} />

navigation/index.js

const LoginStack = createStackNavigator(
    {
      LoginScreen: { screen: LoginScreen },
      SignUpScreen: {
        screen: SignUpScreen,
        path: 'signup',
       },
      ForgotPasswordScreen: { screen: ForgotPasswordScreen },
    },
    {
      navigationOptions: { tabBarVisible: false },
    },
    {
      mode: "modal",
      header: null,
      transitionConfig: () => TransitionConfig,
    }
);

const AppNavigator = createBottomTabNavigator(
    {
      Default: {
        screen: HomeStack,
        navigationOptions: {
          tabBarIcon: ({ tintColor }) => (
            <TabBarIcon icon={Images.Icon} tintColor={tintColor} />
          ),
        },
      },
      LoginStack: {
        screen: LoginStack,
        path: 'login',
      },
    },
    {
      initialRouteName: 'Default',
      tabBarComponent: TabBar,
      tabBarPosition: "bottom",
      swipeEnabled: false,
      animationEnabled: false,
      tabBarOptions: {
        showIcon: true,
        showLabel: true,
        activeTintColor: Color.tabbarTint,
        inactiveTintColor: Color.tabbarColor,
      },
      lazy: true,
      navigationOptions: {
        gestureDirection: I18nManager.isRTL ? "inverted" : "default",
      },
    }
);

const AuthNavigator = createStackNavigator(
  {
    LoginScreen: { screen: LoginScreen },
    SignUpScreen: {
      screen: SignUpScreen,
      path: 'signup',
    },
  },
  {
    mode: "modal",
    header: null,
    transitionConfig: () => TransitionConfig,
  }
);

export default createAppContainer(
  Config.Login.RequiredLogin
    ? createSwitchNavigator(
        {
          AuthLoading: AuthLoadingScreen,
          App: AppNavigator,
          Auth: AuthNavigator,
        },
        {
          initialRouteName: "AuthLoading",
        }
      )
    : AppNavigator
);

AndroidManifest.xml

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:exported="true"
        android:launchMode="singleTask"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myapp" android:host="mobile" />
        </intent-filter>
      </activity>

any help would be appreciated :)

Body:
I had the same problem with react-navigation 4.x. so I ended up first navigate to screen that I wanted to open in deep linking then open url. In your case if you want to go to specific url page in login and after some process navigate to sign up, you should first navigate to SignUp then go to url. The code bellow shows my button which open url

const goToWebPage = () => {
    props.navigation.navigate('SignUp');
    Linking.canOpenURL(`${paymentUrl}\/${id}`).then(supported => {
        if (supported) {
           Linking.openURL(`${paymentUrl}\/${id}`);
        }
    });
 }

the main problem I think is in createSwitchNavigator.
before using my approch, use https://medium.com/react-native-training/deep-linking-your-react-native-app-d87c39a1ad5e approch and disable deep linking by adding enableURLHandling={false} to Navigator and remove uriPrefix={prefix} so if it wont work, use my approch.


Title: How to add value step by step in list

Body:
I want to add [13178.0, 13178.0, 14130.0, 15082.0, 15082.0, 15082.0, 16034.0, 16034.0, 16986.0, 16986.0, 16986.0] in a list, so I use

pred_set.append([13178.0, 13178.0, 14130.0, 15082.0, 15082.0, 15082.0, 16034.0, 16034.0, 16986.0, 16986.0, 16986.0])

however, the result shows they are in same row:

I want to them in different row, like the data below them, how to do it?

Body:
Use extend:

l = [13005]
l.extend([13178.0, 13178.0, 14130.0, 15082.0, 15082.0, 15082.0, 16034.0, 16034.0, 16986.0, 16986.0, 16986.0])
l

Output:

[13005,
 13178.0,
 13178.0,
 14130.0,
 15082.0,
 15082.0,
 15082.0,
 16034.0,
 16034.0,
 16986.0,
 16986.0,
 16986.0]


问:
ModuleNotFoundError: No module named 'sklearn.externals.six'
I keep getting the error

```<code>ModuleNotFoundError: No module named 'sklearn.externals.six'
</code>```

when running the code below:

```<code>from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import pandas as pd
import mglearn
import numpy as np
from IPython.display import display
import matplotlib as pl
import sklearn

iris_dataset = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state=0)
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
pd.plotting.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o', hist_kwds={'bins':20}, s=60, alpha=.8, cmap=mglearn.cm3)
</code>```

Is there a module I haven't imported or installed?

答:
I was able to run your code by simply performing these commands:

```<code>C:\Windows\system32>pip install sklearn
Collecting sklearn
  Downloading https://files.pythonhosted.org/packages/1e/7a/dbb3be0ce9bd5c8b7e3d87328e79063f8b263b2b1bfa4774cb1147bfcd3f/sklearn-0.0.tar.gz
Collecting scikit-learn (from sklearn)
  Downloading https://files.pythonhosted.org/packages/7e/e5/888491b7e2c16718a68dfd8498325e8927003410b2d19ba255d8751338a5/scikit_learn-0.23.1-cp38-cp38-win_amd64.whl (6.8MB)
     |████████████████████████████████| 6.8MB 2.2MB/s
Collecting joblib>=0.11 (from scikit-learn->sklearn)
  Downloading https://files.pythonhosted.org/packages/b8/a6/d1a816b89aa1e9e96bcb298eb1ee1854f21662ebc6d55ffa3d7b3b50122b/joblib-0.15.1-py3-none-any.whl (298kB)
     |████████████████████████████████| 307kB 3.2MB/s
Collecting threadpoolctl>=2.0.0 (from scikit-learn->sklearn)
  Downloading https://files.pythonhosted.org/packages/db/09/cab2f398e28e9f183714afde872b2ce23629f5833e467b151f18e1e08908/threadpoolctl-2.0.0-py3-none-any.whl
Requirement already satisfied: numpy>=1.13.3 in c:\python38\lib\site-packages (from scikit-learn->sklearn) (1.18.4)
Collecting scipy>=0.19.1 (from scikit-learn->sklearn)
  Downloading https://files.pythonhosted.org/packages/f8/b9/98a75846fdda3756ce75705b518dde4c599ba419d11415ce3fe1ebc4a885/scipy-1.4.1-cp38-cp38-win_amd64.whl (31.0MB)
     |████████████████████████████████| 31.0MB 1.1MB/s
Installing collected packages: joblib, threadpoolctl, scipy, scikit-learn, sklearn
  Running setup.py install for sklearn ... done
Successfully installed joblib-0.15.1 scikit-learn-0.23.1 scipy-1.4.1 sklearn-0.0 threadpoolctl-2.0.0
WARNING: You are using pip version 19.2.3, however version 20.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:Windows\system32>pip install mglearn
Collecting mglearn
  Downloading https://files.pythonhosted.org/packages/65/38/8aced26fce0b2ae82c3c87cd3b6105f38ca6d9d51704ecc44aa54473e6b9/mglearn-0.1.9.tar.gz (540kB)
     |████████████████████████████████| 542kB 1.3MB/s
Requirement already satisfied: numpy in c:\python38\lib\site-packages (from mglearn) (1.18.4)
Requirement already satisfied: matplotlib in c:\python38\lib\site-packages (from mglearn) (3.2.1)
Requirement already satisfied: scikit-learn in c:\python38\lib\site-packages (from mglearn) (0.23.1)
Requirement already satisfied: pandas in c:\python38\lib\site-packages (from mglearn) (1.0.3)
Collecting pillow (from mglearn)
  Downloading https://files.pythonhosted.org/packages/91/9e/1b45eed618c35010d8cc3ba57f12baf09af37054665b7cdf79aafa93ed75/Pillow-7.1.2-cp38-cp38-win_amd64.whl (2.0MB)
     |████████████████████████████████| 2.0MB 2.2MB/s
Requirement already satisfied: cycler in c:\python38\lib\site-packages (from mglearn) (0.10.0)
Collecting imageio (from mglearn)
  Downloading https://files.pythonhosted.org/packages/4c/2b/9dd19644f871b10f7e32eb2dbd6b45149c350b4d5f2893e091b882e03ab7/imageio-2.8.0-py3-none-any.whl (3.3MB)
     |████████████████████████████████| 3.3MB 126kB/s
Requirement already satisfied: joblib in c:\python38\lib\site-packages (from mglearn) (0.15.1)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\python38\lib\site-packages (from matplotlib->mglearn) (2.4.7)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\python38\lib\site-packages (from matplotlib->mglearn) (1.2.0)
Requirement already satisfied: python-dateutil>=2.1 in c:\python38\lib\site-packages (from matplotlib->mglearn) (2.8.1)
Requirement already satisfied: scipy>=0.19.1 in c:\python38\lib\site-packages (from scikit-learn->mglearn) (1.4.1)
Requirement already satisfied: threadpoolctl>=2.0.0 in c:\python38\lib\site-packages (from scikit-learn->mglearn) (2.0.0)
Requirement already satisfied: pytz>=2017.2 in c:\python38\lib\site-packages (from pandas->mglearn) (2020.1)
Requirement already satisfied: six in c:\python38\lib\site-packages (from cycler->mglearn) (1.14.0)
Installing collected packages: pillow, imageio, mglearn
  Running setup.py install for mglearn ... done
Successfully installed imageio-2.8.0 mglearn-0.1.9 pillow-7.1.2
WARNING: You are using pip version 19.2.3, however version 20.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
</code>```

Please note that I have this version of Python on my system:

```<code>C:\Windows\system32>python --version
Python 3.8.3
</code>```

Here are the versions of sklearn and mglearn on my system:

```<code>C:\Windows\system32>pip list
...
mglearn           0.1.9
...
scikit-learn      0.23.1
...
</code>```

Body:
I keep getting the error

ModuleNotFoundError: No module named 'sklearn.externals.six'

when running the code below:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import pandas as pd
import mglearn
import numpy as np
from IPython.display import display
import matplotlib as pl
import sklearn

iris_dataset = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state=0)
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
pd.plotting.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o', hist_kwds={'bins':20}, s=60, alpha=.8, cmap=mglearn.cm3)

Is there a module I haven't imported or installed?

Body:
I was able to run your code by simply performing these commands:

C:\Windows\system32>pip install sklearn
Collecting sklearn
  Downloading https://files.pythonhosted.org/packages/1e/7a/dbb3be0ce9bd5c8b7e3d87328e79063f8b263b2b1bfa4774cb1147bfcd3f/sklearn-0.0.tar.gz
Collecting scikit-learn (from sklearn)
  Downloading https://files.pythonhosted.org/packages/7e/e5/888491b7e2c16718a68dfd8498325e8927003410b2d19ba255d8751338a5/scikit_learn-0.23.1-cp38-cp38-win_amd64.whl (6.8MB)
     |████████████████████████████████| 6.8MB 2.2MB/s
Collecting joblib>=0.11 (from scikit-learn->sklearn)
  Downloading https://files.pythonhosted.org/packages/b8/a6/d1a816b89aa1e9e96bcb298eb1ee1854f21662ebc6d55ffa3d7b3b50122b/joblib-0.15.1-py3-none-any.whl (298kB)
     |████████████████████████████████| 307kB 3.2MB/s
Collecting threadpoolctl>=2.0.0 (from scikit-learn->sklearn)
  Downloading https://files.pythonhosted.org/packages/db/09/cab2f398e28e9f183714afde872b2ce23629f5833e467b151f18e1e08908/threadpoolctl-2.0.0-py3-none-any.whl
Requirement already satisfied: numpy>=1.13.3 in c:\python38\lib\site-packages (from scikit-learn->sklearn) (1.18.4)
Collecting scipy>=0.19.1 (from scikit-learn->sklearn)
  Downloading https://files.pythonhosted.org/packages/f8/b9/98a75846fdda3756ce75705b518dde4c599ba419d11415ce3fe1ebc4a885/scipy-1.4.1-cp38-cp38-win_amd64.whl (31.0MB)
     |████████████████████████████████| 31.0MB 1.1MB/s
Installing collected packages: joblib, threadpoolctl, scipy, scikit-learn, sklearn
  Running setup.py install for sklearn ... done
Successfully installed joblib-0.15.1 scikit-learn-0.23.1 scipy-1.4.1 sklearn-0.0 threadpoolctl-2.0.0
WARNING: You are using pip version 19.2.3, however version 20.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:Windows\system32>pip install mglearn
Collecting mglearn
  Downloading https://files.pythonhosted.org/packages/65/38/8aced26fce0b2ae82c3c87cd3b6105f38ca6d9d51704ecc44aa54473e6b9/mglearn-0.1.9.tar.gz (540kB)
     |████████████████████████████████| 542kB 1.3MB/s
Requirement already satisfied: numpy in c:\python38\lib\site-packages (from mglearn) (1.18.4)
Requirement already satisfied: matplotlib in c:\python38\lib\site-packages (from mglearn) (3.2.1)
Requirement already satisfied: scikit-learn in c:\python38\lib\site-packages (from mglearn) (0.23.1)
Requirement already satisfied: pandas in c:\python38\lib\site-packages (from mglearn) (1.0.3)
Collecting pillow (from mglearn)
  Downloading https://files.pythonhosted.org/packages/91/9e/1b45eed618c35010d8cc3ba57f12baf09af37054665b7cdf79aafa93ed75/Pillow-7.1.2-cp38-cp38-win_amd64.whl (2.0MB)
     |████████████████████████████████| 2.0MB 2.2MB/s
Requirement already satisfied: cycler in c:\python38\lib\site-packages (from mglearn) (0.10.0)
Collecting imageio (from mglearn)
  Downloading https://files.pythonhosted.org/packages/4c/2b/9dd19644f871b10f7e32eb2dbd6b45149c350b4d5f2893e091b882e03ab7/imageio-2.8.0-py3-none-any.whl (3.3MB)
     |████████████████████████████████| 3.3MB 126kB/s
Requirement already satisfied: joblib in c:\python38\lib\site-packages (from mglearn) (0.15.1)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\python38\lib\site-packages (from matplotlib->mglearn) (2.4.7)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\python38\lib\site-packages (from matplotlib->mglearn) (1.2.0)
Requirement already satisfied: python-dateutil>=2.1 in c:\python38\lib\site-packages (from matplotlib->mglearn) (2.8.1)
Requirement already satisfied: scipy>=0.19.1 in c:\python38\lib\site-packages (from scikit-learn->mglearn) (1.4.1)
Requirement already satisfied: threadpoolctl>=2.0.0 in c:\python38\lib\site-packages (from scikit-learn->mglearn) (2.0.0)
Requirement already satisfied: pytz>=2017.2 in c:\python38\lib\site-packages (from pandas->mglearn) (2020.1)
Requirement already satisfied: six in c:\python38\lib\site-packages (from cycler->mglearn) (1.14.0)
Installing collected packages: pillow, imageio, mglearn
  Running setup.py install for mglearn ... done
Successfully installed imageio-2.8.0 mglearn-0.1.9 pillow-7.1.2
WARNING: You are using pip version 19.2.3, however version 20.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

Please note that I have this version of Python on my system:

C:\Windows\system32>python --version
Python 3.8.3

Here are the versions of sklearn and mglearn on my system:

C:\Windows\system32>pip list
...
mglearn           0.1.9
...
scikit-learn      0.23.1
...


问:
Read() in c: Reading extra chars
I am currently writing a program that will read a file according to a user given buffer, will write that to an output file, and will continue doing that until the file is done.  However, right now my output file has extra characters then it should have when compared to the original file. I think it has something to do with how read and write do not always return the number of bytes that is requested. I am unsure how to fix this.

Right now I just have a simple while loop:

```<code>while(read(inFD, buff, buf)!= 0)

   write(outFD, buff, buf);
</code>```

buf is the user given buffer.

Thanks if you can help!

答:
read manual reads: "On success, the number of bytes read is returned".

You are ignoring the number returned; instead you are assuming buf bytes were read. In result, your output file size will be a multiple of buf.

Title: Read() in c: Reading extra chars

Body:
I am currently writing a program that will read a file according to a user given buffer, will write that to an output file, and will continue doing that until the file is done.  However, right now my output file has extra characters then it should have when compared to the original file. I think it has something to do with how read and write do not always return the number of bytes that is requested. I am unsure how to fix this.

Right now I just have a simple while loop:

while(read(inFD, buff, buf)!= 0)

   write(outFD, buff, buf);

buf is the user given buffer.

Thanks if you can help!


问:
How do I get the desired grid layout in bootstrap
I've been plugging away at this for some time and I get close to the desired output but there's always an issue with centering. It's the thumbnail charts to the right that I can seem to get aligned in a square as shown in the attached figure. I know that my understanding of div code isn't where it should be and that's where I'm sure my issues stem from. Any help would be most appreciated.

```<code><div class="container-fluid">
    <div class="row bg-secondary text-light">
        <div class="col-sm-12">

  </div>

  <div class="container-fluid">
    <div class="row">
        <div class="col-sm-3 bg-secondary text-light">
            <div>
              <h4><b>Project Summary</b></h4>
                <p>Here is  bunch of that doesn't mean anything for the purposes of sharing this code
                  latitude location. The adsfasdf includes analysis of asfdd, fdfdf sdsd, dfdf Index
                  and Humidity. These data are then asdfasdfasdfas fsadf asdf asdf asdfof latitude. The data was
                  drawn from other stff adsfasdfasdfasdfadsfasdfasdfasdfsdfasdf  adsfasdfdfadsfadsfsdfsdf
                  using Python API calls to that site, then stored in CSV files and integrated into Panda Dataframes and plotted
                  with Matplotlib.<br></p>

                 <p></p>  asfasdf asdf d d fsdf sadf d d adsf asdf sd d d asdf d df sd fadsa fsd f
                </p>
            </div>
        </div>
        <div class="col-sm-9">
            <div class="row">
                <div class="col-sm-6">
                 <br>
                    <img src="fig1.png" alt="Bootcamp" width="500" height="500">"

                </div>

            <div class="col-sm-3 bg-secondary text-light">
              <div class="row">
                  <h5>Visualizations</h5>

            <div class="col-sm-3 bg-secondary text-light justify-content-cente">
            </div>
                  <img src="Fig1.png" class="img-thumbnail" alt="Temp v Alt" width="195" height="236">
                  <img src="Fig2.png" class="img-thumbnail" alt="Temp v Alt" width="195" height="236">

                  <div class="col-sm-3 bg-secondary text-light">
                  </div>
                        <img src="Fig3.png" class="img-thumbnail" alt="Temp v Alt" width="195" height="236">
                        <img src="Fig4.png" class="img-thumbnail" alt="Temp v Alt" width="195" height="236">
            </div>

            </div>
        </div>
        <!-- Add second row -->
        <br>
        <div class="col-sm-12 bg-secondary text-light">
            <div>
                <p>Text 2</p>
            </div>
        </div>
        <div class="col-sm-12 bg-secondary text-light">
            <div>

            </div>
        </div>

        <div class="col-sm-12 row justify-content-center">
            <div class="row">
                <div class="col-sm-12">

                </div>
                <div class="col-sm-1bg-secondary text-light">

                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>
</code>```

答:
Here is the solution in Bootstrap:

* {
  margin: 0;
  padding: 0;
  border: 0;
}

.boxes-left,
.box-centre,
.boxes-right {
  padding-top: 10vh;
  height: 90vh;
}

.box1,
.box2 {
  width: 100%;
  height: 50%;
}

.box1 {
  background: red;
}

.box2 {
  background: green;
}

.box-middle {
  background: blue;
  width: 100%;
  height: 100%;
}

.boxes-right {
  height: 100%;
  position: relative;
}

.title {
  text-align: center;
}

.box-r {
  float: left;
  width: 48%;
  height: 200px;
  margin: 1%;
  /* margin: 5%; */
  background: orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
    />
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container-fluid">
      <div class="col-md-2 boxes-left">
        <div class="box1"></div>
        <div class="box2"></div>
      </div>

      <div class="col-md-6 box-centre">
        <div class="box-middle"></div>
      </div>

      <div class="col-md-4 boxes-right">
        <div class="col-md-12 title">
          <h1>Your Text Here</h1>
        </div>
        <div class="col-md-6 box-r"></div>
        <div class="col-md-6 box-r"></div>
        <div class="col-md-6 box-r"></div>
        <div class="col-md-6 box-r"></div>
      </div>
    </div>
  </body>
</html></code>```

Body:
I've been plugging away at this for some time and I get close to the desired output but there's always an issue with centering. It's the thumbnail charts to the right that I can seem to get aligned in a square as shown in the attached figure. I know that my understanding of div code isn't where it should be and that's where I'm sure my issues stem from. Any help would be most appreciated.

Project Summary

Here is  bunch of that doesn't mean anything for the purposes of sharing this code
                  latitude location. The adsfasdf includes analysis of asfdd, fdfdf sdsd, dfdf Index
                  and Humidity. These data are then asdfasdfasdfas fsadf asdf asdf asdfof latitude. The data was
                  drawn from other stff adsfasdfasdfasdfadsfasdfasdfasdfsdfasdf  adsfasdfdfadsfadsfsdfsdf
                  using Python API calls to that site, then stored in CSV files and integrated into Panda Dataframes and plotted
                  with Matplotlib.

  asfasdf asdf d d fsdf sadf d d adsf asdf sd d d asdf d df sd fadsa fsd f

                    "

Visualizations

Text 2

Body:
Here is the solution in Bootstrap:

* {
  margin: 0;
  padding: 0;
  border: 0;
}

.boxes-left,
.box-centre,
.boxes-right {
  padding-top: 10vh;
  height: 90vh;
}

.box1,
.box2 {
  width: 100%;
  height: 50%;
}

.box1 {
  background: red;
}

.box2 {
  background: green;
}

.box-middle {
  background: blue;
  width: 100%;
  height: 100%;
}

.boxes-right {
  height: 100%;
  position: relative;
}

.title {
  text-align: center;
}

.box-r {
  float: left;
  width: 48%;
  height: 200px;
  margin: 1%;
  /* margin: 5%; */
  background: orange;
}

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
    />
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container-fluid">
      <div class="col-md-2 boxes-left">
        <div class="box1"></div>
        <div class="box2"></div>
      </div>

      <div class="col-md-6 box-centre">
        <div class="box-middle"></div>
      </div>

      <div class="col-md-4 boxes-right">
        <div class="col-md-12 title">
          <h1>Your Text Here</h1>
        </div>
        <div class="col-md-6 box-r"></div>
        <div class="col-md-6 box-r"></div>
        <div class="col-md-6 box-r"></div>
        <div class="col-md-6 box-r"></div>
      </div>
    </div>
  </body>
</html>


问:
Boto3 S3 Bucket Lifecycle Policy - Delete folders and files after so many days
I have a use case where I need to remove content from S3 buckets after 30 days without question. Using Boto3 I'd like to set a lifecycle policy on the S3 bucket itself to clear out the files and folders rather than having to manually run a script every so often. I've looked through the S3 documentation and I'm not seeing where the content can actually be specified to be deleted. I see where I can transfer that content to different storage tiers but that's it.

I'm referring to the documentation here:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.BucketLifecycle.put

答: In that documentation the "Expiration" and "NoncurrentVersionExpiration" are the actions that delete content (whereas "Transition"/"NoncurrentVersionTransition" are the ones to transition objects to a different storage, so you shouldn't include them in the configuration). The "Prefix" then identifies the objects to delete.</p>


问:
Is there a way change an array to a string, split the values at a comma, and join each value via a new line?
I am writing a recursive function that prints an org chart. When logging, this function displays the hierarchy of the chart by adding spaces to the beginning of "subKeys".

Problem:
I am having trouble logging the array as a string and splitting the array and joining it with "\n".

Question:
Is there a way to implement .toString().split(",").join("\n") to results?

I've tried return results.toString().split(",").join("\n") under // Base case and have been receiving a TypeError, TypeError: subKeys.map is not a function.

```<code>const displayOrgChart = (orgChart) => {

  let results = [];

  // General case
  for (let member in orgChart) {
    if (typeof orgChart[member] === "object") {
      let subKeys = displayOrgChart(orgChart[member]);
      results = results.concat(subKeys.map(subKey => {
        return "  " + subKey;
      }))
    } else {
      results.push(orgChart[member]);
    }
  }

  // Base case
  return results
};

console.log(displayOrgChart(orgChart));
</code>```

Array:

EDITED (5/28 2:52 pm): From object to array.

```<code>const orgChart = [
  {
    0: {
      name: "Zuckerberg",
      children: {
        0: {
          name: "Schroepfer",
          children: {
            0: {
              name: "Bosworth",
              children: {
                0: {
                  name: "Steve",
                },
                1: {
                  name: "Kyle",
                },
                2: {
                  name: "Andra",
                },
              },
            },
            1: {
              name: "Zhao",
              children: {
                0: {
                  name: "Richie",
                },
                1: {
                  name: "Sofia",
                },
                2: {
                  name: "Jen",
                },
              },
            },
          },
        },
        1: {
          name: "Schrage",
          children: {
            0: {
              name: "VanDyck",
              children: {
                0: {
                  name: "Sabrina",
                },
                1: {
                  name: "Michelle",
                },
                2: {
                  name: "Josh",
                },
              },
            },
            1: {
              name: "Swain",
              children: {
                0: {
                  name: "Blanch",
                },
                1: {
                  name: "Tom",
                },
                2: {
                  name: "Joe",
                },
              },
            },
          },
        },
        2: {
          name: "Sandberg",
          children: {
            0: {
              name: "Goler",
              children: {
                0: {
                  name: "Eddie",
                },
                1: {
                  name: "Julie",
                },
                2: {
                  name: "Annie",
                },
              },
            },
            1: {
              name: "Hernandez",
              children: {
                0: {
                  name: "Rowi",
                },
                1: {
                  name: "Inga",
                },
                2: {
                  name: "Morgan",
                },
              },
            },
            2: {
              name: "Moissinac",
              children: {
                0: {
                  name: "Amy",
                },
                1: {
                  name: "Chuck",
                },
                2: {
                  name: "Vinni",
                },
              },
            },
            3: {
              name: "Kelley",
              children: {
                0: {
                  name: "Eric",
                },
                1: {
                  name: "Ana",
                },
                2: {
                  name: "Wes",
                },
              },
            },
          },
        },
      },
    },
  },
];
</code>```

Current console log:

```<code>[
  '    Zuckerberg',
  '        Schroepfer',
  '            Bosworth',
  '                Steve',
  '                Kyle',
  '                Andra',
  '            Zhao',
  '                Richie',
  '                Sofia',
  '                Jen',
  '        Schrage',
  '            VanDyck',
  '                Sabrina',
  '                Michelle',
  '                Josh',
  '            Swain',
  '                Blanch',
  '                Tom',
  '                Joe',
  '        Sandberg',
  '            Goler',
  '                Eddie',
  '                Julie',
  '                Annie',
  '            Hernandez',
  '                Rowi',
  '                Inga',
  '                Morgan',
  '            Moissinac',
  '                Amy',
  '                Chuck',
  '                Vinni',
  '            Kelley',
  '                Eric',
  '                Ana',
  '                Wes'
]
</code>```

答:
Code is a little more complicated than it needs to be. Just using a foreach on the children to call and using a variable to maintain the indent will help.

const orgChart = {
  0: {
    name: "Zuckerberg",
    children: {
      0: {
        name: "Schroepfer",
        children: {
          0: {
            name: "Bosworth",
            children: {
              0: {
                name: "Steve",
              },
              1: {
                name: "Kyle",
              },
              2: {
                name: "Andra",
              },
            },
          },
          1: {
            name: "Zhao",
            children: {
              0: {
                name: "Richie",
              },
              1: {
                name: "Sofia",
              },
              2: {
                name: "Jen",
              },
            },
          },
        },
      },
      1: {
        name: "Schrage",
        children: {
          0: {
            name: "VanDyck",
            children: {
              0: {
                name: "Sabrina",
              },
              1: {
                name: "Michelle",
              },
              2: {
                name: "Josh",
              },
            },
          },
          1: {
            name: "Swain",
            children: {
              0: {
                name: "Blanch",
              },
              1: {
                name: "Tom",
              },
              2: {
                name: "Joe",
              },
            },
          },
        },
      },
      2: {
        name: "Sandberg",
        children: {
          0: {
            name: "Goler",
            children: {
              0: {
                name: "Eddie",
              },
              1: {
                name: "Julie",
              },
              2: {
                name: "Annie",
              },
            },
          },
          1: {
            name: "Hernandez",
            children: {
              0: {
                name: "Rowi",
              },
              1: {
                name: "Inga",
              },
              2: {
                name: "Morgan",
              },
            },
          },
          2: {
            name: "Moissinac",
            children: {
              0: {
                name: "Amy",
              },
              1: {
                name: "Chuck",
              },
              2: {
                name: "Vinni",
              },
            },
          },
          3: {
            name: "Kelley",
            children: {
              0: {
                name: "Eric",
              },
              1: {
                name: "Ana",
              },
              2: {
                name: "Wes",
              },
            },
          },
        },
      },
    },
  },
};

function generateReport (org) {
  const results = []
  function getData(entry, indent) {
    if (entry.name) results.push(indent + entry.name)
    if (entry.children) {
      Object.values(entry.children).forEach(function(child) {
        indent = indent === undefined ? '' : indent + '   '
        getData(child, indent)
      })
    }
  }
  getData({ children: org })
  return results.join("\n")
}

console.log(generateReport(orgChart))```

Body:
I am writing a recursive function that prints an org chart. When logging, this function displays the hierarchy of the chart by adding spaces to the beginning of "subKeys".

Problem:
I am having trouble logging the array as a string and splitting the array and joining it with "\n".

Question:
Is there a way to implement .toString().split(",").join("\n") to results?

I've tried return results.toString().split(",").join("\n") under // Base case and have been receiving a TypeError, TypeError: subKeys.map is not a function.

const displayOrgChart = (orgChart) => {

  let results = [];

  // General case
  for (let member in orgChart) {
    if (typeof orgChart[member] === "object") {
      let subKeys = displayOrgChart(orgChart[member]);
      results = results.concat(subKeys.map(subKey => {
        return "  " + subKey;
      }))
    } else {
      results.push(orgChart[member]);
    }
  }

  // Base case
  return results
};

console.log(displayOrgChart(orgChart));

Array:

EDITED (5/28 2:52 pm): From object to array.

const orgChart = [
  {
    0: {
      name: "Zuckerberg",
      children: {
        0: {
          name: "Schroepfer",
          children: {
            0: {
              name: "Bosworth",
              children: {
                0: {
                  name: "Steve",
                },
                1: {
                  name: "Kyle",
                },
                2: {
                  name: "Andra",
                },
              },
            },
            1: {
              name: "Zhao",
              children: {
                0: {
                  name: "Richie",
                },
                1: {
                  name: "Sofia",
                },
                2: {
                  name: "Jen",
                },
              },
            },
          },
        },
        1: {
          name: "Schrage",
          children: {
            0: {
              name: "VanDyck",
              children: {
                0: {
                  name: "Sabrina",
                },
                1: {
                  name: "Michelle",
                },
                2: {
                  name: "Josh",
                },
              },
            },
            1: {
              name: "Swain",
              children: {
                0: {
                  name: "Blanch",
                },
                1: {
                  name: "Tom",
                },
                2: {
                  name: "Joe",
                },
              },
            },
          },
        },
        2: {
          name: "Sandberg",
          children: {
            0: {
              name: "Goler",
              children: {
                0: {
                  name: "Eddie",
                },
                1: {
                  name: "Julie",
                },
                2: {
                  name: "Annie",
                },
              },
            },
            1: {
              name: "Hernandez",
              children: {
                0: {
                  name: "Rowi",
                },
                1: {
                  name: "Inga",
                },
                2: {
                  name: "Morgan",
                },
              },
            },
            2: {
              name: "Moissinac",
              children: {
                0: {
                  name: "Amy",
                },
                1: {
                  name: "Chuck",
                },
                2: {
                  name: "Vinni",
                },
              },
            },
            3: {
              name: "Kelley",
              children: {
                0: {
                  name: "Eric",
                },
                1: {
                  name: "Ana",
                },
                2: {
                  name: "Wes",
                },
              },
            },
          },
        },
      },
    },
  },
];

Current console log:

[
  '    Zuckerberg',
  '        Schroepfer',
  '            Bosworth',
  '                Steve',
  '                Kyle',
  '                Andra',
  '            Zhao',
  '                Richie',
  '                Sofia',
  '                Jen',
  '        Schrage',
  '            VanDyck',
  '                Sabrina',
  '                Michelle',
  '                Josh',
  '            Swain',
  '                Blanch',
  '                Tom',
  '                Joe',
  '        Sandberg',
  '            Goler',
  '                Eddie',
  '                Julie',
  '                Annie',
  '            Hernandez',
  '                Rowi',
  '                Inga',
  '                Morgan',
  '            Moissinac',
  '                Amy',
  '                Chuck',
  '                Vinni',
  '            Kelley',
  '                Eric',
  '                Ana',
  '                Wes'
]