问:
Only print when run as script?
Is there a better way to only print when run as a script, when __name__ == '__main__' ?

I have some scripts that I also import and use parts of.

Something like the below will work but is ugly, and would have to be defined in each script separately:

```<code>def printif(s):
    if globals()['__name__'] == '__main__':
        print (s)
    return
</code>```

I looked briefly at some of python's logging libraries but would prefer a two lighter solution...

edit:

I ended up doing something like this:

```<code># mylog.py
import sys
import logging

log = logging.getLogger()

#default logging level
log.setLevel(logging.WARNING)

log.addHandler(logging.StreamHandler(sys.stdout))
</code>```

And from the script:

```<code>import log from mylog

...
log.info(...)
log.warning(...)
...

if __name__ == '__main__':
    #override when script is run..
    log.setLevel(logger.INFO)
</code>```

This scheme has minimal code duplication, per script log levels, and a project-wide default level...which is exactly what I wanted.

答:
In light of user318904's comment on my other answer, I'll provide an alternative (although this may not work in all cases, it might just be "good enough").

For a separate module:

```<code>import sys

def printif(s):
    if sys.argv[0] != '':
        print (s)
</code>```

Title: Only print when run as script?

Body:
Is there a better way to only print when run as a script, when __name__ == '__main__' ?

I have some scripts that I also import and use parts of.

Something like the below will work but is ugly, and would have to be defined in each script separately:

def printif(s):
    if globals()['__name__'] == '__main__':
        print (s)
    return

I looked briefly at some of python's logging libraries but would prefer a two lighter solution...

edit:

I ended up doing something like this:

# mylog.py
import sys
import logging

log = logging.getLogger()

#default logging level
log.setLevel(logging.WARNING)

log.addHandler(logging.StreamHandler(sys.stdout))

And from the script:

import log from mylog

...
log.info(...)
log.warning(...)
...

if __name__ == '__main__':
    #override when script is run..
    log.setLevel(logger.INFO)

This scheme has minimal code duplication, per script log levels, and a project-wide default level...which is exactly what I wanted.

Body:
In light of user318904's comment on my other answer, I'll provide an alternative (although this may not work in all cases, it might just be "good enough").

For a separate module:

import sys

def printif(s):
    if sys.argv[0] != '':
        print (s)


来源: stackexchange

问:
Host a "non-django app" (a folder with index.html, some .js and .css) in a django website
Short brief:

I have some “non-django html apps” (a folder with a index.html, some .js files and a .css file) and I want to execute them in a django website without touching their code. How can I do it?

How can I make work inside django a non-django app (a folder with an index.html, some .js and .css) withou touching the code of the app?

Details:

I'm building a website with Django where i want to host some Construct3 games (it allows you to create HTML5 through a GUI).

When you export a Construct3 game to HTML it creates the following structure:

```<code>C3App
|_ appmanifest.json
|_ c2runtime.js
|_ data.js
|_ index.html
|_ offline.js
|_ offlineClient.js
|_ register-sw.js
|_ start.js
|_ style.css
|_ sw.js
|_ icons
|   |_ icon1.png
|_ images
    |_ image1.png
</code>```

That is what I have tried:

1.- In my Django website I dropped the C3App in my template folder and created a view and called index.html. As a result i got a blank page with not found errors (404) for: appmanifest.json, icon1.png, style.css, c2runtime.js, start.js and register-sw.js. That is the external files called in index.html.

2.- As that dindn't work, I moved C3App to my static folder and I created a template with the same content of index.html but changing the references.

So I changed this lines:

```<code><link rel="manifest" href="appmanifest.json" />
<link rel="icon" type="image/png" href="icons/icon-512.png" />
<link rel="stylesheet" href="style.css"/>
<script src="c2runtime.js"></script>
<script src="start.js"></script>
<script src="register-sw.js"></script>
</code>```

To this others:

```<code>{% load static %}
<link rel="manifest" href="{% static 'games/C3App/appmanifest.json' %}" />
<link rel="icon" type="image/png" href="{% static 'games/C3App/icons/icon-512.png' %}" />
<link rel="stylesheet" href="{% static 'games/C3App/style.css' %}"/>
<script src="{% static 'games/C3App/c2runtime.js' %}"></script>
<script src="{% static 'games/C3App/start.js' %}"></script>
<script src="{% static 'games/C3App/register-sw.js' %}"></script>
</code>```

After the changes I got 2 not found errors for: data.js and offlineClient.js. Two files called several times in c2runtime.js.

So c2runtime.js needs to be touched too. And this starts to become too dirty, I'm modifying more than one file, in more than one place. So every time I will want to make an update for a game I will need to modify all that files again. Sounds like stupid work and an easy way to introduce bugs.

The perfect scenario would be drag the folder (exported game) and work. Is there a way to do that posible? Any idea?

How can I make work inside django a non-django app (a folder with an index.html, some .js and .css) withou touching the code of the app?

答:
I have some “non-django html apps” (a folder with a index.html, some
  .js files and a .css file) and I want to execute them in a django
  website without touching their code. How can I do it?

There a lot's of ways in which you can, but you shouldn't

How can I make work inside django a non-django app (a folder with an  index.html, some .js and .css) withou touching the code of the app?

As above, if this is a static non django app (or even a dynamic one). Don't mix it with django. It should be the responsibility of the webserver (Nginx, Apache) etc to route the django app related urls to your WSGI server. And to route the non django app urls to whatever that hosts it.

ps:
You should not run the dev server in production as it's unsafe. The nature of your question gives the impression that you maybe doing so.

ContentLicense: CC BY-SA 3.0

Body:
Short brief:

I have some “non-django html apps” (a folder with a index.html, some .js files and a .css file) and I want to execute them in a django website without touching their code. How can I do it?

How can I make work inside django a non-django app (a folder with an index.html, some .js and .css) withou touching the code of the app?

Details:

I'm building a website with Django where i want to host some Construct3 games (it allows you to create HTML5 through a GUI).

When you export a Construct3 game to HTML it creates the following structure:

C3App
|_ appmanifest.json
|_ c2runtime.js
|_ data.js
|_ index.html
|_ offline.js
|_ offlineClient.js
|_ register-sw.js
|_ start.js
|_ style.css
|_ sw.js
|_ icons
|   |_ icon1.png
|_ images
    |_ image1.png

That is what I have tried:

1.- In my Django website I dropped the C3App in my template folder and created a view and called index.html. As a result i got a blank page with not found errors (404) for: appmanifest.json, icon1.png, style.css, c2runtime.js, start.js and register-sw.js. That is the external files called in index.html.

2.- As that dindn't work, I moved C3App to my static folder and I created a template with the same content of index.html but changing the references.

So I changed this lines:

<link rel="manifest" href="appmanifest.json" />
<link rel="icon" type="image/png" href="icons/icon-512.png" />
<link rel="stylesheet" href="style.css"/>

To this others:

{% load static %}
<link rel="manifest" href="{% static 'games/C3App/appmanifest.json' %}" />
<link rel="icon" type="image/png" href="{% static 'games/C3App/icons/icon-512.png' %}" />
<link rel="stylesheet" href="{% static 'games/C3App/style.css' %}"/>

After the changes I got 2 not found errors for: data.js and offlineClient.js. Two files called several times in c2runtime.js.

So c2runtime.js needs to be touched too. And this starts to become too dirty, I'm modifying more than one file, in more than one place. So every time I will want to make an update for a game I will need to modify all that files again. Sounds like stupid work and an easy way to introduce bugs.

The perfect scenario would be drag the folder (exported game) and work. Is there a way to do that posible? Any idea?

How can I make work inside django a non-django app (a folder with an index.html, some .js and .css) withou touching the code of the app?


问:
*ng2For not working and no error messages logged in console
I ran through many questions which had ngFor not working I tried all the suggestions as below, but nothing seemed to work me.

Imported {CommonModule} in my "app.component.ts"

Also tried importing it in my "app.module.ts"

Check if my array is something like this myArray = [ ] an not myArray :[ ];

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FileSelectDirective, FileDropDirective } from 'ng2-file-upload';
import { Ng2DragDropModule } from 'ng2-drag-drop';
import {DndModule} from 'ng2-dnd';

import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { AppConfig } from './app.config';

