问:
Angular 2- calling http with observable not working. tried all option but not worked

Not able to call web api using http in angular2.
tried different solutions but still not help. So may opening new issue will help me.

tried below solutions but not helped:

http with Observable in Angular 2 cant use data

Angular2 - http.get not calling the webpi

why http.post didn't call my controller in angular 2

Below is the source - please let me know if i am doing anything wrong:

"package.json"

{
  "name": "Angular2Spa",
  "version": "0.0.0",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/platform-server": "2.0.0",
    "@angular/router": "3.0.0",
    "@types/node": "^6.0.38",
    "angular2-localstorage": "^0.4.0",
    "angular2-platform-node": "~2.0.10",
    "angular2-universal": "~2.0.10",
    "angular2-universal-polyfills": "~2.0.10",
    "aspnet-prerendering": "^1.0.6",
    "aspnet-webpack": "^1.0.11",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.25.0",
    "es6-shim": "^0.35.1",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^2.2.1",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "5.0.0-beta.12",
    "style-loader": "^0.13.0",
    "to-string-loader": "^1.1.5",
    "ts-loader": "^0.8.2",
    "typescript": "^2.0.0",
    "url-loader": "^0.5.7",
    "webpack": "^1.12.14",
    "webpack-externals-plugin": "^1.0.0",
    "webpack-hot-middleware": "^2.10.0",
    "webpack-merge": "^0.14.1",
    "zone.js": "^0.6.21"
  }
}
```

<p>"app.component.ts"</p>

<pre class="lang-js prettyprint-override"><code>import { Component, Inject } from '@angular/core';

@Component({
    selector: 'app',
    template: require('./app.component.html'),
    styles: [require('./app.component.css')]
})
export class AppComponent {
}

"app.module.ts"

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
//declare var localStorage: any;
// used to create fake backend
import { fakeBackendProvider } from './components/_helpers/index';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions, Http, HttpModule, Response } from '@angular/http';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { LoginComponent } from './components/login/index';
import { RegisterComponent } from './components/register/index';
import { AlertComponent } from './components/_directives/index';
import { AuthGuard } from './components/_guards/index';
import { AlertService, AuthenticationService, UserService, FetchDataService } from './components/_services/index';

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        LoginComponent,
        RegisterComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        //HttpModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'login', component: LoginComponent },
            { path: 'register', component: RegisterComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ],
    providers: [
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        FetchDataService,
        // providers used to create fake backend
        fakeBackendProvider,
        MockBackend,
        BaseRequestOptions
    ],
})
export class AppModule {
}
</code>```

"fetchdata.component.ts"  (in this calling service)

import { Component, OnInit } from '@angular/core';
import { Http, Response, HttpModule } from '@angular/http';
import { Observable } from "rxjs/Observable";
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Router } from '@angular/router';
import { AlertService, FetchDataService } from "../_services/index";

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})

export class FetchDataComponent implements OnInit{
    public forecasts: WeatherForecast[];
    array = Array<any>();
    loading: boolean;

    private baseUrl: string = 'http://localhost:2828/';

    //private fetchDataService: FetchDataService;
    constructor(
        private router: Router,
        private fetchDataService: FetchDataService,
        private alertService: AlertService,
        private http: Http) {
        //TRY-1
        //this.http.get(this.baseUrl + 'api/SampleData/WeatherForecasts')
        //    .catch((error: any) => Observable.throw(error.json().error || 'Server error'))
        //    .subscribe(result =>
        //    {
        //        this.forecasts = result.json();
        //    });

        //TRY-2
        //this.fetchDataService.getAll()
        //    .subscribe(
        //    data => {
        //        this.alertService.success('service called successfuly', true);
        //    },
        //    error => {
        //        this.alertService.error(error);
        //        this.loading = false;
        //    });

        //http.get('http://jsonplaceholder.typicode.com/photos/1')
        //    .map((res: Response) => res.json())
        //    .subscribe(res => {
        //        this.array = res;
        //        this.loading = false;
        //    });

        //TRY-3
        //http.get('/api/SampleData/WeatherForecasts')
        //    .catch((error: any) => Observable.throw(error.json().error || 'Server error'))
        //    .subscribe(result =>
        //    {
        //        this.forecasts = result.json();
        //    });
    }

    ngOnInit() {
        this.getMyData()
            .subscribe((res: any) => {
                console.log(res);
            },
            error => {
                // TODO: Error handling
                console.log(error);
            });
    }

    private getHeaders() {
        // I included these headers because otherwise FireFox
        // will request text/html instead of application/json
        let headers = new Headers();
        headers.append('Accept', 'application/json');
        return headers;
    }

    getMyData(): Observable<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get('http://jsonplaceholder.typicode.com/photos/1', headers)
            //.do(response => console.log("Result: " + JSON.stringify(response)))
            .map((res: Response) => {
                console.log(res);
                return res;
            })
            .catch((err) => {
                // TODO: Error handling
                console.log(err);
                return err;
            })
    };
}
```

Please let me know if anything wrong.

答:
It will be helpful to let know what error are you getting.
If you want to use headers, try changing

```<code>this.http.get('http://jsonplaceholder.typicode.com/photos/1', headers)`
</code>```

to

```<code>this.http.get('http://jsonplaceholder.typicode.com/photos/1', { headers: headers })
</code>```

Body:
Not able to call web api using http in angular2.
tried different solutions but still not help. So may opening new issue will help me.

tried below solutions but not helped:

http with Observable in Angular 2 cant use data

Angular2 - http.get not calling the webpi

why http.post didn't call my controller in angular 2

Below is the source - please let me know if i am doing anything wrong:

"package.json"

{
  "name": "Angular2Spa",
  "version": "0.0.0",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/platform-server": "2.0.0",
    "@angular/router": "3.0.0",
    "@types/node": "^6.0.38",
    "angular2-localstorage": "^0.4.0",
    "angular2-platform-node": "~2.0.10",
    "angular2-universal": "~2.0.10",
    "angular2-universal-polyfills": "~2.0.10",
    "aspnet-prerendering": "^1.0.6",
    "aspnet-webpack": "^1.0.11",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.25.0",
    "es6-shim": "^0.35.1",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^2.2.1",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "5.0.0-beta.12",
    "style-loader": "^0.13.0",
    "to-string-loader": "^1.1.5",
    "ts-loader": "^0.8.2",
    "typescript": "^2.0.0",
    "url-loader": "^0.5.7",
    "webpack": "^1.12.14",
    "webpack-externals-plugin": "^1.0.0",
    "webpack-hot-middleware": "^2.10.0",
    "webpack-merge": "^0.14.1",
    "zone.js": "^0.6.21"
  }
}

"app.component.ts"

import { Component, Inject } from '@angular/core';

@Component({
    selector: 'app',
    template: require('./app.component.html'),
    styles: [require('./app.component.css')]
})
export class AppComponent {
}

"app.module.ts"

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
//declare var localStorage: any;
// used to create fake backend
import { fakeBackendProvider } from './components/_helpers/index';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions, Http, HttpModule, Response } from '@angular/http';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { LoginComponent } from './components/login/index';
import { RegisterComponent } from './components/register/index';
import { AlertComponent } from './components/_directives/index';
import { AuthGuard } from './components/_guards/index';
import { AlertService, AuthenticationService, UserService, FetchDataService } from './components/_services/index';

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        LoginComponent,
        RegisterComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        //HttpModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'login', component: LoginComponent },
            { path: 'register', component: RegisterComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ],
    providers: [
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        FetchDataService,
        // providers used to create fake backend
        fakeBackendProvider,
        MockBackend,
        BaseRequestOptions
    ],
})
export class AppModule {
}

"fetchdata.component.ts"  (in this calling service)

import { Component, OnInit } from '@angular/core';
import { Http, Response, HttpModule } from '@angular/http';
import { Observable } from "rxjs/Observable";
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Router } from '@angular/router';
import { AlertService, FetchDataService } from "../_services/index";

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})

export class FetchDataComponent implements OnInit{
    public forecasts: WeatherForecast[];
    array = Array<any>();
    loading: boolean;

    private baseUrl: string = 'http://localhost:2828/';