import { AlertComponent } from './_directives/index';
import { AuthGuard } from './_guards/index';
import { AlertService, AuthenticationService, UserService, SchemaService } from './_services/index';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';
import { UploadComponent } from './upload/index';
import { ReadComponent } from './read/index';
import { DragComponent } from './drag/index';

@NgModule({
    imports: [
        BrowserModule,
        DndModule.forRoot(),
        FormsModule,
        HttpModule,
        routing,
        Ng2DragDropModule
    ],
    declarations: [
        AppComponent,
        AlertComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent,
        FileSelectDirective,
        UploadComponent,
        ReadComponent,
        DragComponent
    ],
    providers: [
        AppConfig,
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        SchemaService
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';
import { CommonModule } from '@angular/common';

@Component({
    moduleId: module.id,
    selector: 'app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css']
})

export class AppComponent { }
</code>```

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { User } from '../_models/index';
import { UserService } from '../_services/index';

@Component({
    moduleId: module.id,
    template: `<h1>{{welcome}}</h1>
                <table class="table">
                    <tr>
                        <th>#</th>
                        <th>Game</th>
                        <th>Platform</th>
                        <th>Release</th>
                    </tr>
                    <tr *ngFor="let game of games; let i = index">
                        <td>{{i + 1}}</td>
                        <td>{{game.game}}</td>
                        <td>{{game.platform}}</td>
                        <td>{{game.release}}</td>
                    </tr>
                </table>`
})

export class HomeComponent implements OnInit {

welcome : string;
    games : [{
        game: string,
        platform : string,
        release : string
    }];

    currentUser: User;
    users: User[] = [];

    constructor(private userService: UserService) {
        this.currentUser = JSON.parse(localStorage.getItem('currentUser'));

        this.welcome = "Display List using ngFor in Angular 2"

        this.games = [{
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        }]
    }

    ngOnInit() {
        this.loadAllUsers();
    }

    deleteUser(_id: string) {
        this.userService.delete(_id).subscribe(() => { this.loadAllUsers() });
    }

    private loadAllUsers() {
        this.userService.getAll().subscribe(users => { this.users = users; });
    }

}
</code>```

Output:

Game    Platform    Release

Elements:

Console Window Screenshot

答:
in home.component.ts

```<code>@Component({
    moduleId: module.id,
selector:'app-home'
    templateUrl: `<h1>{{welcome}}</h1>
})
</code>```

and put above selector in your 'app.component.html',

in app.component.html

```<code><h1>This is app.component.html</h1>
<app-home></app-home>
</code>```

Body:
I ran through many questions which had ngFor not working I tried all the suggestions as below, but nothing seemed to work me.

Imported {CommonModule} in my "app.component.ts"

Also tried importing it in my "app.module.ts"

Check if my array is something like this myArray = [ ] an not myArray :[ ];

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FileSelectDirective, FileDropDirective } from 'ng2-file-upload';
import { Ng2DragDropModule } from 'ng2-drag-drop';
import {DndModule} from 'ng2-dnd';

import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { AppConfig } from './app.config';

import { AlertComponent } from './_directives/index';
import { AuthGuard } from './_guards/index';
import { AlertService, AuthenticationService, UserService, SchemaService } from './_services/index';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';
import { UploadComponent } from './upload/index';
import { ReadComponent } from './read/index';
import { DragComponent } from './drag/index';

@NgModule({
    imports: [
        BrowserModule,
        DndModule.forRoot(),
        FormsModule,
        HttpModule,
        routing,
        Ng2DragDropModule
    ],
    declarations: [
        AppComponent,
        AlertComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent,
        FileSelectDirective,
        UploadComponent,
        ReadComponent,
        DragComponent
    ],
    providers: [
        AppConfig,
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        SchemaService
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';
import { CommonModule } from '@angular/common';

@Component({
    moduleId: module.id,
    selector: 'app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css']
})

export class AppComponent { }

home.component.ts

import { Component, OnInit } from '@angular/core';
import { User } from '../_models/index';
import { UserService } from '../_services/index';

@Component({
    moduleId: module.id,
    template: `
{{welcome}}

                        #
                        Game
                        Platform
                        Release

                        {{i + 1}}
                        {{game.game}}
                        {{game.platform}}
                        {{game.release}}

`
})

export class HomeComponent implements OnInit {

welcome : string;
    games : [{
        game: string,
        platform : string,
        release : string
    }];

    currentUser: User;
    users: User[] = [];

    constructor(private userService: UserService) {
        this.currentUser = JSON.parse(localStorage.getItem('currentUser'));

        this.welcome = "Display List using ngFor in Angular 2"

        this.games = [{
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        }]
    }

    ngOnInit() {
        this.loadAllUsers();
    }

    deleteUser(_id: string) {
        this.userService.delete(_id).subscribe(() => { this.loadAllUsers() });
    }

    private loadAllUsers() {
        this.userService.getAll().subscribe(users => { this.users = users; });
    }

}

Output:

Game    Platform    Release

Elements:

Console Window Screenshot

Body:
in home.component.ts

@Component({
    moduleId: module.id,
selector:'app-home'
    templateUrl: `<h1>{{welcome}}</h1>
})

and put above selector in your 'app.component.html',

in app.component.html

<h1>This is app.component.html</h1>
<app-home></app-home>


问:
How to inject environment config to different Angular Modules?
I have a app.config.ts in my angular app that look something like this:

```<code>export const APP_CONFIG = {
   ....
}
</code>```

This is generated on webpack build.

Now I have different angular modules that are on separate repository which is being used by my angular app. Some of these modules also needs the environment configs defined in app.config.ts. I am installing these modules using NPM so they are found in node_modules folder.

My problem is how am I going to supply the environment config to these modules without creating a dependency to the App itself?

I am thinking of saving the config to a global variable or saving it to localStorage on bootstrap of the app.

Should I also create environment configs on each module? Then handle it on webpack build?

Any ideas would be much appreciated.

答:
If I understand your question, you need to pass configuration information from your main application to your own external Angular libraries.  You can do that using the forRoot methodology explained in the Angular docs here.

Inside of your external Angular library modify the main exported module to have this structure:

```<code>export class MyLibraryModule {
  static forRoot(config: configData): ModuleWithProviders {
    return {
      ngModule: MyLibraryModule,
      providers: [
        {provide: AppConfigModel, useValue: config }
      ]
    };
  }

  constructor(@Optional() config: AppConfigModel) {
    if (config) { /* Save config data */ }
  }

 }
</code>```

When you import this module into your application, use the forRoot static method and pass in the config data.  You will need to create the appropriate model in your libarary (AppConfigModel in my example) to receive the APP_CONFIG you are passing in the forRoot method.

```<code>imports: [
    MyLibraryModule.forRoot(APP_CONFIG),
 ]
</code>```

Body:
I have a app.config.ts in my angular app that look something like this:

export const APP_CONFIG = {
   ....
}

This is generated on webpack build.

Now I have different angular modules that are on separate repository which is being used by my angular app. Some of these modules also needs the environment configs defined in app.config.ts. I am installing these modules using NPM so they are found in node_modules folder.

My problem is how am I going to supply the environment config to these modules without creating a dependency to the App itself?

I am thinking of saving the config to a global variable or saving it to localStorage on bootstrap of the app.

Should I also create environment configs on each module? Then handle it on webpack build?

Any ideas would be much appreciated.

Body:
If I understand your question, you need to pass configuration information from your main application to your own external Angular libraries.  You can do that using the forRoot methodology explained in the Angular docs here.

Inside of your external Angular library modify the main exported module to have this structure:

export class MyLibraryModule {
  static forRoot(config: configData): ModuleWithProviders {
    return {
      ngModule: MyLibraryModule,
      providers: [
        {provide: AppConfigModel, useValue: config }
      ]
    };
  }

  constructor(@Optional() config: AppConfigModel) {
    if (config) { /* Save config data */ }
  }

 }

When you import this module into your application, use the forRoot static method and pass in the config data.  You will need to create the appropriate model in your libarary (AppConfigModel in my example) to receive the APP_CONFIG you are passing in the forRoot method.

imports: [
    MyLibraryModule.forRoot(APP_CONFIG),
 ]


问:
Python: Trying to execute command to clear screen if user inputs certain number
I'm trying to remake a terminal from the Fallout series, if any of you know what that is.

Basically, the program shows a bunch of options they can choose from, then they have to input a number (1-5) to select which thing they want to view. The program will use an if statement to determine which thing they want to view. For example, if the user inputted one, then it will clear the screen and print a bunch of information, then the user has to input enter, then the screen clears and the options from the beginning are displayed again. This whole thing is inside a while statement, and while the user input is not "C", it will still display all of that other stuff, and when it does become "C", the program will clear everything and the program ends.

I know all of that sounded confusing, but basically the problem is that if the person inputs a number, it doesn't do the clearing thing, it just displays the choices again.

I'll just display the code, so if anyone could tell me what the problem is, that would greatly be appreciated.

```<code>def confusingFunction():
    from os import system
    userChoice = ""

    while userChoice.upper() != "C":
        print("Choice 1")
        print("Choice 2")
        print("Choice 3")
        print("Choice 4")
        print("Choice 5")
        userChoice = input(">>>")

        if userChoice == 1:
            system('cls')
            print("Stuff")
            print("Stuff")
            print("Stuff")
            input(">>>")
            system('cls')

    system('cls')
    return
</code>```

答:
You can try this:</p>

```<code>import subprocess
userChoice = ""

while userChoice.upper() != "C":
    print("Choice 1")
    print("Choice 2")
    print("Choice 3")
    print("Choice 4")
    print("Choice 5")
    userChoice = raw_input(">>>")

    if userChoice == '1':
        subprocess.call('clear')
        print("Stuff")
        print("Stuff")
        print("Stuff")
        userChoice = raw_input(">>>")
        subprocess.call('clear')

subprocess.call('clear')
</code>```

Body:
I'm trying to remake a terminal from the Fallout series, if any of you know what that is.

Basically, the program shows a bunch of options they can choose from, then they have to input a number (1-5) to select which thing they want to view. The program will use an if statement to determine which thing they want to view. For example, if the user inputted one, then it will clear the screen and print a bunch of information, then the user has to input enter, then the screen clears and the options from the beginning are displayed again. This whole thing is inside a while statement, and while the user input is not "C", it will still display all of that other stuff, and when it does become "C", the program will clear everything and the program ends.

I know all of that sounded confusing, but basically the problem is that if the person inputs a number, it doesn't do the clearing thing, it just displays the choices again.

I'll just display the code, so if anyone could tell me what the problem is, that would greatly be appreciated.

def confusingFunction():
    from os import system
    userChoice = ""

    while userChoice.upper() != "C":
        print("Choice 1")
        print("Choice 2")
        print("Choice 3")
        print("Choice 4")
        print("Choice 5")
        userChoice = input(">>>")

        if userChoice == 1:
            system('cls')
            print("Stuff")
            print("Stuff")
            print("Stuff")
            input(">>>")
            system('cls')

    system('cls')
    return

Body:
You can try this:

import subprocess
userChoice = ""

while userChoice.upper() != "C":
    print("Choice 1")
    print("Choice 2")
    print("Choice 3")
    print("Choice 4")
    print("Choice 5")
    userChoice = raw_input(">>>")

    if userChoice == '1':
        subprocess.call('clear')
        print("Stuff")
        print("Stuff")
        print("Stuff")
        userChoice = raw_input(">>>")
        subprocess.call('clear')

subprocess.call('clear')


问:
bash: npm: command not found
When I check the version of Node, it says

```<code>v8.0.0
</code>```

but when I check the version of NPM, it says

```<code>bash: npm: command not found
</code>```

Previously, my action was

npm install -g "@angular/cli"

That's when it consistently shows the npm: command not found message.

I tried searching for possible solutions but none worked like the brew and others.

答:
I have understand your problem, you have installed node and as well as you can install node legacy and npm. follow below commands you will easily solve

sudo apt-get remove npm,
  sudo apt-get remove nodejs-legacy,
  sudo apt-get remove nodejs ,
  sudo rm /usr/bin/node ,
  sudo apt-get install nodejs ,
  sudo apt-get install nodejs-legacy ,
  sudo apt-get install npm.

Title: bash: npm: command not found

Body:
When I check the version of Node, it says

v8.0.0

but when I check the version of NPM, it says

bash: npm: command not found

Previously, my action was

npm install -g "@angular/cli"

That's when it consistently shows the npm: command not found message.

I tried searching for possible solutions but none worked like the brew and others.


问:
Prgrammably making excel spreadsheets (97 - 2003 format)
I was wondering how difficult it would be to make an application like this. Basically, I have some old html files that use tables. I want to put these tables into excel for easier reading and manipulation. I only have text, I have no numbers of formulas or anything.

Are there any tutorials on how to do this sort of thing?

The application would produce .xls

Thanks

答:
There is a trick here:  save .html tables with the .xls extension and Excel can read them (ie Excel can read the output of the DataGrid control). </p>

<p>But, if you want to create 'real' Excel files, then you can either use Excel Interop (which could be messy, requires Excel and the PIA's to be installed on the machine, and needs careful memory management (since its COM)).  You could also opt for a 3rd-party library like FlexCel - which will avoid many of the InterOp problems but will not give you 'complete' Excel functionality (addins, custom vba macros etc.). For most uses, however, a 3rd party library should do the trick. </p>

ContentLicense: CC BY-SA 2.5

Body:
There is a trick here:  save .html tables with the .xls extension and Excel can read them (ie Excel can read the output of the DataGrid control).

But, if you want to create 'real' Excel files, then you can either use Excel Interop (which could be messy, requires Excel and the PIA's to be installed on the machine, and needs careful memory management (since its COM)).  You could also opt for a 3rd-party library like FlexCel - which will avoid many of the InterOp problems but will not give you 'complete' Excel functionality (addins, custom vba macros etc.). For most uses, however, a 3rd party library should do the trick.


问:
hide php file url in html form submit
```<code><form action="/path/hello.php" name='myForm' method='post'>
<!--  onChange="ajaxFunction();"  -->
<input type= "text"  name="user" id= "txtname" /><br />
<!-- <input type="text" name="user2" id="txtname2" /> -->
<input type='submit' name = "click"  />
</form>
</code>```

Noweveryone who looks at my html source code will know where this php file is located and will know how to call it. How can i stop this ?

答:
you can first give an action to page1 and in page 1 you can get the data and redirect and post the data to page2.
if you are using phpin page1 you can use curl and options to put data and execute it.</p>

Title: hide php file url in html form submit

Body:
<form action="/path/hello.php" name='myForm' method='post'>

<input type= "text"  name="user" id= "txtname" />

<input type='submit' name = "click"  />
</form>

Noweveryone who looks at my html source code will know where this php file is located and will know how to call it. How can i stop this ?


问:
Architecture: one or multiple databases for sub customers (web)APP
I've built a winforms application that i'm currently rebuilding into an ASP.NET MVC application using Web API etc. Maybe an app will be added later on.

Assume that I will provide these applications to a few customers.
My applications are made for customer accounting.
So all of my customers wil manage their customers whithin the applications I provide.

That brings me to my question. Should I work with one big database for al my customers, or should I use seperate database for each of my customers? I'd like to ask the same for web app instances, api's etc.

Technicaly I think both options are possible. If it's just a mather of preference, all input is appreciated.

Some pros and cons I could think off:

One database:

Easy to setup/maintain

Install one update for all of my customers

No possibility to restore db for one customer

Not flexible in terms of resource spreading

Performance, this db can get realy large

Multiple databases:

Preformance, databases are smaller sized and can be spread by multiple servers

Easy to restore data if customer made a 'huge mistake'

The ability to provide customer specific needs (not needed atm)

Harder to setup/maintain, every instance needs to be updated seperately.

A kind of gateway/routing thing is needed to route users to the right datbase/app

I would like to know how the 'big companies' approach this.

答:
You seem to be talking about database multi-tenancy, and you are right about the pros and cons.

The answer to this depends a lot on the kind of application you are building and the kind of customers it will have.

I would go with multi-tenant (single DB multiple tenants) database if

Your application is a multi-tenant application.

Your users do not need to store their own data backups.

Your DB schema will not change for each customer (this is implied in multi-tenant applications anyway).

Your tenants/customers will not have a huge amount of individual data.

Your customers don't have government imposed data isolation laws they need to comply with (EU data in EU, US data in US etc.).

And for individual databases pretty much the inverse of all those points.


问:
why onclick is not working with innerHtml
Here I am trying to add html to an element using innerHtml

```<code>  <body>
 <h3>Dynamically Retrieve the chapter name</h3>
<div>
<div>
    <button id="addChapter">Add Chapter</button>
    <div id="courseStructure">

    </div>
 </div>
 </div>
<script src="index.js"></script>
</body>
</code>```

JS:

```<code>var addChapter = document.getElementById("addChapter");

  addChapter.onclick = function(){
document.getElementById("courseStructure").innerHtml += '<div><input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button><br><br></div>';
 }
</code>```

everything seems good the onclick event is firing when button is clicked but the html is not getting added to the element.

答:
Change innerHtml to innerHTML.

var addChapter = document.getElementById("addChapter");

  addChapter.onclick = function(){
document.getElementById("courseStructure").innerHTML += '
<input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button>

';
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Dynamically Retrieve the chapter name</h3>
<div>
<div>
    <button id="addChapter">Add Chapter</button>
    <div id="courseStructure">

    </div>
 </div>
 </div></code>```

Body:
Here I am trying to add html to an element using innerHtml

Dynamically Retrieve the chapter name

    <button id="addChapter">Add Chapter</button>

JS:

var addChapter = document.getElementById("addChapter");

  addChapter.onclick = function(){
document.getElementById("courseStructure").innerHtml += '
<input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button>

';
 }

everything seems good the onclick event is firing when button is clicked but the html is not getting added to the element.

Body:
Change innerHtml to innerHTML.

var addChapter = document.getElementById("addChapter");

  addChapter.onclick = function(){
document.getElementById("courseStructure").innerHTML += '<div><input type="text" name="chaptername" placeholder="chapter name"/><button id="addSubChapter">Add SubChapter</button><button id="addContent">Add Content</button><br><br></div>';
 }

<h3>Dynamically Retrieve the chapter name</h3>
<div>
<div>
    <button id="addChapter">Add Chapter</button>
    <div id="courseStructure">

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


问:
Recycler view is not refreshed when i delete an item from recycler view?
When I try to delete an item from recyclerview (Full Image Activity), I call onfinish() method to go back to previous activity i.e recyclerview(GalleryActivity).

But the image which I delete is still visible and when I exit the gallery Activity and enter again then it is refreshed.

Any Solution to it, so that it can refresh when the item is deleted.When i delete an image this thing appears

This is my Recyclerview Adapter

public class RecyclerViewAdapter extends RecyclerView.Adapter {

```<code>private ArrayList<String> yeniliste;
private Context context;

public RecyclerViewAdapter(Context context, ArrayList<String> itemList) {
    this.yeniliste = itemList;
    this.context = context;
}

@Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
    View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_item, null);
    RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
    return rcv;
}

@Override
public void onBindViewHolder(final RecyclerViewHolders holder, final int position) {
    Bitmap bitmap = BitmapFactory.decodeFile(yeniliste.get(position));
    holder.countryPhoto.setImageBitmap(bitmap);
    holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(),GalleryFullImage.class);
            intent.putExtra("realid",String.valueOf(holder.getAdapterPosition()));
            v.getContext().startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return this.yeniliste.size();
}