    //private fetchDataService: FetchDataService;
    constructor(
        private router: Router,
        private fetchDataService: FetchDataService,
        private alertService: AlertService,
        private http: Http) {
        //TRY-1
        //this.http.get(this.baseUrl + 'api/SampleData/WeatherForecasts')
        //    .catch((error: any) => Observable.throw(error.json().error || 'Server error'))
        //    .subscribe(result =>
        //    {
        //        this.forecasts = result.json();
        //    });

        //TRY-2
        //this.fetchDataService.getAll()
        //    .subscribe(
        //    data => {
        //        this.alertService.success('service called successfuly', true);
        //    },
        //    error => {
        //        this.alertService.error(error);
        //        this.loading = false;
        //    });

        //http.get('http://jsonplaceholder.typicode.com/photos/1')
        //    .map((res: Response) => res.json())
        //    .subscribe(res => {
        //        this.array = res;
        //        this.loading = false;
        //    });

        //TRY-3
        //http.get('/api/SampleData/WeatherForecasts')
        //    .catch((error: any) => Observable.throw(error.json().error || 'Server error'))
        //    .subscribe(result =>
        //    {
        //        this.forecasts = result.json();
        //    });
    }

    ngOnInit() {
        this.getMyData()
            .subscribe((res: any) => {
                console.log(res);
            },
            error => {
                // TODO: Error handling
                console.log(error);
            });
    }

    private getHeaders() {
        // I included these headers because otherwise FireFox
        // will request text/html instead of application/json
        let headers = new Headers();
        headers.append('Accept', 'application/json');
        return headers;
    }

    getMyData(): Observable<any> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get('http://jsonplaceholder.typicode.com/photos/1', headers)
            //.do(response => console.log("Result: " + JSON.stringify(response)))
            .map((res: Response) => {
                console.log(res);
                return res;
            })
            .catch((err) => {
                // TODO: Error handling
                console.log(err);
                return err;
            })
    };
}

Please let me know if anything wrong.

Body:
It will be helpful to let know what error are you getting.
If you want to use headers, try changing

this.http.get('http://jsonplaceholder.typicode.com/photos/1', headers)`

to

this.http.get('http://jsonplaceholder.typicode.com/photos/1', { headers: headers })


来源: stackexchange

问:
Notepad++ RegEx
I am in need a reg ex for the following:

```<code>/****** Object: AnyNumberofCharacters ******/
</code>```

Here is what I have Tried but I cant make it work

```<code>/^\/\*\*\*\*\*\* Object\:.*\*\*\*\*\*\*\//
</code>```

Could someone tell me what I'm doing wrong?

Edited:  Sorry I'm using NotePad++ to search a number of text files for this string.

答:
Since you are using Notepad++ to find that string, you don't need the delimiters. And therefore, you don't need to escape the forward slashes either.</p>

```<code>^/\*\*\*\*\*\* Object\:.*\*\*\*\*\*\*/
</code>```

ContentLicense: CC BY-SA 3.0

Title: Notepad++ RegEx

Body:
I am in need a reg ex for the following:

/****** Object: AnyNumberofCharacters ******/

Here is what I have Tried but I cant make it work

/^\/\*\*\*\*\*\* Object\:.*\*\*\*\*\*\*\//

Could someone tell me what I'm doing wrong?

Edited:  Sorry I'm using NotePad++ to search a number of text files for this string.

Body:
Since you are using Notepad++ to find that string, you don't need the delimiters. And therefore, you don't need to escape the forward slashes either.

^/\*\*\*\*\*\* Object\:.*\*\*\*\*\*\*/


问:
NAT on TCP connections
When we establish a TCP connection from PC1 to Server and send data through this connection, how does the Router know to which of the two PCs (PC1 and PC2) should it communicate on the way back from Server to PC1?

And

How does ping (ICMP) know to which internal node it should send the answer?

答:
There is a large pool of resources describing NAT (Network Address Translation), which is available if you search "nat explained". A great resource is What is NAT and how it work tutorial.

The most important detail is that commonly we use NAPT (commonly used as PAT - Port Address Translation) (Network Address and Port Translation), alongside NAT.

When a device needs to use the Internet, it must open a local (source port) and send the IP request to the other end. For example, a notepad with source IP address 192.168.1.2 needs to communicate with a web server at 216.58.212.35.

It fires up random source port 1234 and requests information from target port 80 (HTTP - Web page).

This goes through the networks NAT device, which stores the information 192.168.1.2/1234 with the next information that it computes, and sends the request as 46.103.93.105 (its own IP public IP) and a new source port, for example 2345.

The web server responds to the NAT device, which in turn finds the correlated information (source port 2345 targets 192.168.1.2/1234). The notepad receives the information and displays it to the user.

Title: NAT on TCP connections


问:
Search icon not working in css
I am using the following code for css:

```<code>#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
</code>```

Search Box:

```<code><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
</code>```

It is looking like this:

However, I want the search box to look like this:

Please note that I have the png file in my css folder. This example is a replication of https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table.

答:
the URL path is only related to CSS style sheet location. So depending on where your style sheet is, it is a relative path to the img.

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document:

BODY { background: url(yellow) }

REF: https://www.w3.org/TR/REC-CSS1/#url

as others said, your url path is not correct, example:

#myInput {
  background-image: url(https://www.w3schools.com/css/searchicon.png);
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"></code>```

Title: Search icon not working in css

Body:
I am using the following code for css:

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

Search Box:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

It is looking like this:

However, I want the search box to look like this:

Please note that I have the png file in my css folder. This example is a replication of https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table.

Body:
the URL path is only related to CSS style sheet location. So depending on where your style sheet is, it is a relative path to the img.

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document:

BODY { background: url(yellow) }

REF: https://www.w3.org/TR/REC-CSS1/#url

as others said, your url path is not correct, example:

#myInput {
  background-image: url(https://www.w3schools.com/css/searchicon.png);
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">


问:
How can i move my UIImage vertically from top to bottom
i want the UIImage to move on the screen vertically downwards and when it reaches to the end it should again start from the top. how can i do it???

please help
Thanks

答:
This is how i wrote my code
moving.h

```<code>#import <UIKit/UIKit.h>
@interface movingViewController : UIViewController{
UIImageView *imageView1;
}
@property (retain , nonatomic) UIImageView *imageView1;
@end
</code>```

moving.m

```<code>#import "movingViewController.h"
@synthesize imageView1;
-(void) animate {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.3];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(myCallback:finished:context:)];

CGRect frame = imageView1.frame;
frame.origin = CGPointMake(0, 480)
imageView1.frame = frame;

[UIView commitAnimations];
}

- (void)viewDidLoad {

    [super viewDidLoad];
 }

 -(void)myCallback:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {

CGRect frame = imageView1.frame;
frame.origin = CGPointMake(0, 0)
imageView1.frame = frame;
[self animate];
}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];}
- (void)viewDidUnload {}
- (void)dealloc {
    [imageView1 dealloc];
    [imageView1 release];
    [super dealloc];
}
@end
</code>```

Im sorry to ask simple questions but im very new to Xcode

is that the correct way

ContentLicense: CC BY-SA 2.5

Body:
This is how i wrote my code
moving.h

#import <UIKit/UIKit.h>
@interface movingViewController : UIViewController{
UIImageView *imageView1;
}
@property (retain , nonatomic) UIImageView *imageView1;
@end

moving.m

#import "movingViewController.h"
@synthesize imageView1;
-(void) animate {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.3];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(myCallback:finished:context:)];

CGRect frame = imageView1.frame;
frame.origin = CGPointMake(0, 480)
imageView1.frame = frame;

[UIView commitAnimations];
}

- (void)viewDidLoad {

    [super viewDidLoad];
 }

 -(void)myCallback:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {

CGRect frame = imageView1.frame;
frame.origin = CGPointMake(0, 0)
imageView1.frame = frame;
[self animate];
}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];}
- (void)viewDidUnload {}
- (void)dealloc {
    [imageView1 dealloc];
    [imageView1 release];
    [super dealloc];
}
@end

Im sorry to ask simple questions but im very new to Xcode

is that the correct way


问:
Java Socket programming with GUI
i have write a code of GUI, and i want to make it as server client. how do i put the GUI code inside socket class? do i need to make a separate class for GUI or just put it inside socket server class?</p>

答: Classes are forms of subdivision provided for simplifying your files. There is no right or wrong way to do it. As far as you are concerned with Server-side GUI, it is just like normal GUI, but uses input from the socket. So, it doesn't really matter.

Title: Java Socket programming with GUI


问:
recursive iteration through python dictionary from mongo
This is the document I currently have in MongoDB.

```<code>{
"name":"food",
"core":{
    "group":{
         "carbs":{
            "abbreviation": "Cs"
            "USA":{
                "breakfast":"potatoes",
                "dinner":"pasta"
            },
            "europe":{
                "breakfast":"something",
                "dinner":"something big"
            }
        },
         "abbreviation": "Ds"
         "dessert":{
             "USA":{
                 "breakfast":"potatoes and eggs",
                 "dinner":"pasta"
        },
         "europe":{
                 "breakfast":"something small",
                 "dinner":"hello"
        }
    },
        "abbreviation": "Vs"
        "veggies":{
                        "USA":{
                                "breakfast":"broccoli",
                                "dinner":"salad"
                        },
                        "europe":{
                                "breakfast":"cheese",
                                "dinner":"asparagus"
                        }
                 }
            }
      }
 }
</code>```