public static class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{

    public ImageView countryPhoto;

    public RecyclerViewHolders(View itemView) {
        super(itemView);
        countryPhoto = (ImageView)itemView.findViewById(R.id.country_photo);
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(view.getContext(), "Clicked Country Position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();

    }

}

public void removeItem(int position)
{
    yeniliste.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, yeniliste.size());
}}
</code>```

removeItem method is also not Working.
This is my Full Image Activity. When I delete Image from here. It is not refreshing GalleryActivity.

```<code>public class GalleryFullImage extends AppCompatActivity {
String idPath;
String realid;
ArrayList<String> stringList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_fullimage);

    stringList = new ArrayList<>();
    String targetPath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {

            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }

    });
    for (File file : files){
        stringList.add(file.getAbsolutePath());
    }

    Intent i = getIntent();
    idPath = i.getStringExtra("realid");
    realid = stringList.get(Integer.parseInt(idPath));
    Log.d("wow",realid);
    File imgFile = new  File(realid);
    if(imgFile.exists()) {
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        ImageView myImage = (ImageView) findViewById(R.id.gallery_fullimg);
        myImage.setImageBitmap(myBitmap);
        myImage.setOnTouchListener(new ImageMatrixTouchHandler(getApplicationContext()));
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.delete, menu);

    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    final int id = item.getItemId();

    if (id == R.id.action_delete) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(GalleryFullImage.this);
        alertDialog.setTitle("Confirm Delete...");
        alertDialog.setMessage("Are you sure you want delete this?");
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
                rcAdapter.removeItem(Integer.parseInt(idPath));
                File file = new File(realid);
                boolean deleted = file.delete();
                Log.v("log_tag","deleted: " + deleted);
                Toast.makeText(GalleryFullImage.this,"File Deleted", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
        alertDialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}}
</code>```

This is GalleryActivity
.

```<code>public class GalleryActivity extends AppCompatActivity {
ArrayList<String> stringList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gallery);
    setTitle("Gallery");
    stringList = new ArrayList<>();
    String targetPath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {

            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }

    });
    for (File file : files){
        stringList.add(file.getAbsolutePath());
    }

    RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
    rView.setHasFixedSize(true);
    rView.setLayoutManager(layoutManager);
    RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
    rView.setAdapter(rcAdapter);

}
@Override
protected void onResume() {
    super.onResume();
}}
</code>```

答:
Do this in GalleryActivity

```<code>@Override
protected void onResume() {
    super.onResume();
    if(rView != null){
      yourAdapter.notifyDataSetChanged();
    }

 };
</code>```

Make the rView  and the adapter global variables.

Body:
When I try to delete an item from recyclerview (Full Image Activity), I call onfinish() method to go back to previous activity i.e recyclerview(GalleryActivity).

But the image which I delete is still visible and when I exit the gallery Activity and enter again then it is refreshed.

Any Solution to it, so that it can refresh when the item is deleted.When i delete an image this thing appears

This is my Recyclerview Adapter

public class RecyclerViewAdapter extends RecyclerView.Adapter {

private ArrayList<String> yeniliste;
private Context context;

public RecyclerViewAdapter(Context context, ArrayList<String> itemList) {
    this.yeniliste = itemList;
    this.context = context;
}

@Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
    View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_item, null);
    RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
    return rcv;
}

@Override
public void onBindViewHolder(final RecyclerViewHolders holder, final int position) {
    Bitmap bitmap = BitmapFactory.decodeFile(yeniliste.get(position));
    holder.countryPhoto.setImageBitmap(bitmap);
    holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(),GalleryFullImage.class);
            intent.putExtra("realid",String.valueOf(holder.getAdapterPosition()));
            v.getContext().startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return this.yeniliste.size();
}

public static class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{

    public ImageView countryPhoto;

    public RecyclerViewHolders(View itemView) {
        super(itemView);
        countryPhoto = (ImageView)itemView.findViewById(R.id.country_photo);
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(view.getContext(), "Clicked Country Position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();

    }

}

public void removeItem(int position)
{
    yeniliste.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, yeniliste.size());
}}

removeItem method is also not Working.
This is my Full Image Activity. When I delete Image from here. It is not refreshing GalleryActivity.

public class GalleryFullImage extends AppCompatActivity {
String idPath;
String realid;
ArrayList<String> stringList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_fullimage);

    stringList = new ArrayList<>();
    String targetPath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {

            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }

    });
    for (File file : files){
        stringList.add(file.getAbsolutePath());
    }

    Intent i = getIntent();
    idPath = i.getStringExtra("realid");
    realid = stringList.get(Integer.parseInt(idPath));
    Log.d("wow",realid);
    File imgFile = new  File(realid);
    if(imgFile.exists()) {
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        ImageView myImage = (ImageView) findViewById(R.id.gallery_fullimg);
        myImage.setImageBitmap(myBitmap);
        myImage.setOnTouchListener(new ImageMatrixTouchHandler(getApplicationContext()));
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.delete, menu);

    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    final int id = item.getItemId();

    if (id == R.id.action_delete) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(GalleryFullImage.this);
        alertDialog.setTitle("Confirm Delete...");
        alertDialog.setMessage("Are you sure you want delete this?");
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
                rcAdapter.removeItem(Integer.parseInt(idPath));
                File file = new File(realid);
                boolean deleted = file.delete();
                Log.v("log_tag","deleted: " + deleted);
                Toast.makeText(GalleryFullImage.this,"File Deleted", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
        alertDialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}}

This is GalleryActivity
.

public class GalleryActivity extends AppCompatActivity {
ArrayList<String> stringList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gallery);
    setTitle("Gallery");
    stringList = new ArrayList<>();
    String targetPath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Images/";
    File targetDirector = new File(targetPath);
    File[] files = targetDirector.listFiles();
    Arrays.sort( files, new Comparator()
    {
        public int compare(Object o1, Object o2) {

            if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
            } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                return +1;
            } else {
                return 0;
            }
        }

    });
    for (File file : files){
        stringList.add(file.getAbsolutePath());
    }

    RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
    rView.setHasFixedSize(true);
    rView.setLayoutManager(layoutManager);
    RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getApplicationContext(), stringList);
    rView.setAdapter(rcAdapter);

}
@Override
protected void onResume() {
    super.onResume();
}}

Body:
Do this in GalleryActivity

@Override
protected void onResume() {
    super.onResume();
    if(rView != null){
      yourAdapter.notifyDataSetChanged();
    }

 };

Make the rView  and the adapter global variables.


问:
Adjust button text size with button height
I have a button that I set a particular height for and have the button text fill the entire button. I achieved this before by setting textSize to a specific dimension to fill the button.

But the problem is whenever the user changes the system font of his/her device, it affects the button text and the text overflows and gets cut in the button. How can I make the button text size match the height of the button?

Edit

The button's height is set to match_parent for it's parent widget

```<code>        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">
            <RelativeLayout
                android:layout_marginEnd="16dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginRight="16dp">
                <Button
                    android:id="@+id/text_toolbar"
                    style="?android:attr/borderlessButtonStyle"
                    android:layout_centerInParent="true"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:textSize="36sp"
                    android:textColor="@color/white"
                    android:text="@string/k_i_n_e_c_t"/>
            </RelativeLayout>
        </android.support.v7.widget.Toolbar>
</code>```

答:
try to wrap_content property to both RelativeLayout and Button like above code ,</p>

```<code>  <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">
        <RelativeLayout
            android:layout_marginEnd="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="16dp">
            <Button
                android:id="@+id/text_toolbar"
                style="?android:attr/borderlessButtonStyle"
                android:layout_centerInParent="true"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="36sp"
                android:textColor="@color/white"
                android:text="@string/k_i_n_e_c_t"
                android:padding="2sp"/>
        </RelativeLayout>
    </android.support.v7.widget.Toolbar>