I extract the data from mongo with the following lines of code.

```<code>data = collection.foodie.find({"name":"food"}, {"name":False, '_id':False})
def recursee(d):
    for k, v in d.items():
        if isinstance(v,dict):
            print recursee(d)
        else:
            print "{0} : {1}".format(k,v)
</code>```

However, when i run the recursee function, it fails to print group : carbs, group : dessert, or group : veggies.  Instead i get the below output.

```<code>breakfast : something big
dinner : something
None
abbreviation : Cs
breakfast : potatoes
dinner : pasta
None
None
breakfast : something small
dinner : hello
None
abbreviation : Ds
breakfast : potatoes and eggs
dinner : pasta
None
None
breakfast : cheese
dinner : asparagus
None
abbreviation : Vs
breakfast : broccoli
dinner : salad
</code>```

Am i skipping something in my recursion that is bypassing printing the group and corresponding value?

答:
From docs:

The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

Because your recursee has no return statement, i.e. it implicitly returns None, so next statement

```<code>print recursee(d)
</code>```

executes recursee with d object as an argument and prints function output (which is None)

Try

```<code>def recursee(d):
    for k, v in d.items():
        if isinstance(v, dict):
            print "{0} :".format(k)
            recursee(v)
        else:
            print "{0} : {1}".format(k, v)
</code>```

Body:
This is the document I currently have in MongoDB.

{
"name":"food",
"core":{
    "group":{
         "carbs":{
            "abbreviation": "Cs"
            "USA":{
                "breakfast":"potatoes",
                "dinner":"pasta"
            },
            "europe":{
                "breakfast":"something",
                "dinner":"something big"
            }
        },
         "abbreviation": "Ds"
         "dessert":{
             "USA":{
                 "breakfast":"potatoes and eggs",
                 "dinner":"pasta"
        },
         "europe":{
                 "breakfast":"something small",
                 "dinner":"hello"
        }
    },
        "abbreviation": "Vs"
        "veggies":{
                        "USA":{
                                "breakfast":"broccoli",
                                "dinner":"salad"
                        },
                        "europe":{
                                "breakfast":"cheese",
                                "dinner":"asparagus"
                        }
                 }
            }
      }
 }

I extract the data from mongo with the following lines of code.

data = collection.foodie.find({"name":"food"}, {"name":False, '_id':False})
def recursee(d):
    for k, v in d.items():
        if isinstance(v,dict):
            print recursee(d)
        else:
            print "{0} : {1}".format(k,v)

However, when i run the recursee function, it fails to print group : carbs, group : dessert, or group : veggies.  Instead i get the below output.

breakfast : something big
dinner : something
None
abbreviation : Cs
breakfast : potatoes
dinner : pasta
None
None
breakfast : something small
dinner : hello
None
abbreviation : Ds
breakfast : potatoes and eggs
dinner : pasta
None
None
breakfast : cheese
dinner : asparagus
None
abbreviation : Vs
breakfast : broccoli
dinner : salad

Am i skipping something in my recursion that is bypassing printing the group and corresponding value?

Body:
From docs:

The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

Because your recursee has no return statement, i.e. it implicitly returns None, so next statement

print recursee(d)

executes recursee with d object as an argument and prints function output (which is None)

Try

def recursee(d):
    for k, v in d.items():
        if isinstance(v, dict):
            print "{0} :".format(k)
            recursee(v)
        else:
            print "{0} : {1}".format(k, v)

ContentLicense: CC BY-SA 4.0


问:
Android: How to turn on screen when new notification received?
I've tried almost everything and I can't understand how to turn on phone screen when new notification received in background mode.

I'm using FCM. When app is in background, notifications received are managed by system tray. How can I ask system tray to turn on the screen when something new received? Thank you!

答:
Try This One

you have to do one thing, when you are showing notification, you have to Broadcast this intent.after generating notification in onMessageReceived(RemoteMessage remoteMessage) method of FirebaseMessagingService extended class

```<code>Intent in=new Intent(Intent.ACTION_POWER_CONNECTED);
        getActivity().sendBroadcast(in);
</code>```

Body:
Try This One

you have to do one thing, when you are showing notification, you have to Broadcast this intent.after generating notification in onMessageReceived(RemoteMessage remoteMessage) method of FirebaseMessagingService extended class

Intent in=new Intent(Intent.ACTION_POWER_CONNECTED);
        getActivity().sendBroadcast(in);


问:
Change image format using WebImage
I'm new to asp.net and I'm making a website with asp.net mvc 4 where user can upload any type of image(png, jpeg, gif) but system will save the image as a png format. I'm using WebImage helper. So far uploading is working fine but whenever system saves the image, filename looks like this, Filename.png.jpeg. Here is my codes from Controller,

```<code>if (file != null && file.ContentLength > 0)
{
    string picName = "FileName";
    WebImage img = new WebImage(file.InputStream);
    if (img.Width > 265 || img.Height > 158)
    {
        img.Resize(265, 158);
    }
    string picExt = Path.GetExtension(file.FileName);
    if (picExt == ".jpg")
    {
        picExt = ".png";
    }
    string path = System.IO.Path.Combine(Server.MapPath("~/Images/"), picName + picExt);
    img.Save(path);
}
</code>```

How can I save the image as only png format no matter what user uploads in any format of image? Need this help badly. Tnx.

答:
Just ran into the same issue. Please see here:
WebImage.Save Method

Cognis is half correct and it will probably work like that. However, the 2nd parameter actually tells it what format to save as:

imageFormat
 Type: System.String
The format to use when the image file
  is saved, such as "gif", or "png".

A jpeg doesn't become a png simply because you change the extension. Unless the Save method knows to reformat based on extension (???), I would rather error on the side of caution by doing:

```<code>img.Save(path, "png", false);
</code>```

Title: Change image format using WebImage

Body:
I'm new to asp.net and I'm making a website with asp.net mvc 4 where user can upload any type of image(png, jpeg, gif) but system will save the image as a png format. I'm using WebImage helper. So far uploading is working fine but whenever system saves the image, filename looks like this, Filename.png.jpeg. Here is my codes from Controller,

if (file != null && file.ContentLength > 0)
{
    string picName = "FileName";
    WebImage img = new WebImage(file.InputStream);
    if (img.Width > 265 || img.Height > 158)
    {
        img.Resize(265, 158);
    }
    string picExt = Path.GetExtension(file.FileName);
    if (picExt == ".jpg")
    {
        picExt = ".png";
    }
    string path = System.IO.Path.Combine(Server.MapPath("~/Images/"), picName + picExt);
    img.Save(path);
}

How can I save the image as only png format no matter what user uploads in any format of image? Need this help badly. Tnx.

Body:
Just ran into the same issue. Please see here:
WebImage.Save Method

Cognis is half correct and it will probably work like that. However, the 2nd parameter actually tells it what format to save as:

imageFormat
 Type: System.String
The format to use when the image file
  is saved, such as "gif", or "png".

A jpeg doesn't become a png simply because you change the extension. Unless the Save method knows to reformat based on extension (???), I would rather error on the side of caution by doing:

img.Save(path, "png", false);


问:
How to get dynamic fields by using ng-model
This is the expected markup which is created dynamically

```<code><textarea data-ng-model="cv.experience[content.title]"></textarea>
<textarea data-ng-model="cv.experience[content.title]"></textarea>
...
</code>```

This is the sample of the JSON I want to achieve

```<code>experience:{

    content:[
        {
            header:String,
            title:String,
            start_date:Date,
            end_date:Date,
            location:String,
            description:String
        },
        {
            header:String,
            title:String,
            start_date:Date,
            end_date:Date,
            location:String,
            description:String
        },
        ....
    ]
}
</code>```

How can i archive above structure using ng-model

答:
You're going to want to use ng-repeat for this:

This creates a textarea for each object in cv.experience.content and then binds ng-model to each object's title property. I think this is what you're after, yes?

```<code><textarea data-ng-model="content.title" data-ng-repeat="content in cv.experience.content">
</textarea>
</code>```

Body:
This is the expected markup which is created dynamically

<textarea data-ng-model="cv.experience[content.title]"></textarea>
<textarea data-ng-model="cv.experience[content.title]"></textarea>
...

This is the sample of the JSON I want to achieve

experience:{

    content:[
        {
            header:String,
            title:String,
            start_date:Date,
            end_date:Date,
            location:String,
            description:String
        },
        {
            header:String,
            title:String,
            start_date:Date,
            end_date:Date,
            location:String,
            description:String
        },
        ....
    ]
}