</code>```

Body:
I have a button that I set a particular height for and have the button text fill the entire button. I achieved this before by setting textSize to a specific dimension to fill the button.

But the problem is whenever the user changes the system font of his/her device, it affects the button text and the text overflows and gets cut in the button. How can I make the button text size match the height of the button?

Edit

The button's height is set to match_parent for it's parent widget

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">
            <RelativeLayout
                android:layout_marginEnd="16dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginRight="16dp">
                <Button
                    android:id="@+id/text_toolbar"
                    style="?android:attr/borderlessButtonStyle"
                    android:layout_centerInParent="true"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:textSize="36sp"
                    android:textColor="@color/white"
                    android:text="@string/k_i_n_e_c_t"/>
            </RelativeLayout>
        </android.support.v7.widget.Toolbar>

Body:
try to wrap_content property to both RelativeLayout and Button like above code ,

  <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">
        <RelativeLayout
            android:layout_marginEnd="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="16dp">
            <Button
                android:id="@+id/text_toolbar"
                style="?android:attr/borderlessButtonStyle"
                android:layout_centerInParent="true"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="36sp"
                android:textColor="@color/white"
                android:text="@string/k_i_n_e_c_t"
                android:padding="2sp"/>
        </RelativeLayout>
    </android.support.v7.widget.Toolbar>


问:
is there a way to change case to low or high whole block in visual mode vim?
Want to change case to lower in whole block in visual mode.
If i want to change case of a single character, i can press ~, but what i need to use in visual mode for changing in selected area into low or high case ?</p>

答:
With visual selection active, press 'u' for lowercase, 'U' for uppercase.

Without visual mode, use 'gu' or 'gU', with motion command. E.g. to uppercase a word 'gUw'.


问:
laravel eloquent store submodel with model
If a user creates an account, I want to store default settings in a different table. I have two models: User and UserSettings .

How to create the settings part after creating the User?

I create the User as follow:

```<code>  $user = User::create([
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
</code>```

Then I tried:

```<code>$user->settings()->save(new UserSettings());
</code>```

I also tried the create method, but with no success. I always receive

ErrorException in HasAttributes.php line 818: Illegal offset type

in User::class model i have

```<code>public function settings()
{
    return $this->hasOne(UserSetting::class, 'user_id', 'id');
}
</code>```

and the inverse in UserSetting::class

```<code>public function user()
{
    return $this->belongsTo(User::class, 'id', 'user_id');
}
</code>```

user_settings table

settings_id | user_id | different_options

答:
I tried the below code and its worked. Please have a look.

```<code>    $user = new User;
    $user->username = "JicksonJohnson";
    $user->email = "jicksonkoottala@gmail.com";
    $user->password = bcrypt('123456');
    $user->save();
    $user->settings()->save(new UserSettings(array('user_id' => $user->id,'options' => 'test options')));
</code>```

In User model I created one relationship.

```<code>public function settings()
{
    return $this->hasOne(UserSettings::class, 'user_id', 'id');
}
</code>```

Body:
If a user creates an account, I want to store default settings in a different table. I have two models: User and UserSettings .

How to create the settings part after creating the User?

I create the User as follow:

  $user = User::create([
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

Then I tried:

$user->settings()->save(new UserSettings());

I also tried the create method, but with no success. I always receive

ErrorException in HasAttributes.php line 818: Illegal offset type

in User::class model i have

public function settings()
{
    return $this->hasOne(UserSetting::class, 'user_id', 'id');
}

and the inverse in UserSetting::class

public function user()
{
    return $this->belongsTo(User::class, 'id', 'user_id');
}

user_settings table

settings_id | user_id | different_options

Body:
I tried the below code and its worked. Please have a look.

    $user = new User;
    $user->username = "JicksonJohnson";
    $user->email = "jicksonkoottala@gmail.com";
    $user->password = bcrypt('123456');
    $user->save();
    $user->settings()->save(new UserSettings(array('user_id' => $user->id,'options' => 'test options')));

In User model I created one relationship.

public function settings()
{
    return $this->hasOne(UserSettings::class, 'user_id', 'id');
}


问:
Action method won't redirect via jQuery.post in .net-core-mvc app
```<code>$.post({
    url: '@Url.Action("Create", "MyController")',
    data: { myVar: myVal }
})
</code>```

In the Controller Action method I'm debugging the parameter value being posted via the jQuery method and I know the method is being called and passed the correct data but the RedirectToAction("Index"); statement doesn't load my other view page.

The debug console shows me a successful get request for the url localhost:xxxxx/MyController/Index.  However, the get request isn't reflected in the browser developer network window.

答:
You can't do that since your post ajax call is expecting a return instead of redirecting to action try something like passing true instead of redirecting and in ajax success function</p>

```<code>success:function(data)
{
    if(data)
    {
        var url = '@url.action("yourACtion","yourController")';
        window.location.href = url;
     }
}
</code>```

Body:
$.post({
    url: '@Url.Action("Create", "MyController")',
    data: { myVar: myVal }
})

In the Controller Action method I'm debugging the parameter value being posted via the jQuery method and I know the method is being called and passed the correct data but the RedirectToAction("Index"); statement doesn't load my other view page.

The debug console shows me a successful get request for the url localhost:xxxxx/MyController/Index.  However, the get request isn't reflected in the browser developer network window.

Body:
You can't do that since your post ajax call is expecting a return instead of redirecting to action try something like passing true instead of redirecting and in ajax success function

success:function(data)
{
    if(data)
    {
        var url = '@url.action("yourACtion","yourController")';
        window.location.href = url;
     }
}


问:
General suggestions for debugging in R
I get an error when using an R function that I wrote:

```<code>Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: algorithm did not converge
</code>```

What I have done:

Step through the function

Adding print to find out at what line the error occurs suggests two functions that should not use glm.fit.  They are window() and save().

My general approaches include adding print and stop commands, and stepping through a function line by line until I can locate the exception.

However, it is not clear to me using those techniques where this error comes from in the code. I am not even certain which functions within the code depend on glm.fit.  How do I go about diagnosing this problem?

答:
So browser(), traceback() and debug() walk into a bar, but trace() waits outside and keeps the motor running.

By inserting browser somewhere in your function, the execution will halt and wait for your input. You can move forward using n (or Enter), run the entire chunk (iteration) with c, finish the current loop/function with f, or quit with Q; see ?browser.

With debug, you get the same effect as with browser, but this stops the execution of a function at its beginning. Same shortcuts apply. This function will be in a "debug" mode until you turn it off using undebug (that is, after debug(foo), running the function foo will enter "debug" mode every time until you run undebug(foo)).

A more transient alternative is debugonce, which will remove the "debug" mode from the function after the next time it's evaluated.

traceback will give you the flow of execution of functions all the way up to where something went wrong (an actual error).

You can insert code bits (i.e. custom functions) in functions using trace, for example browser. This is useful for functions from packages and you're too lazy to get the nicely folded source code.

Title: General suggestions for debugging in R

Body:
I get an error when using an R function that I wrote:

Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: algorithm did not converge

What I have done:

Step through the function

Adding print to find out at what line the error occurs suggests two functions that should not use glm.fit.  They are window() and save().

My general approaches include adding print and stop commands, and stepping through a function line by line until I can locate the exception.

However, it is not clear to me using those techniques where this error comes from in the code. I am not even certain which functions within the code depend on glm.fit.  How do I go about diagnosing this problem?

ContentLicense: CC BY-SA 4.0


问:
Why can't I remove these divs with jQuery?
I have dynamically created elements within a parent element of .output which are created within my on('click') function.

```<code>$(document).on("click", '#search', function() {
//Loop crime data array from api request above...
for(var i = 0; i < mapData.length; i++) {

  //Fill in crime data
  var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';

  //add to div
  $('.output').append(fill);
}
...
.......
</code>```

But nowhere outside the function am I able to target the new .resu rows for which I can apply .empty() or .remove(). Every time I hit the search button I wish to empty the output container div first.

If you go to my pen and hit the button, you will see some information regarding crime in that postcode's area. If you keep pressing it then multiple duplications of the same information will fill it up. How can I get rid of those with jquery?

My pen:
https://codepen.io/anon/pen/xrwXYy

答:
You are doing right with output div.

But you missed out the mapData variable to be empty.

Each time its getting push in your ajax success response for loop.

So you need to clear mapData veriable.

Body:
I have dynamically created elements within a parent element of .output which are created within my on('click') function.

$(document).on("click", '#search', function() {
//Loop crime data array from api request above...
for(var i = 0; i < mapData.length; i++) {

  //Fill in crime data
  var fill = '

'+[i+1]+'

Type of crime: '+mapData[i][0]+'

Location specifics: '+mapData[i][1]+'

';

  //add to div
  $('.output').append(fill);
}
...
.......

But nowhere outside the function am I able to target the new .resu rows for which I can apply .empty() or .remove(). Every time I hit the search button I wish to empty the output container div first.

If you go to my pen and hit the button, you will see some information regarding crime in that postcode's area. If you keep pressing it then multiple duplications of the same information will fill it up. How can I get rid of those with jquery?

My pen:
https://codepen.io/anon/pen/xrwXYy


问:
Back button not working: $ionicHistory.backView() is the same with currentView
I am using Ionic v1 Angular

Here is my code:

```<code>$scope.back = function () {
    $ionicHistory.goBack();
    // window.history.back(); //this works but not working on device hardware back button
    console.log($ionicHistory.currentView()); //url: app/home
    console.log($ionicHistory.backView()); //url: app/home
};
</code>```

Here is my button:

```<code><button ng-hide="current_state == 'app.home'" class="button button-clear" menu-toggle="left" ng-click="back()" id="back_button">back</button>
</code>```

答:
If you want to control hardware backbutton you must register and override default action of hardware back button</p>

```<code>  // Disable BACK button on home
  $ionicPlatform.registerBackButtonAction(function (event) {
    if($state.current.name=="app.home"){  // if you are in home page you can close the app
      navigator.app.exitApp();
    }
    else { // otherwise you just go back to previous statein the history
      navigator.app.backHistory();
    }
  }, 100);
</code>```

Body:
I am using Ionic v1 Angular

Here is my code:

$scope.back = function () {
    $ionicHistory.goBack();
    // window.history.back(); //this works but not working on device hardware back button
    console.log($ionicHistory.currentView()); //url: app/home
    console.log($ionicHistory.backView()); //url: app/home
};

Here is my button:

<button ng-hide="current_state == 'app.home'" class="button button-clear" menu-toggle="left" ng-click="back()" id="back_button">back</button>

Body:
If you want to control hardware backbutton you must register and override default action of hardware back button

  // Disable BACK button on home
  $ionicPlatform.registerBackButtonAction(function (event) {
    if($state.current.name=="app.home"){  // if you are in home page you can close the app
      navigator.app.exitApp();
    }
    else { // otherwise you just go back to previous statein the history
      navigator.app.backHistory();
    }
  }, 100);


问:
"/admin" disappearing from URL after loading the view (Rails)
After navigating to an admin view, /admin disappears out of the URL.

This is occurring for all routes nested inside namespace :admin do.

Example:

Visiting http://localhost:3000/admin/universities loads the view.

But then the URL in that view changes to http://localhost:3000/universities.

Refreshing the page without manually adding back in the /admin, results in "No route matches".

Server Logs:

```<code>Started GET "/admin/universities"
Processing by Admin::UniversitiesController#index as HTML
Rendered admin/universities/index.html.haml within layouts/admin
Rendering admin/universities/index.html.haml within layouts/admin
</code>```

Route:

```<code>namespace :admin do
    ...
    get '/universities', to: 'universities#index', as: :university_index
    ...
end
</code>```

rake routes:

```<code>admin_university_index GET   /admin/universities(.:format)    admin/universities#index
</code>```

Controller:

```<code>class Admin::UniversitiesController < Admin::BaseController

  def index
    @universities = University.all
  end
end
</code>```

I inherited the app and am having trouble figuring out why this is occuring. Has anyone else had experience with this before?

UPDATE

Could this be caused by turbolinks?

UPDATE

Per request, adding admin/base_controller

```<code># /app/controllers/admin/base_controller.rb
class Admin::BaseController < ApplicationController

  before_action :admin_only
  layout "admin"

  private

    def admin_only
      unless current_user && current_user.role == 'admin'
        redirect_to login_url, :notice => "Unauthorized"
      end
    end

end
</code>```

答:
Certainly seems like a problem which could be caused by Turbolinks. If you haven't already, you can try and narrow down the possibilities by starting up a dev server and removing the Turbolinks gem. If you don't experience the problem then you'll know it has something to do with Turbolinks.

While it seems inevitable that this is caused by Javascript, you can test this by disabling javascript execution in your browser, visiting an admin page, and checking to see if the address updates.

Turbolinks documentation: https://github.com/turbolinks/turbolinks

Body:
After navigating to an admin view, /admin disappears out of the URL.

This is occurring for all routes nested inside namespace :admin do.

Example:

Visiting http://localhost:3000/admin/universities loads the view.

But then the URL in that view changes to http://localhost:3000/universities.

Refreshing the page without manually adding back in the /admin, results in "No route matches".

Server Logs:

Started GET "/admin/universities"
Processing by Admin::UniversitiesController#index as HTML
Rendered admin/universities/index.html.haml within layouts/admin
Rendering admin/universities/index.html.haml within layouts/admin

Route:

namespace :admin do
    ...
    get '/universities', to: 'universities#index', as: :university_index
    ...
end

rake routes:

admin_university_index GET   /admin/universities(.:format)    admin/universities#index

Controller:

class Admin::UniversitiesController < Admin::BaseController

  def index
    @universities = University.all
  end
end

I inherited the app and am having trouble figuring out why this is occuring. Has anyone else had experience with this before?

UPDATE

Could this be caused by turbolinks?

UPDATE

Per request, adding admin/base_controller

# /app/controllers/admin/base_controller.rb
class Admin::BaseController < ApplicationController

  before_action :admin_only
  layout "admin"

  private

    def admin_only
      unless current_user && current_user.role == 'admin'
        redirect_to login_url, :notice => "Unauthorized"
      end
    end

end


问:
Sonarqube 4.0 unable to generate report
I am trying to do sonar analysis on one of my projects but I am facing some issue when it comes to the very end of the mvn sonar:sonar command I am using Java 7 with maven 2.2.1 and sonar 4.0
The error reported on screen is cannot execute sonar
Unable to execute maven plugin.

And further the trace says     Org.apache.maven.lifecycle.lifecycleExecutionException: cannot execute sonar

```<code> Caused by:org.apache.maven.plugin.mojoExecutionException: cannot execute sonar
Caused by: org.sonar.api.utils.SonarException:unable to execute maven plugin.
Caused by org.sonar.api.utils.SonarException:Unable to execute Maven 2 plugin
Caused by Java.lang.reflect.InvoacationTargetException

Caused by java.util.ConcurrentModificationException
</code>```

答:
It can depend on your exact mvn command, especially when used with a multithreading option (mvn -T4).

The firs thing to test, as mentioned in this versions-maven-plugin issue 40, is to see if the latest maven would avoid this issue.

Check out Maven 3.5.0, to see if this is a maven core issue, or a Sonar plugin one.

Title: Sonarqube 4.0 unable to generate report

Body:
I am trying to do sonar analysis on one of my projects but I am facing some issue when it comes to the very end of the mvn sonar:sonar command I am using Java 7 with maven 2.2.1 and sonar 4.0
The error reported on screen is cannot execute sonar
Unable to execute maven plugin.

And further the trace says     Org.apache.maven.lifecycle.lifecycleExecutionException: cannot execute sonar

 Caused by:org.apache.maven.plugin.mojoExecutionException: cannot execute sonar
Caused by: org.sonar.api.utils.SonarException:unable to execute maven plugin.
Caused by org.sonar.api.utils.SonarException:Unable to execute Maven 2 plugin
Caused by Java.lang.reflect.InvoacationTargetException

Caused by java.util.ConcurrentModificationException


问:
Cannot get javascript innerHtml to work on WebView
I am using a WebView with a javaScript interface.  All I want to do is change the inner html of a span if some checkboxes are ticked.

Below is a snippet of a String I have in strings.xml.  The form will call this function onSubmit and should not continue if it does not pass.  The problem is that I can't get the innerHtml working (is returns true everytime).

This works

```<code><script type=\"text/javascript\" language=\"javascript\">
    function pass() {
        return javaInterface.checkboxPass();
        /*
        if(passed) {
            //change the instructions
            document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
        }

        return passed;
        */
    }
</script>
</code>```

This returns true everytime

```<code><script type=\"text/javascript\" language=\"javascript\">
    function pass() {
        var passed= javaInterface.checkboxPass();

        if(passed) {
            //change the instructions
            document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
        }

        return passed;

    }
</script>
</code>```

This is the span in the body of the document

```<code><span id=\"txtInstructions\">%1$s</span>
</code>```

What am I doing wrong?

答:
I still think that your method is returning something that isn't strictly a boolean. I would try doing something like this:

```<code><script type="text/javascript" language="javascript">
function pass() {
    var passed= javaInterface.checkboxPass();

    if(JSON.parse(passed)) {
        //change the instructions
        document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
    }

    return passed;

}
</script>
</code>```

This will rule out the possibility of the "boolean" being wrapped in quotes or something else lame.  If this truly is a Java interface, it probably is converting the boolean to a string.

I don't think that booleans can be passed as real boolean values, especially since javascript and java work differently under the hood. You could use eval, but it's not good practice because if it were a function, it would run it.

IE doesn't have an parse function, so you'll have to use this:

https://github.com/douglascrockford/JSON-js

Body:
I am using a WebView with a javaScript interface.  All I want to do is change the inner html of a span if some checkboxes are ticked.

Below is a snippet of a String I have in strings.xml.  The form will call this function onSubmit and should not continue if it does not pass.  The problem is that I can't get the innerHtml working (is returns true everytime).

This works

This returns true everytime

This is the span in the body of the document

%1$s

What am I doing wrong?

Body:
I still think that your method is returning something that isn't strictly a boolean. I would try doing something like this:

<script type="text/javascript" language="javascript">
function pass() {
    var passed= javaInterface.checkboxPass();

    if(JSON.parse(passed)) {
        //change the instructions
        document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
    }

    return passed;

}
</script>

This will rule out the possibility of the "boolean" being wrapped in quotes or something else lame.  If this truly is a Java interface, it probably is converting the boolean to a string.

I don't think that booleans can be passed as real boolean values, especially since javascript and java work differently under the hood. You could use eval, but it's not good practice because if it were a function, it would run it.

IE doesn't have an parse function, so you'll have to use this:

https://github.com/douglascrockford/JSON-js


问:
Fortrans equivalent syntax to C++
I am handling a file . THe format of content is as following :

```<code>name   - problem name (A string value)
m      - number or rows (int value)
n      - number of columns (int value)
Ap     - pointers to the begining of storage of column (size n+1)(an array of size (n+1) )
Ai     - row indices for each non zero entry (input, nnz A)
Ax     - non zero entries (input, nnz A)
b      - right hand side (input, size m)(an double array of size m )
c      - objective vector (minimize, size n) (an double array of size n) )
z0     - initial fixed value for objective (double value)
lobnd  - lower bounds on variables (size n) (an double array of size n )
upbnd  - upper bounds on variables (size n) (an double array of size n )
</code>```

The syntax for reading this file in fortran is as follows :

```<code>Ap (j) = location of start of column j
Ai (Ap (j)) through Ai (Ap (j+1)-1) are the row indices in column j
Ax (Ap (j)) through Ax (Ap (j+1)-1) are the numerical values in column j

      read(file,'(a8)') name
      read(file,*) m,n
      read(file,*) (ia(i),i=1,n+1)
      read(file,*) (ja(i),i=1,ia(n+1)-1)
      read(file,*) (a(i),i=1,ia(n+1)-1)
      read(file,*) (b(i),i=1,m)
      read(file,*) (c(i),i=1,n)
      read(file,*) z0
      read(file,*) (lobnd(i),i=1,n)
      read(file,*) (upbnd(i),i=1,n)
</code>```

I want to know the corresponding syntax in C++ . Do anyone has any idea how to convert this program from fortran to C++ ?
Here is an example of an file .

According to the description of file format here in the above file

```<code>name   = 'BLEND'
m      = 74
n      = 114
upbnd  = I can see the n or 114 double values at the end of the file
lobnd  = I can see the n or 114 double values before the values of upbnd
z0     = here I can see 0. is the value of z0
c      = I can see n or 114 values before z0 in the file and understand this
b      = I understand the right hand side and I can see the m or 74 values
Ai     - I understand row indices for each non zero entry (input, nnz A)
Ax     - non zero entries (input, nnz A)

Now I can not understand the following values in the file:
Ap     = I can not understand what do these (n+1) or 115 integers mean
</code>```

I want to understand this Ap values in the file.
thanks in advance.

答:
The read(file,'(a8)') name translates roughly like scanf("%8s", name);.

The read(file,*) m,n is roughly equivalent to something like file >> m >> n;

The lines like read(file,*) (ia(i),i=1,n+1) are undoubtedly the trickiest. The part after the first comma is an "implied DO loop". It basically means this is roughly equivalent to something on the order of:

```<code>for (int i=1; i<n+1; i++)
    file >> ia[i];
</code>```

I believe the rest are just repetitions of one or another of those shown above.

There is one other point to keep in mind, though: Fortran stores arrays in column major order. C and C++ store arrays in row-major order. That means as you traverse an array in C or C++, you normally want to traverse it row by row. This will, among other things, optimize cache usage, because each row is stored contiguously in memory.

Fortran is column-major. That means each column is contiguous in memory, and the natural way to traverse the array is a column at a time. Since each column is contiguous in memory, this (of course) optimizes cache usage.

The values in Ap contain the location of the beginning of each column. That is Ap(1) is the index of the first item in the first column. Ap(2) is the index of the first item in the second column, and so on. If you need to read the Nth column, Ap(N) will tell you the spot in the main array where you start to read to get the data for that column. Since Ap(N+1) is the beginning of column N+1, the last item in column N is at Ap(N+1)-1.

So, let's assume you read the main data array into a flat (1D) array, which we'll just call data. To read the Nth column in data, you can use Ap. For example, to print out the Nth column, we could write code like this:

```<code>void print_column(int n) {
    for (int i=Ap[n]; i<Ap[n+1]; i++)
        std::cout << data[i] << '\t';
}
</code>```

This lets you avoid having to deal with dynamically allocating a 2D array, and instead use only single new/malloc/vector to hold the data, along with a second one to hold the index for the beginning of each column. In C++ it's pretty easy to create a 2D matrix class that overloads operator() to do 2D addressing into data stored in a vector. You could use either the extra level of indirection provided by Ap, or you could just use multiplication to get to the right position. On a current processor, the multiplication is probably faster than a memory reference, but on older processors multiplication was often much slower relative to memory access.

Title: Fortrans equivalent syntax to C++

Body:
I am handling a file . THe format of content is as following :

name   - problem name (A string value)
m      - number or rows (int value)
n      - number of columns (int value)
Ap     - pointers to the begining of storage of column (size n+1)(an array of size (n+1) )
Ai     - row indices for each non zero entry (input, nnz A)
Ax     - non zero entries (input, nnz A)
b      - right hand side (input, size m)(an double array of size m )
c      - objective vector (minimize, size n) (an double array of size n) )
z0     - initial fixed value for objective (double value)
lobnd  - lower bounds on variables (size n) (an double array of size n )
upbnd  - upper bounds on variables (size n) (an double array of size n )

The syntax for reading this file in fortran is as follows :

Ap (j) = location of start of column j
Ai (Ap (j)) through Ai (Ap (j+1)-1) are the row indices in column j
Ax (Ap (j)) through Ax (Ap (j+1)-1) are the numerical values in column j

      read(file,'(a8)') name
      read(file,*) m,n
      read(file,*) (ia(i),i=1,n+1)
      read(file,*) (ja(i),i=1,ia(n+1)-1)
      read(file,*) (a(i),i=1,ia(n+1)-1)
      read(file,*) (b(i),i=1,m)
      read(file,*) (c(i),i=1,n)
      read(file,*) z0
      read(file,*) (lobnd(i),i=1,n)
      read(file,*) (upbnd(i),i=1,n)

I want to know the corresponding syntax in C++ . Do anyone has any idea how to convert this program from fortran to C++ ?
Here is an example of an file .

According to the description of file format here in the above file

name   = 'BLEND'
m      = 74
n      = 114
upbnd  = I can see the n or 114 double values at the end of the file
lobnd  = I can see the n or 114 double values before the values of upbnd
z0     = here I can see 0. is the value of z0
c      = I can see n or 114 values before z0 in the file and understand this
b      = I understand the right hand side and I can see the m or 74 values
Ai     - I understand row indices for each non zero entry (input, nnz A)
Ax     - non zero entries (input, nnz A)

Now I can not understand the following values in the file:
Ap     = I can not understand what do these (n+1) or 115 integers mean

I want to understand this Ap values in the file.
thanks in advance.

Body:
The read(file,'(a8)') name translates roughly like scanf("%8s", name);.

The read(file,*) m,n is roughly equivalent to something like file >> m >> n;

The lines like read(file,*) (ia(i),i=1,n+1) are undoubtedly the trickiest. The part after the first comma is an "implied DO loop". It basically means this is roughly equivalent to something on the order of:

for (int i=1; i<n+1; i++)
    file >> ia[i];

I believe the rest are just repetitions of one or another of those shown above.

There is one other point to keep in mind, though: Fortran stores arrays in column major order. C and C++ store arrays in row-major order. That means as you traverse an array in C or C++, you normally want to traverse it row by row. This will, among other things, optimize cache usage, because each row is stored contiguously in memory.

Fortran is column-major. That means each column is contiguous in memory, and the natural way to traverse the array is a column at a time. Since each column is contiguous in memory, this (of course) optimizes cache usage.

The values in Ap contain the location of the beginning of each column. That is Ap(1) is the index of the first item in the first column. Ap(2) is the index of the first item in the second column, and so on. If you need to read the Nth column, Ap(N) will tell you the spot in the main array where you start to read to get the data for that column. Since Ap(N+1) is the beginning of column N+1, the last item in column N is at Ap(N+1)-1.

So, let's assume you read the main data array into a flat (1D) array, which we'll just call data. To read the Nth column in data, you can use Ap. For example, to print out the Nth column, we could write code like this:

void print_column(int n) {
    for (int i=Ap[n]; i<Ap[n+1]; i++)
        std::cout << data[i] << '\t';
}

This lets you avoid having to deal with dynamically allocating a 2D array, and instead use only single new/malloc/vector to hold the data, along with a second one to hold the index for the beginning of each column. In C++ it's pretty easy to create a 2D matrix class that overloads operator() to do 2D addressing into data stored in a vector. You could use either the extra level of indirection provided by Ap, or you could just use multiplication to get to the right position. On a current processor, the multiplication is probably faster than a memory reference, but on older processors multiplication was often much slower relative to memory access.


问:
TableView Section Footers doesn't resize its width after rotation
I have a table view with header and footer in every section.
When the device rotates, the headers resizes to fit the table's width, but the footers remains with portrait width.

I tried setting a large width in the xib file, and it works for the header, but no effect on footer.

I also tried doing a reload data in

```<code>viewWillTransitionToSize
</code>```

and it works, but I feel like is not the best way to do it, it also has a weird animation while rotating.

答:
You might use viewWillLayoutSubviews(). This question should be helpful but this is bassically called whenever the view controller views is about to layout its subviews.

So your code will look like this:

```<code>override func viewWillLayoutSubviews() {
   super.viewWillLayoutSubviews()
   if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
      //here you can do the logic for the cell size if phone is in landscape
   } else {
         //logic if not landscape
     }
 self.tableView.reloadData()
}
</code>```

Body:
I have a table view with header and footer in every section.
When the device rotates, the headers resizes to fit the table's width, but the footers remains with portrait width.

I tried setting a large width in the xib file, and it works for the header, but no effect on footer.

I also tried doing a reload data in

viewWillTransitionToSize

and it works, but I feel like is not the best way to do it, it also has a weird animation while rotating.

Body:
You might use viewWillLayoutSubviews(). This question should be helpful but this is bassically called whenever the view controller views is about to layout its subviews.

So your code will look like this:

override func viewWillLayoutSubviews() {
   super.viewWillLayoutSubviews()
   if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
      //here you can do the logic for the cell size if phone is in landscape
   } else {
         //logic if not landscape
     }
 self.tableView.reloadData()
}


问:
Is it possible to set a new entity directly from twig?
Sometime i need to check if an user can comment from a voter, obviously at this point of the code the comment does not yet exist, but still i need to check if the user is allowed to comment or not.

From the controller i would usually do $this->isGranted('create', new Comment()) but how i'm supposed to do the same thing in twig? I can't find a clear explaination, and i obviously can't do something like {% if is_granted('create', new comment()) %}.

Is there a way to do this without hacking an object from the controller such as rendering a new Comment() from the controller? Doing so will allow me to avoid a lot of spaghetti code in my voters.

答:
you can extend twig with Symfony Twig Extensions

Look at this documentation link:

Symfony Twig Extensions

Inside your twig you can use is_granted like this:

```<code>{{ is_granted(role, object = null, field = null) }}
</code>```

Body:
you can extend twig with Symfony Twig Extensions

Look at this documentation link:

Symfony Twig Extensions

Inside your twig you can use is_granted like this:

{{ is_granted(role, object = null, field = null) }}