How can i archive above structure using ng-model

Body:
You're going to want to use ng-repeat for this:

This creates a textarea for each object in cv.experience.content and then binds ng-model to each object's title property. I think this is what you're after, yes?

<textarea data-ng-model="content.title" data-ng-repeat="content in cv.experience.content">
</textarea>


问:
std::max cannot be resolved after including <algorithm>
I am trying to write my own library for competitive programming contests, and I need such code:

```<code>#include <functional>
#include <algorithm>

template <typename T>
using binop = std::function<T (T, T)>;

int main()
{
    binop<int> op = std::max<int>;
}
</code>```

Unfortunately, it produces the following error:

```<code>error: conversion from '<unresolved overloaded function type>' to non-scalar type 'binop<int> {aka std::function<int(int, int)>}' requested
</code>```

But when I remove the line

```<code>#include <algorithm>
</code>```

it magically compiles. (though there shouldn't really be a max function defined)

The question is: how can I compile the code without removing "algorithm"?

Note that I have also tried this:

```<code>binop<int> op = (int(*)(int, int)) std::max<int>;
</code>```

which produces

```<code>error: insufficient contextual information to determine type
</code>```

答:
This is because there are multiple overloads of the same function.  This does not work for exactly the same reason that this does not work

```<code>void foo() {}
void foo(int) {}
void foo(double) {}

int main() {
    auto foo_ptr = &foo;
}
</code>```

To make your code work you would have to cast the function pointer to the right type to tell the compiler which overload you are referring to

```<code>#include <algorithm>

template <typename T>
using Func_t = std::function<T(T, T)>;

int main() {
    template <typename T>
    using MaxOverload_t = const T& (*) (const T&, const T&);

    auto f1 = static_cast<MaxOverload_t<int>>(&std::max<int>);
    auto f2 = Func_t<int>{static_cast<MaxOverload_t<int>>(&std::max<int>)};
}
</code>```

Body:
I am trying to write my own library for competitive programming contests, and I need such code:

#include <functional>
#include <algorithm>

template <typename T>
using binop = std::function<T (T, T)>;

int main()
{
    binop<int> op = std::max<int>;
}

Unfortunately, it produces the following error:

error: conversion from '<unresolved overloaded function type>' to non-scalar type 'binop<int> {aka std::function<int(int, int)>}' requested

But when I remove the line

#include <algorithm>

it magically compiles. (though there shouldn't really be a max function defined)

The question is: how can I compile the code without removing "algorithm"?

Note that I have also tried this:

binop<int> op = (int(*)(int, int)) std::max<int>;

which produces

error: insufficient contextual information to determine type

Body:
This is because there are multiple overloads of the same function.  This does not work for exactly the same reason that this does not work

void foo() {}
void foo(int) {}
void foo(double) {}

int main() {
    auto foo_ptr = &foo;
}

To make your code work you would have to cast the function pointer to the right type to tell the compiler which overload you are referring to

#include <algorithm>

template <typename T>
using Func_t = std::function<T(T, T)>;

int main() {
    template <typename T>
    using MaxOverload_t = const T& (*) (const T&, const T&);

    auto f1 = static_cast<MaxOverload_t<int>>(&std::max<int>);
    auto f2 = Func_t<int>{static_cast<MaxOverload_t<int>>(&std::max<int>)};
}


问:
Django server side caching of uploaded file
I am running a server in django and I want to serve a file. I am storing the file under '/upload/directory/filename' and I return it using

```<code>from django.shortcuts import redirect

file_path = '/upload/directory/filename'
return redirect(file_path)
</code>```

However, the file appears to have been cached to the first version that had been placed locally and is never updated. Even if I remove the file, the file is still served. I checked that if I change the path to 'upload/directory_2/filename then I correctly get my new file. What is going on and how can I fight this ?

This is happening locally and I am making a direct server request (hence there is no possibility of browser caching or anything else).

Additional information:

I understand that maybe I should be using static files, although for instance this answer suggests that it is quite debatable for files that I am uploading myself.

When I say "I want to serve files with django" I just mean that I have associated a file path to a particular entity in my database (using models.FileField) and based on what the user requests I want to return this file. I kind of doubt this is a clear cut for using static files in that case.

There are many workarounds to my issue, like generating unique filenames every time I want to "clear my cache" or explicitly opening the file:

```<code>with open(absolute_file_path) as file:
    response = HttpResponse(file.read(), content_type='application/octet-stream')
</code>```

My question was about understanding why the particular piece of code above does what it does, i.e. leads to data caching, and how to prevent this.

答:
There is a special HttpResponse in Django that can help you to serve a file easily.</p>

```<code>def file_dowload(request):
    file_name = request.GET.get('file_name', '')
    try:
        temp = open(file_name, 'rb')
    except IOError:
        temp = None
    if not temp:
        return HttpResponse("Not found")
    response = FileResponse(temp, content_type='text/plain')

    return response
</code>```

Body:
I am running a server in django and I want to serve a file. I am storing the file under '/upload/directory/filename' and I return it using

from django.shortcuts import redirect

file_path = '/upload/directory/filename'
return redirect(file_path)

However, the file appears to have been cached to the first version that had been placed locally and is never updated. Even if I remove the file, the file is still served. I checked that if I change the path to 'upload/directory_2/filename then I correctly get my new file. What is going on and how can I fight this ?

This is happening locally and I am making a direct server request (hence there is no possibility of browser caching or anything else).

Additional information:

I understand that maybe I should be using static files, although for instance this answer suggests that it is quite debatable for files that I am uploading myself.

When I say "I want to serve files with django" I just mean that I have associated a file path to a particular entity in my database (using models.FileField) and based on what the user requests I want to return this file. I kind of doubt this is a clear cut for using static files in that case.

There are many workarounds to my issue, like generating unique filenames every time I want to "clear my cache" or explicitly opening the file:

with open(absolute_file_path) as file:
    response = HttpResponse(file.read(), content_type='application/octet-stream')

My question was about understanding why the particular piece of code above does what it does, i.e. leads to data caching, and how to prevent this.

Body:
There is a special HttpResponse in Django that can help you to serve a file easily.

def file_dowload(request):
    file_name = request.GET.get('file_name', '')
    try:
        temp = open(file_name, 'rb')
    except IOError:
        temp = None
    if not temp:
        return HttpResponse("Not found")
    response = FileResponse(temp, content_type='text/plain')

    return response


问:
Intramolecular protein residue contact map using biopython, KeyError: 'CA'
I am trying to identify amino acid residues in contact in the 3D protein structure. I am new to BioPython but found this helpful website http://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/protein_contact_map/

Following their lead (which I will reproduce here for completion; Note, however, that I am using a different protein):

```<code>import Bio.PDB
import numpy as np

pdb_code = "1QHW"
pdb_filename = "1qhw.pdb"

def calc_residue_dist(residue_one, residue_two) :
    """Returns the C-alpha distance between two residues"""
    diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord
    return np.sqrt(np.sum(diff_vector * diff_vector))

def calc_dist_matrix(chain_one, chain_two) :
    """Returns a matrix of C-alpha distances between two chains"""
    answer = np.zeros((len(chain_one), len(chain_two)), np.float)
    for row, residue_one in enumerate(chain_one) :
        for col, residue_two in enumerate(chain_two) :
            answer[row, col] = calc_residue_dist(residue_one, residue_two)
    return answer

structure = Bio.PDB.PDBParser().get_structure(pdb_code, pdb_filename)
model = structure[0]

dist_matrix = calc_dist_matrix(model["A"], model["A"])
</code>```

But when I run the above code, I get the following error message:

```<code>Traceback (most recent call last):

  File "<ipython-input-26-7239fb7ebe14>", line 4, in <module>
    dist_matrix = calc_dist_matrix(model["A"], model["A"])

  File "<ipython-input-3-730a11883f27>", line 15, in calc_dist_matrix
    answer[row, col] = calc_residue_dist(residue_one, residue_two)

  File "<ipython-input-3-730a11883f27>", line 6, in calc_residue_dist
    diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord

  File "/Users/anaconda/lib/python3.6/site-packages/Bio/PDB/Entity.py", line 39, in __getitem__
    return self.child_dict[id]

KeyError: 'CA'
</code>```

Any suggestions on how to fix this issue?

答:
So I've been testing (bear in mind I know very little about Bio) and it looks like whatever is in you 1qhw.pdb file is very different from the one in that example.

```<code>pdb_code = '1qhw'
structure = Bio.PDB.PDBParser().get_structure(pdb_code, pdb_filename)
model = structure[0]
</code>```

next, to see what is in it, I did:

```<code>print(list(model))
</code>```

Which gave me:

```<code>[<Chain id=A>]
</code>```

exploring this, it appears the pdb file is a dict of dicts.  So, using this id,

```<code>test = model['A']
</code>```

gives me the next dict.  This level is the level being passed to your function that is causing the error.  Printing this with:

```<code>print(list(test))
</code>```

Gave me a huge list of the data inside, including lots of residues and related info.  But crucially, no CA.  Try using this to see whats inside and modify the line:

```<code>diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord
</code>```

to reflect what you are after, replacing CA where appropriate.
I hope this helps, its a little tricky to get much more specific.

Body:
I am trying to identify amino acid residues in contact in the 3D protein structure. I am new to BioPython but found this helpful website http://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/protein_contact_map/

Following their lead (which I will reproduce here for completion; Note, however, that I am using a different protein):

import Bio.PDB
import numpy as np

pdb_code = "1QHW"
pdb_filename = "1qhw.pdb"

def calc_residue_dist(residue_one, residue_two) :
    """Returns the C-alpha distance between two residues"""
    diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord
    return np.sqrt(np.sum(diff_vector * diff_vector))

def calc_dist_matrix(chain_one, chain_two) :
    """Returns a matrix of C-alpha distances between two chains"""
    answer = np.zeros((len(chain_one), len(chain_two)), np.float)
    for row, residue_one in enumerate(chain_one) :
        for col, residue_two in enumerate(chain_two) :
            answer[row, col] = calc_residue_dist(residue_one, residue_two)
    return answer

structure = Bio.PDB.PDBParser().get_structure(pdb_code, pdb_filename)
model = structure[0]

dist_matrix = calc_dist_matrix(model["A"], model["A"])

But when I run the above code, I get the following error message:

Traceback (most recent call last):

  File "<ipython-input-26-7239fb7ebe14>", line 4, in <module>
    dist_matrix = calc_dist_matrix(model["A"], model["A"])

  File "<ipython-input-3-730a11883f27>", line 15, in calc_dist_matrix
    answer[row, col] = calc_residue_dist(residue_one, residue_two)

  File "<ipython-input-3-730a11883f27>", line 6, in calc_residue_dist
    diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord

  File "/Users/anaconda/lib/python3.6/site-packages/Bio/PDB/Entity.py", line 39, in __getitem__
    return self.child_dict[id]

KeyError: 'CA'

Any suggestions on how to fix this issue?

Body:
So I've been testing (bear in mind I know very little about Bio) and it looks like whatever is in you 1qhw.pdb file is very different from the one in that example.

pdb_code = '1qhw'
structure = Bio.PDB.PDBParser().get_structure(pdb_code, pdb_filename)
model = structure[0]

next, to see what is in it, I did:

print(list(model))

Which gave me:

[<Chain id=A>]

exploring this, it appears the pdb file is a dict of dicts.  So, using this id,

test = model['A']

gives me the next dict.  This level is the level being passed to your function that is causing the error.  Printing this with:

print(list(test))

Gave me a huge list of the data inside, including lots of residues and related info.  But crucially, no CA.  Try using this to see whats inside and modify the line:

diff_vector  = residue_one["CA"].coord - residue_two["CA"].coord

to reflect what you are after, replacing CA where appropriate.
I hope this helps, its a little tricky to get much more specific.


问:
Unable to make dataframe because read_csv whitespace separation not constant
I am trying to make this text file (philadelphia.txt) into a pandas dataframe:

```<code>STATION           STATION_NAME                                       DATE     TAVG     TMAX     TMIN
----------------- -------------------------------------------------- -------- -------- -------- --------
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970605 -9999    74       47
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970606 -9999    68       50
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970608 -9999    72       50
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970609 -9999    83       47
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970610 -9999    86       55
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970611 -9999    88       61
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970612 -9999    83       70
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970613 -9999    80       66
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970614 -9999    80       64
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970615 -9999    77       55
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970616 -9999    79       49
</code>```

However, if I use

```<code>data = pd.read_csv('philadelphia.txt', sep="\s+", header=0)
</code>```

It makes a correct header, but then runs into the issue of splitting the station name data. I want it to be contained under the column name "STATION_NAME", but sep="\s+" splits it at the spaces and I get an error.

```<code>pandas.errors.ParserError: Error tokenizing data. C error: Expected 6 fields in line 3, saw 11
</code>```

How do I separate the data into 6 columns, without splitting the station name into individual words?

I also want to be able to pass in other text documents with different station names such as (yellowknife.txt).

```<code>STATION           STATION_NAME                                       DATE     TMAX     TMIN
----------------- -------------------------------------------------- -------- -------- --------
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130117 -21      -35
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130118 -15      -21
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130119 -17      -29
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130120 -18      -28
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130121 -21      -34
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130122 -16      -30
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130123 -17      -28
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130124 -5       -17
</code>```

答:
Use read_fwf() method:

```<code>In [7]: df = pd.read_fwf(r'/path/to/file.csv').drop(0)

In [8]: df
Out[8]:
              STATION                                STATION_NAME      DATE   TAVG TMAX TMIN
1   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970605  -9999   74   47
2   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970606  -9999   68   50
3   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970608  -9999   72   50
4   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970609  -9999   83   47
5   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970610  -9999   86   55
6   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970611  -9999   88   61
7   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970612  -9999   83   70
8   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970613  -9999   80   66
9   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970614  -9999   80   64
10  GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970615  -9999   77   55
11  GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970616  -9999   79   49
</code>```

Columns:

```<code>In [9]: df.columns.tolist()
Out[9]: ['STATION', 'STATION_NAME', 'DATE', 'TAVG', 'TMAX', 'TMIN']
</code>```

Body:
I am trying to make this text file (philadelphia.txt) into a pandas dataframe:

STATION           STATION_NAME                                       DATE     TAVG     TMAX     TMIN
----------------- -------------------------------------------------- -------- -------- -------- --------
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970605 -9999    74       47
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970606 -9999    68       50
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970608 -9999    72       50
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970609 -9999    83       47
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970610 -9999    86       55
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970611 -9999    88       61
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970612 -9999    83       70
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970613 -9999    80       66
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970614 -9999    80       64
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970615 -9999    77       55
GHCND:USW00094732         PHILADELPHIA NE PHILADELPHIA AIRPORT PA US 19970616 -9999    79       49

However, if I use

data = pd.read_csv('philadelphia.txt', sep="\s+", header=0)

It makes a correct header, but then runs into the issue of splitting the station name data. I want it to be contained under the column name "STATION_NAME", but sep="\s+" splits it at the spaces and I get an error.

pandas.errors.ParserError: Error tokenizing data. C error: Expected 6 fields in line 3, saw 11

How do I separate the data into 6 columns, without splitting the station name into individual words?

I also want to be able to pass in other text documents with different station names such as (yellowknife.txt).

STATION           STATION_NAME                                       DATE     TMAX     TMIN
----------------- -------------------------------------------------- -------- -------- --------
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130117 -21      -35
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130118 -15      -21
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130119 -17      -29
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130120 -18      -28
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130121 -21      -34
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130122 -16      -30
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130123 -17      -28
GHCND:CA002204101                                   YELLOWKNIFE A CA 20130124 -5       -17

Body:
Use read_fwf() method:

In [7]: df = pd.read_fwf(r'/path/to/file.csv').drop(0)

In [8]: df
Out[8]:
              STATION                                STATION_NAME      DATE   TAVG TMAX TMIN
1   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970605  -9999   74   47
2   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970606  -9999   68   50
3   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970608  -9999   72   50
4   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970609  -9999   83   47
5   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970610  -9999   86   55
6   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970611  -9999   88   61
7   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970612  -9999   83   70
8   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970613  -9999   80   66
9   GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970614  -9999   80   64
10  GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970615  -9999   77   55
11  GHCND:USW00094732  PHILADELPHIA NE PHILADELPHIA AIRPORT PA US  19970616  -9999   79   49

Columns:

In [9]: df.columns.tolist()
Out[9]: ['STATION', 'STATION_NAME', 'DATE', 'TAVG', 'TMAX', 'TMIN']


问:
Python next iterator in a loop
I have a small routine like this:

```<code>to_use = [True] * n
val = 0
while (val is not None) :
   # various manipulations on val
   # so the val below is different from
   # val entering the loop
   to_use[val] = False
   val = next((i for i in range(n) if to_use[i]),None)
</code>```

In my sample, n is of the order of a millon. Is the last like with the iterator the most efficient way to get the next "val"?. Or will it go through to_use from 0 each time in the loop? Note that once to_use[i]=False, its never reset to True.

答:
Another approach would be to make to_use a set of values instead:

```<code>to_use = set(range(n))

while len(to_use) > 0:
    val = min(to_use)
    # val manipulation here
    to_use.remove(val)
</code>```

Note that this approach requires scanning through all the remaining values at each iteration. On average, per iteration, it scans through n/2 values. Your original approach may be faster or slower than that depending on which elements of the list get set to False in which order. (If you tend to set things to False from the end of the list, your approach may already be faster. If you tend to set things to False from the beginning of the list, this set approach may be faster.)

Title: Python next iterator in a loop

Body:
I have a small routine like this:

to_use = [True] * n
val = 0
while (val is not None) :
   # various manipulations on val
   # so the val below is different from
   # val entering the loop
   to_use[val] = False
   val = next((i for i in range(n) if to_use[i]),None)

In my sample, n is of the order of a millon. Is the last like with the iterator the most efficient way to get the next "val"?. Or will it go through to_use from 0 each time in the loop? Note that once to_use[i]=False, its never reset to True.

Body:
Another approach would be to make to_use a set of values instead:

to_use = set(range(n))

while len(to_use) > 0:
    val = min(to_use)
    # val manipulation here
    to_use.remove(val)

Note that this approach requires scanning through all the remaining values at each iteration. On average, per iteration, it scans through n/2 values. Your original approach may be faster or slower than that depending on which elements of the list get set to False in which order. (If you tend to set things to False from the end of the list, your approach may already be faster. If you tend to set things to False from the beginning of the list, this set approach may be faster.)


问:
after_commit fires but attribute changes are not captured
So I am encountering something a bit weird and need help

I have the following three models and their relationships are shown below

```<code>class Assignment < ActiveRecord::Base
  belongs_to :case_status
  has_one :application, :through => :case_status, :autosave => false
  after_create :update_status

  def update_status
    self.case_status.update_attributes!({loan_case_id: update_case_status_id})
  end
end

class CaseStatus < ActiveRecord::Base
  belongs_to: application
  has_many :assignments, :dependent => :destroy
  accepts_nested_attributes_for :assignments,
                                :allow_destroy => true,
                                reject_if: proc { |attr| attr["lender_id"].blank? && attr["banker_id"].blank? }

  after_commit :catch_previous_changes,on: :update

  def catch_previous_changes
    self.previous_changes
  end
end

class Application < ActiveRecord::Base
  has_one :case_status, :dependent => :destroy
end
</code>```

Basically, when an assignment is created, there is a method that updates the loan_case_id of that record on the case_status model but when the self.versions code is called, it is always empty.

But when I check the record on rails console, the data has been updated which leads me to understand that the after_commit call is being triggered but somewhat ahead of the thread that has the previous changes of the attribute loan_case_id.

Now I don't know how to debug this to know why this is happening because it only happens when d update is done via the after_create method. Any other form where the loan_case_id gets updated always has data when the self.previous_changes is called.

答:
You can not get any of the dirty changes from after_commit, you have to use around_save, similar to this:

```<code>class CaseStatus < ActiveRecord::Base
  # all other code removed for brevity

  around_save :catch_previous_changes, on: :update

  def catch_previous_changes
    # see what attributes changed
    yield
    if persisted?
      # maybe do so other stuff if everything is ok
    end
  end
end
</code>```

Body:
So I am encountering something a bit weird and need help

I have the following three models and their relationships are shown below

class Assignment < ActiveRecord::Base
  belongs_to :case_status
  has_one :application, :through => :case_status, :autosave => false
  after_create :update_status

  def update_status
    self.case_status.update_attributes!({loan_case_id: update_case_status_id})
  end
end

class CaseStatus < ActiveRecord::Base
  belongs_to: application
  has_many :assignments, :dependent => :destroy
  accepts_nested_attributes_for :assignments,
                                :allow_destroy => true,
                                reject_if: proc { |attr| attr["lender_id"].blank? && attr["banker_id"].blank? }

  after_commit :catch_previous_changes,on: :update

  def catch_previous_changes
    self.previous_changes
  end
end

class Application < ActiveRecord::Base
  has_one :case_status, :dependent => :destroy
end

Basically, when an assignment is created, there is a method that updates the loan_case_id of that record on the case_status model but when the self.versions code is called, it is always empty.

But when I check the record on rails console, the data has been updated which leads me to understand that the after_commit call is being triggered but somewhat ahead of the thread that has the previous changes of the attribute loan_case_id.

Now I don't know how to debug this to know why this is happening because it only happens when d update is done via the after_create method. Any other form where the loan_case_id gets updated always has data when the self.previous_changes is called.

Body:
You can not get any of the dirty changes from after_commit, you have to use around_save, similar to this:

class CaseStatus < ActiveRecord::Base
  # all other code removed for brevity

  around_save :catch_previous_changes, on: :update

  def catch_previous_changes
    # see what attributes changed
    yield
    if persisted?
      # maybe do so other stuff if everything is ok
    end
  end
end


问:
Bootstrap form not in the center of the div
I have a bootstraap form where two field I have added the class .d-inline-block so that it comes next to each other and I have another field where I have not added the class so that It comes below of the two field.

I want this to be in the center of the div which I am not able to do it. Only the first two fields are coming to center but not the last div.

Can someone point out the mistake?

@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css' );

.d-inline-block {

  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="formClass ">
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="nameInput">
    <div class="form-control-placeholder"> Name </div>
  </div>
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>

  <div class="form-group message">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>
</form></code>```

https://jsfiddle.net/97avbgsq/

答:
Using bootstrap 4, you can use the helper classes .d-flex .flex-wrap .justify-content-center on the parent.

.d-inline-block {
  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<form class="formClass d-flex flex-wrap justify-content-center">
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="nameInput">
    <div class="form-control-placeholder"> Name </div>
  </div>
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>

  <div class="form-group message">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>
</form></code>```

But if you want to use your original code, to horizontally center a block element with a width, use margin-left: auto; margin-right: auto or margin: auto for short if that works for you. You can also do that using the .mx-auto bootstrap helper class.

.d-inline-block {
  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<form class="formClass ">
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="nameInput">
    <div class="form-control-placeholder"> Name </div>
  </div>
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>

  <div class="form-group message mx-auto">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>
</form></code>```

Body:
I have a bootstraap form where two field I have added the class .d-inline-block so that it comes next to each other and I have another field where I have not added the class so that It comes below of the two field.

I want this to be in the center of the div which I am not able to do it. Only the first two fields are coming to center but not the last div.

Can someone point out the mistake?

@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css' );

.d-inline-block {

  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}

<form class="formClass ">

    <input type="text" class="form-control" id="nameInput">

 Name

    <input type="text" class="form-control" id="phoneInput">

 Phone

    <input type="text" class="form-control" id="phoneInput">

 Phone

</form>

https://jsfiddle.net/97avbgsq/

Body:
Using bootstrap 4, you can use the helper classes .d-flex .flex-wrap .justify-content-center on the parent.

.d-inline-block {
  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<form class="formClass d-flex flex-wrap justify-content-center">
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="nameInput">
    <div class="form-control-placeholder"> Name </div>
  </div>
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>

  <div class="form-group message">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>
</form>

But if you want to use your original code, to horizontally center a block element with a width, use margin-left: auto; margin-right: auto or margin: auto for short if that works for you. You can also do that using the .mx-auto bootstrap helper class.

.d-inline-block {
  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<form class="formClass ">
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="nameInput">
    <div class="form-control-placeholder"> Name </div>
  </div>
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>

  <div class="form-group message mx-auto">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>
</form>


问:
Rendering Problems @id/visible Android Studio
I have this xml file. If I compile it works fine, but if I go to see the preview it shows me this error:

I tried to look for this id but I couldn't find it anywhere.
What is this @id/visible? How can I fix that?
Thanks

答:
You should set
1. android:id="@+id/visible" to android.support.design.widget.TextInputLayout and 2. android:id="@+id/masked" to child of TextInputLayout</p>


问:
Remove objects from array of objects swift
I have an issue and need your help.
I have array of objects

```<code>var arrayDirection: [Directions]
</code>```

every object has properties:

```<code>var name: String?
var uniqueId: Int?
</code>```

I need find and leave only one object whose values of properties duplicate values of properties of another objects from that array.

For example I print in console:

```<code>for object in arrayDirection {
    print(object.name, object.uniqueId)
}
</code>```

and see:

Optional("name1") Optional(833)

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name4") Optional(833)

Optional("name1") Optional(833)

Optional("name1") Optional(862)

So, I need remove Optional("name1") Optional(833) because there are 3 in array and leave only one as result I'd like to see:

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name3") Optional(833)

Optional("name1") Optional(862)

答:
Actually you need to remove duplicate from your data set. This link will help what you want to achieve.

However in short, use Set to avoid duplicate data.

Body:
I have an issue and need your help.
I have array of objects

var arrayDirection: [Directions]

every object has properties:

var name: String?
var uniqueId: Int?

I need find and leave only one object whose values of properties duplicate values of properties of another objects from that array.

For example I print in console:

for object in arrayDirection {
    print(object.name, object.uniqueId)
}

and see:

Optional("name1") Optional(833)

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name4") Optional(833)

Optional("name1") Optional(833)

Optional("name1") Optional(862)

So, I need remove Optional("name1") Optional(833) because there are 3 in array and leave only one as result I'd like to see:

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name3") Optional(833)

Optional("name1") Optional(862)


问:
Hosting Public websites with Django Dev Server
I am trying to host my personal website, I am new to hosting websites business, so this may be a Noob question.

So I made my website using django, and tested everything locally. Now I want to make the site public, then I came across this :
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment
which seemed to be a pain in the arse.

But, Then I figured i could make the website available on all interfaces using:

python manage.py runserver 0.0.0.0:80
  Now I can access the website using  http://myIp/myapp

So my question is, "Is it a good idea to host websites using the django dev server"

The gut feeling is a "No", but I really want to know "Why?"

答:
Your gut feeling is right. You better use a WSGI server that is going to serve your django app.
It is not that hard to configure.

Personally I like to use Gunicorn, which is easy to set up. Setting it up may look something like this:

```<code>gunicorn mirador_django.wsgi:application \
  --bind 0.0.0.0:8000 \
  --workers 4
</code>```

(see : http://docs.gunicorn.org/en/latest/run.html)

I then set a reverse proxy on my web server to point on the Gunicorn. For Nginx the info are on the gunicorn website: http://gunicorn.org/#deployment
You can also easily set it up on an apache server as I am currently doing.

Hope it can help.

Body:
Your gut feeling is right. You better use a WSGI server that is going to serve your django app.
It is not that hard to configure.

Personally I like to use Gunicorn, which is easy to set up. Setting it up may look something like this:

gunicorn mirador_django.wsgi:application \
  --bind 0.0.0.0:8000 \
  --workers 4

(see : http://docs.gunicorn.org/en/latest/run.html)

I then set a reverse proxy on my web server to point on the Gunicorn. For Nginx the info are on the gunicorn website: http://gunicorn.org/#deployment
You can also easily set it up on an apache server as I am currently doing.

Hope it can help.


问:
How does the following linked list work in python?
Following is the code to create a linked list from scratch in python.Only the append function is done here:

```<code>class Element(object):
    def __init__(self, value):
        self.value = value
        self.next = None
class LinkedList(object):

    def __init__(self, head=None):
        self.head = head

    def append(self, new_element):
        current = self.head
        if self.head:
            while current.next:
                current = current.next
            current.next = new_element
        else:
            self.head = new_element
</code>```

I do not completely understand how the lines work

```<code>            current = current.next
        current.next = new_element
</code>```

I realize that the first line is to move along the linked list(like an increment) and the second line is to link the address of the previous node to the next element of the linked list.But could someone please explain how this actually works on a deeper level as in what is assigned to what (what kind of variables they are, assignment an address or a value)

答:
well 'current=current.next statement means you are going to the node which contains address of None in its next field because that will be the terminating node of your linked list and after that you have to add the new node which will be done by the statement current.next=element(7) See the program given below it will show you how to create a singly linked list in python... Hope it helps you.... and for insertion at beginning or any other position in linked list click here

```<code>class Node:
   def __init__(self,data,next=None):
   self.data=data
   self.next=None

class LinkedList():
   def __init__(self):
   self.head=None

   def insert(self,data):
      if(self.head==None):
         n=Node(data)
         self.head=n
         return
      else:
         current=self.head
         while(current.next!=None):
             current=current.next
         current.next=Node(data)
         return
   def printing(self):
      if(self.head==None):
         print "Linked List is empty"
      else:
         current=self.head
         while(current!=None):
            print current.data,
            current=current.next
myLinkList=LinkedList()
myLinkList.insert(18)
myLinkList.insert(20)
myLinkList.insert(56)
myLinkList.insert(50)
print("\n\nThe created Singly Linked List is: \n\n")
myLinkList.printing()
print("\n\n")
</code>```

Body:
Following is the code to create a linked list from scratch in python.Only the append function is done here:

class Element(object):
    def __init__(self, value):
        self.value = value
        self.next = None
class LinkedList(object):

    def __init__(self, head=None):
        self.head = head

    def append(self, new_element):
        current = self.head
        if self.head:
            while current.next:
                current = current.next
            current.next = new_element
        else:
            self.head = new_element

I do not completely understand how the lines work

            current = current.next
        current.next = new_element

I realize that the first line is to move along the linked list(like an increment) and the second line is to link the address of the previous node to the next element of the linked list.But could someone please explain how this actually works on a deeper level as in what is assigned to what (what kind of variables they are, assignment an address or a value)

Body:
well 'current=current.next statement means you are going to the node which contains address of None in its next field because that will be the terminating node of your linked list and after that you have to add the new node which will be done by the statement current.next=element(7) See the program given below it will show you how to create a singly linked list in python... Hope it helps you.... and for insertion at beginning or any other position in linked list click here

class Node:
   def __init__(self,data,next=None):
   self.data=data
   self.next=None

class LinkedList():
   def __init__(self):
   self.head=None

   def insert(self,data):
      if(self.head==None):
         n=Node(data)
         self.head=n
         return
      else:
         current=self.head
         while(current.next!=None):
             current=current.next
         current.next=Node(data)
         return
   def printing(self):
      if(self.head==None):
         print "Linked List is empty"
      else:
         current=self.head
         while(current!=None):
            print current.data,
            current=current.next
myLinkList=LinkedList()
myLinkList.insert(18)
myLinkList.insert(20)
myLinkList.insert(56)
myLinkList.insert(50)
print("\n\nThe created Singly Linked List is: \n\n")
myLinkList.printing()
print("\n\n")


问:
how does first generation iPhone camera video?
There are some apps that let the first generation iPhone record video with a reasonable quality. My question is, which api do those apps use? Do they use custom code for compression to mpeg? And how do they gather so many images per second from the camera, which does only allow to take still pictures? The takePicture function of UIImagePickerController would be too slow for that.

答:
"This app works by using the long-blacklisted UIGetScreenImage() function that I've written about in the past. (I discovered this use by scanning the application using my APIkit scanner.) Apple must have willingly given the go-ahead for its use, as their automated scanning must have picked the same function call. Good news on the "more flexible review" front. Since Apple recently gave the green light to the UStream video app, with Qik hot on its heels, it's likely we'll see more of these applications that provide iPhone video functionality for livecasting or recording from your device." - http://www.tuaw.com/2009/12/14/app-store-approved-app-brings-video-recording-to-iphone-3g-and-1/

My summary: I think that the app opens a "Take a picture" type of view, and then "records the screen and saves to video" by using the UIGetScreenImage() API.


答:
There are multiple overloads for std::max.  Even specifying a template type is not enough as you have

```<code>template< class T >
const T& max( const T& a, const T& b );

//and

template< class T >
T max( std::initializer_list<T> ilist );
</code>```

The compiler cannot decide which one of those you want.

To get around this we can use a lambda and wrap that around the call to max like

```<code>binop<int> op = [](const auto& lhs, const auto& rhs){ return std::max(lhs, rhs); };
</code>```

Title: std::max cannot be resolved after including <algorithm>

Body:
I am trying to write my own library for competitive programming contests, and I need such code:

#include <functional>
#include <algorithm>

template <typename T>
using binop = std::function<T (T, T)>;

int main()
{
    binop<int> op = std::max<int>;
}

Unfortunately, it produces the following error:

error: conversion from '<unresolved overloaded function type>' to non-scalar type 'binop<int> {aka std::function<int(int, int)>}' requested

But when I remove the line

#include <algorithm>

it magically compiles. (though there shouldn't really be a max function defined)

The question is: how can I compile the code without removing "algorithm"?

Note that I have also tried this:

binop<int> op = (int(*)(int, int)) std::max<int>;

which produces

error: insufficient contextual information to determine type

Body:
There are multiple overloads for std::max.  Even specifying a template type is not enough as you have

template< class T >
const T& max( const T& a, const T& b );

//and

template< class T >
T max( std::initializer_list<T> ilist );

The compiler cannot decide which one of those you want.

To get around this we can use a lambda and wrap that around the call to max like

binop<int> op = [](const auto& lhs, const auto& rhs){ return std::max(lhs, rhs); };


问:
Rails: Validating min and max length of a string but allowing it to be blank
I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am using the below validations in the model, but this doesn't allow the user to leave it blank:

```<code>validates_length_of :foo, :maximum => 5
validates_length_of :foo, :minimum => 5
</code>```

How do I write this to accomplish my goal?

答:
every validates_* accepts :if or :unless options

```<code>validates_length_of :foo, :maximum => 5, :if => :validate_foo_condition
</code>```

where validate_foo_condition is method that returns true or false

you can also pass a Proc object:

```<code>validates_length_of :foo, :maximum => 5, :unless => Proc.new {|object| object.foo.blank?}
</code>```

Body:
I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am using the below validations in the model, but this doesn't allow the user to leave it blank:

validates_length_of :foo, :maximum => 5
validates_length_of :foo, :minimum => 5

How do I write this to accomplish my goal?

Body:
every validates_* accepts :if or :unless options

validates_length_of :foo, :maximum => 5, :if => :validate_foo_condition

where validate_foo_condition is method that returns true or false

you can also pass a Proc object:

validates_length_of :foo, :maximum => 5, :unless => Proc.new {|object| object.foo.blank?}


问:
Using node modules in zeit/next.js
I have simple application on isomorphic react (zeit/next.js https://github.com/zeit/next.js).
How can I use node modules on server side?

Code example:

```<code>import React from 'react'

export default class extends React.Component {
        static async getInitialProps({ req }) {
            const isServer = !!req;
            if (isServer){
                // how!?
            }
            return {
                isServer: isServer
            }
        }

        render() {
            return (
                <div>test</div>
            )
        }
    }
</code>```

答:
you also may want to use a custom server.js to send some data from the server in the request object.

like

const dev = process.env.NODE_ENV !== 'production'

const { createServer } = require('http')
const { parse } = require('url')
const { readFileSync } = require('fs')
const next = require('next')
const mobxReact = require('mobx-react')
const app = next({ dev })
const handle = app.getRequestHandler()

mobxReact.useStaticRendering(true)

app.prepare()
  .then(() => {
    createServer((req, res) => {
      const parsedUrl = parse(req.url, true)
      req.rules = JSON.parse(readFileSync('./micro/rules.json', 'utf8')).rules
      handle(req, res, parsedUrl)
    })
      .listen(3000, err => {
        if (err) throw err
        console.log('> Ready')
      })
  })```

Title: Using node modules in zeit/next.js

Body:
I have simple application on isomorphic react (zeit/next.js https://github.com/zeit/next.js).
How can I use node modules on server side?

Code example:

import React from 'react'

export default class extends React.Component {
        static async getInitialProps({ req }) {
            const isServer = !!req;
            if (isServer){
                // how!?
            }
            return {
                isServer: isServer
            }
        }

        render() {
            return (

test

            )
        }
    }


问:
Preventing a thread from being created when memory is low
I have an application that handles TCP connections, and when a connection is made, BeginRead is called on the stream to wait for data, and the main thread resumes waiting for new connections.

Under normal circumstances, there will be only a few connections at a time, and so generally the number of worker threads created by BeginRead is not an issue. However, in the theoretical situation that many, many connections exist at the same time, eventually when a new connection is made, the call to BeginRead causes an OutOfMemoryException. I would like to prevent the thread from being created in this situation (or be informed of a better way to wait for data from multiple streams).

What are some decent ways of accomplishing this? All I can think to do is to either

a) only allow a certain number of active connections at a time, or

b) attempt to use something called a MemoryFailPoint. After reading, I think this might be the better option, but how do I know how much memory a call to BeginRead will need to do its thing safely?

答: You should be using the thread pool to handle these operations, rather than creating whole new threads for every operation you need to perform.  Not only will using a thread pool that can re-use threads greatly remove effort spent creating and tearing down threads (which isn't cheap) but the thread pool will work to ensure that threads are only created when it will be beneficial to do so, and will simply let requests to have work done queue up when adding more threads wouldn't be beneficial.</p>


问:
Android: Deviceready has not fired after 5 seconds
After update Cordova to v6.4.0 and Android platform to 6.0.0, my app don't work any more. I'm getting this:

```<code>deviceready has not fired after 5 seconds. cordova.js:1223
Channel not fired: onCordovaInfoReady cordova.js:1216
Channel not fired: onCordovaConnectionReady cordova.js:1216
</code>```

I tried to remove all plugins and add it one by one. I found that is a problem with cordova-plugin-device and cordova-plugin-network-information. All my plugins are up to date

答:
I recently encountered this same issue on iOS. Eventually what worked for me was a simple remove and add of the ios platform:

```<code>cordova platform remove ios
cordova platform add ios
</code>```

It had been quite a while since I had completely re-built the ios platform and, just like you, I had made other major changes during that time (Cordova upgrade, XCode upgrade, etc). My theory is that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements. Doing a platform remove and platform add will clear out the build files and update config.xml.

I doubt this applies to the OP, but for others who've encountered this same issue, please ensure that you've included cordova.js in your index.html file. If you've not done so, add this line:

```<code><script src="cordova.js"></script>
</code>```

It's a very common omission when just getting started with Cordova.

Body:
After update Cordova to v6.4.0 and Android platform to 6.0.0, my app don't work any more. I'm getting this:

deviceready has not fired after 5 seconds. cordova.js:1223
Channel not fired: onCordovaInfoReady cordova.js:1216
Channel not fired: onCordovaConnectionReady cordova.js:1216

I tried to remove all plugins and add it one by one. I found that is a problem with cordova-plugin-device and cordova-plugin-network-information. All my plugins are up to date

Body:
I recently encountered this same issue on iOS. Eventually what worked for me was a simple remove and add of the ios platform:

cordova platform remove ios
cordova platform add ios

It had been quite a while since I had completely re-built the ios platform and, just like you, I had made other major changes during that time (Cordova upgrade, XCode upgrade, etc). My theory is that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements. Doing a platform remove and platform add will clear out the build files and update config.xml.

I doubt this applies to the OP, but for others who've encountered this same issue, please ensure that you've included cordova.js in your index.html file. If you've not done so, add this line:

<script src="cordova.js"></script>

It's a very common omission when just getting started with Cordova.


问:
Input data from multiple sources Azure streaming job
I need to send data from two devices to my Azure IOT hub.
Both of the devices transmit data with different JSON format. The common column between them is TimeStamp.

Now i need to consume and combine these two inputs and output my data into Power BI.
Can anybody suggest any approach or any link to refer to?

Prateek Raina

答:
To implement such a scenario you might want to use Azure Stream Analytics to reconcile the 2 different data types. The query language for ASA is SQL like and is pretty straight forward, it shouldn't be too hard to do this considering your data sources are both json.
Note that you can easily setup PowerBI as the output for Stream Analytics as well.</p>


答:
Add a class to the third DIV and give that display: inline-block;:

@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css' );

.d-inline-block {

  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}
.x {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="formClass ">
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="nameInput">
    <div class="form-control-placeholder"> Name </div>
  </div>
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>

  <div class="form-group message x">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>
</form></code>```

https://jsfiddle.net/tyuxpzk9/1/

Title: Bootstrap form not in the center of the div

Body:
Add a class to the third DIV and give that display: inline-block;:

@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css' );

.d-inline-block {

  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}
.x {
  display: inline-block;
}

<form class="formClass ">
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="nameInput">
    <div class="form-control-placeholder"> Name </div>
  </div>
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>

  <div class="form-group message x">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>
</form>

https://jsfiddle.net/tyuxpzk9/1/


问:
JSON for Modern C++ thread safe?
I am using a library named "JSON for Modern C++" (https://github.com/nlohmann/json) which is pretty slick, letting me use JSON configuration files by a C++ program that are shared with a Javascript server side application.  This library essentially creates another datatype that is accessed and manipulated in way that is very close to the same as a Javascript JSON objects.

My question is, do I need to be concerned about thread safety on JSON variable accesses and manipulations or can I trust the library is thread safe.  I've looked in the documentation and I don't see it say it is thread safe but I also don't see anywhere that says it isn't thread safe.

Is anyone else using this library in a multithreaded environment?  Did you need to protect it yourself or did the library protect itself.  Maybe I'm really lucky and the repository author nlohmann will answer directly!

Any help is greatly appreciated!

答:
nlohmann library is NOT thread safe. Take a look at the header file. It's a single one. There's no mutexes, locks or atomics or anything related to threads.

https://github.com/nlohmann/json/blob/develop/src/json.hpp

You are responsible for protecting against concurrency of multiple threads accessing this data.

Title: JSON for Modern C++ thread safe?