问:
Get line break in UILabel due to Autolayout
I want to get the text with newline characters as the UILabel is displayed using autolayout on the phone's screen. Thanks.

For example : If I assign

```<code>label.text = "dhasghdsgah dgahjdg ahjgd hkagkhdhk ajsh djkah"
</code>```

When this is displayed on screen it appears as follows depending on screen width:

```<code>dhasghdsgah dgahjdg ahjgd

 hkagkhdhk ajsh

  djkah
</code>```

I want to know where the '\n' has been inserted by autolayout.

Kindly correct me if I missed something.

Please find the screenshot :
There is no space in the label.

答:
Here is the code work around for detecting line breaks inside UILabel

```<code>- (int)getLengthForString:(NSString *)str fromFrame:(CGRect)frame withFont:(UIFont *)font
{
    int length = 1;
    int lastSpace = 1;
    NSString *cutText = [str substringToIndex:length];
    CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
    while (textSize.height <= frame.size.height)
    {
        NSRange range = NSMakeRange (length, 1);
        if ([[str substringWithRange:range] isEqualToString:@" "])
        {
            lastSpace = length;
        }
        length++;
        cutText = [str substringToIndex:length];
        textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
    }
    return lastSpace;
}

-(NSString*) getLinebreaksWithString:(NSString*)labelText forWidth:(CGFloat)lblWidth forPoint:(CGPoint)point
{
    //Create Label
    UILabel *label = [[UILabel alloc] init];
    label.text = labelText;
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;

    //Set frame according to string
    CGSize size = [label.text sizeWithFont:label.font
                         constrainedToSize:CGSizeMake(lblWidth, MAXFLOAT)
                             lineBreakMode:UILineBreakModeWordWrap];
    [label setFrame:CGRectMake(point.x , point.y , size.width , size.height)];

    //Add Label in current view
    [self.view addSubview:label];

    //Count the total number of lines for the Label which has NSLineBreakByWordWrapping line break mode
    int numLines = (int)(label.frame.size.height/label.font.leading);

    //Getting and dumping lines from text set on the Label
    NSMutableArray *allLines = [[NSMutableArray alloc] init];

    BOOL shouldLoop = YES;
    while (shouldLoop)
    {
        //Getting length of the string from rect with font
        int length = [self getLengthForString:labelText fromFrame:CGRectMake(point.x, point.y, size.width, size.height/numLines) withFont:label.font] + 1;

        [allLines addObject:[labelText substringToIndex:length]];

        labelText = [labelText substringFromIndex:length];
        if(labelText.length<length)
            shouldLoop = NO;
    }

    [allLines addObject:labelText];
    //NSLog(@"\n\n%@\n",allLines);

    return [allLines componentsJoinedByString:@"\n"];
}
</code>```

How to use :

```<code>NSString *labelText = @"We are what our thoughts have made us; so take care about what you think. Words are secondary. Thoughts live; they travel far.";

NSString *stringWithLineBreakChar = [self getLinebreaksWithString:labelText forWidth:200 forPoint:CGPointMake(15, 15)];
NSLog(@"\n\n%@",stringWithLineBreakChar);
</code>```

You just need to set parameters required by getLinebreaksWithString and you will get a string with each "\n" break included.
Use your label width and starting point you designed in storyboard.

Reference : https://stackoverflow.com/a/15243686/6904341

Body:
I want to get the text with newline characters as the UILabel is displayed using autolayout on the phone's screen. Thanks.

For example : If I assign

label.text = "dhasghdsgah dgahjdg ahjgd hkagkhdhk ajsh djkah"

When this is displayed on screen it appears as follows depending on screen width:

dhasghdsgah dgahjdg ahjgd

 hkagkhdhk ajsh

  djkah

I want to know where the '\n' has been inserted by autolayout.

Kindly correct me if I missed something.

Please find the screenshot :
There is no space in the label.

Body:
Here is the code work around for detecting line breaks inside UILabel

- (int)getLengthForString:(NSString *)str fromFrame:(CGRect)frame withFont:(UIFont *)font
{
    int length = 1;
    int lastSpace = 1;
    NSString *cutText = [str substringToIndex:length];
    CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
    while (textSize.height <= frame.size.height)
    {
        NSRange range = NSMakeRange (length, 1);
        if ([[str substringWithRange:range] isEqualToString:@" "])
        {
            lastSpace = length;
        }
        length++;
        cutText = [str substringToIndex:length];
        textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
    }
    return lastSpace;
}

-(NSString*) getLinebreaksWithString:(NSString*)labelText forWidth:(CGFloat)lblWidth forPoint:(CGPoint)point
{
    //Create Label
    UILabel *label = [[UILabel alloc] init];
    label.text = labelText;
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;

    //Set frame according to string
    CGSize size = [label.text sizeWithFont:label.font
                         constrainedToSize:CGSizeMake(lblWidth, MAXFLOAT)
                             lineBreakMode:UILineBreakModeWordWrap];
    [label setFrame:CGRectMake(point.x , point.y , size.width , size.height)];

    //Add Label in current view
    [self.view addSubview:label];

    //Count the total number of lines for the Label which has NSLineBreakByWordWrapping line break mode
    int numLines = (int)(label.frame.size.height/label.font.leading);

    //Getting and dumping lines from text set on the Label
    NSMutableArray *allLines = [[NSMutableArray alloc] init];

    BOOL shouldLoop = YES;
    while (shouldLoop)
    {
        //Getting length of the string from rect with font
        int length = [self getLengthForString:labelText fromFrame:CGRectMake(point.x, point.y, size.width, size.height/numLines) withFont:label.font] + 1;

        [allLines addObject:[labelText substringToIndex:length]];

        labelText = [labelText substringFromIndex:length];
        if(labelText.length<length)
            shouldLoop = NO;
    }

    [allLines addObject:labelText];
    //NSLog(@"\n\n%@\n",allLines);

    return [allLines componentsJoinedByString:@"\n"];
}

How to use :

NSString *labelText = @"We are what our thoughts have made us; so take care about what you think. Words are secondary. Thoughts live; they travel far.";

NSString *stringWithLineBreakChar = [self getLinebreaksWithString:labelText forWidth:200 forPoint:CGPointMake(15, 15)];
NSLog(@"\n\n%@",stringWithLineBreakChar);

You just need to set parameters required by getLinebreaksWithString and you will get a string with each "\n" break included.
Use your label width and starting point you designed in storyboard.

Reference : https://stackoverflow.com/a/15243686/6904341


来源: stackexchange

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

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

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

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

app.module.ts

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

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

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

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

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

app.component.ts

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

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

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

home.component.ts

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

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

export class HomeComponent implements OnInit {

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

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

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

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

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

    ngOnInit() {
        this.loadAllUsers();
    }

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

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

}
</code>```

Output:

Game    Platform    Release

Elements:

Console Window Screenshot

答:
Use ngOnInit() lifecycle callback to initialized the fields.

Try below code:

```<code>export class HomeComponent implements OnInit {

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

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

    ngOnInit() {
      this.loadAllUsers();

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

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

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

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

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

}
</code>```

ContentLicense: CC BY-SA 3.0

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

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

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

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

app.module.ts

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

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

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

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

export class AppModule { }

app.component.ts

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

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

export class AppComponent { }

home.component.ts

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

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

                        #
                        Game
                        Platform
                        Release

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

`
})

export class HomeComponent implements OnInit {

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

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

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

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

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

    ngOnInit() {
        this.loadAllUsers();
    }

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

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

}

Output:

Game    Platform    Release

Elements:

Console Window Screenshot

Body:
Use ngOnInit() lifecycle callback to initialized the fields.

Try below code:

export class HomeComponent implements OnInit {

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

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

    ngOnInit() {
      this.loadAllUsers();

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

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

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

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

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

}


问:
Center a textview vertical to a EditText
What I'm trying to do is have a TextView, and to the right of it an editText that takes up the rest of the space.  The textView should be  centered vertically along the editText.  Now I can do this using an linearlayout, however I would prefer to do it in a relativelayout.  </p>

```<code><RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:padding="10dp">
     <TextView
          android:id="@+id/loginText"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Login:"
          android:paddingRight="20dp" />

<EditText
          android:id="@+id/login"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_toRightOf="@id/loginText" />

</RelativeLayout>
</code>```

答:
add android:layout_gravity="center_vertical" to your Textview

this would place the textview centered vertically in the parent

ContentLicense: CC BY-SA 2.5

Body:
What I'm trying to do is have a TextView, and to the right of it an editText that takes up the rest of the space.  The textView should be  centered vertically along the editText.  Now I can do this using an linearlayout, however I would prefer to do it in a relativelayout.

<RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:padding="10dp">
     <TextView
          android:id="@+id/loginText"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Login:"
          android:paddingRight="20dp" />

<EditText
          android:id="@+id/login"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_toRightOf="@id/loginText" />

</RelativeLayout>


问:
App bar like Google inbox web app
I am building a react web application. I am using material ui for it. I am looking to have an appbar like google inbox has (screenshot attached below). Currently I have Appbar imported from material ui module, but it just contains title , navigation icon. I want to have a search bar, profile photo etc in my app bar, just like google inbox. How can I customize it to get a design like that. Do I have to tweak with material ui's appbar (if yes then how exactly) or do I have to do something else?

答:
```<code>const rightButtons = (
<div>
 <FlatButton key={1} label="Btn1"/>
 <FlatButton key={2} label="Btn2" />
<div>
)   //Style as per your requirement, Also implement search textfield component
// Drawer with list items
<Drawer/>
<AppBar
  title="Inbox"
  iconElementLeft={<SearchComponent/>}
  iconElementRight={rightButtons}
  onLeftIconButtonTouchTap={this.handleLeftDrawerToggle}
/>
</code>```

make use of iconElementLeft and iconElementRight.
Docs of AppBar

Title: App bar like Google inbox web app

Body:
const rightButtons = (
<div>
 <FlatButton key={1} label="Btn1"/>
 <FlatButton key={2} label="Btn2" />
<div>
)   //Style as per your requirement, Also implement search textfield component
// Drawer with list items
<Drawer/>
<AppBar
  title="Inbox"
  iconElementLeft={<SearchComponent/>}
  iconElementRight={rightButtons}
  onLeftIconButtonTouchTap={this.handleLeftDrawerToggle}
/>

make use of iconElementLeft and iconElementRight.
Docs of AppBar


问:
Alternative to mcrypt_encrypt?
As per the php 7.0 mcrypt_decrypt is deprecated.

I have following code.

```<code>$intSize= mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
$strSize = mcrypt_create_iv( $intSize, MCRYPT_RAND );
$strText = ( true == $boolTrimText ) ? trim( $strText ) : $strText;
$strResult = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, ( string ) $strKey, ( string ) $strText, MCRYPT_MODE_ECB, $strSize) );
</code>```

Now we are getting

```<code>mcrypt_encrypt(): Key of size 0 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported
</code>```

Any alternative to fix this warning?

答:
If you want to go encryption/decryption have a look upon  this blog post

https://paragonie.com/white-paper/2015-secure-php-data-encryption it will tell you how to do it in proper way.

Alternative http://php.net/manual/en/intro.openssl.php
This extension binds functions of » OpenSSL library for symmetric and asymmetric encryption and decryption.

Title: Alternative to mcrypt_encrypt?

Body:
As per the php 7.0 mcrypt_decrypt is deprecated.

I have following code.

$intSize= mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
$strSize = mcrypt_create_iv( $intSize, MCRYPT_RAND );
$strText = ( true == $boolTrimText ) ? trim( $strText ) : $strText;
$strResult = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, ( string ) $strKey, ( string ) $strText, MCRYPT_MODE_ECB, $strSize) );

Now we are getting

mcrypt_encrypt(): Key of size 0 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported

Any alternative to fix this warning?


问:
ANDROID:- not able to get the available wifi list using ScanResult
I'm trying to list available wifi network by ScanResult.

Can anyone tell me what's wrong in my code? I'm not getting the desired output.

Here's My code:

```<code>public class Activity_scanwifi extends AppCompatActivity {

    Switch aSwitch;
    TextView textView;
    WifiManager wifiManager;
    WifiInfo wifiInfo;
    String info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scanwifi);

        aSwitch=(Switch) findViewById(R.id.s);
        textView=(TextView) findViewById(R.id.textView);
        wifiManager=(WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // switch on
                if(isChecked && ! wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(true);
                    wifiInfo=wifiManager.getConnectionInfo();
                }
                // switch off
                if (!isChecked && wifiManager.isWifiEnabled())
                {
                  wifiManager.setWifiEnabled(false);
                }
            }
        });
        broadcast b=new broadcast();
        registerReceiver(b,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    public class broadcast extends BroadcastReceiver{
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceive(Context context, Intent intent) {
            // onReceive method updates any change in the available wifi
            StringBuffer stringBuffer=new StringBuffer();
           /// List<WifiConfiguration> list=wifiManager.getConfiguredNetworks();
            List<ScanResult> list=wifiManager.getScanResults();
            //for(WifiConfiguration wifiConfiguration : list)
            for(ScanResult scanResult : list)
            {
                stringBuffer.append(scanResult);
            }

            textView.setText(stringBuffer);

        }
    }
}
</code>```

答:
Try this code

WifiList.java

```<code>import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WifiList extends Activity {

            WifiManager mWifiManager;
            ArrayList<String> mWifiList;

            @BindView(R.id.lst_wifilist)
            ListView lst_wifilist;

            @BindView(R.id.ll_scan)
            LinearLayout ll_scan;

            @Override
            protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_wifilist);
                ButterKnife.bind(this);
                mWifiList = new ArrayList<>();
                mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                mWifiList.clear();

                scanNetwork();
    }

    private void scanNetwork() {
            registerReceiver(mWifiScanReceiver,
                    new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            mWifiManager.startScan();
        }

        private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent intent) {
                if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                    List<ScanResult> mScanResults = mWifiManager.getScanResults();
                    // add your logic here
                    mWifiList.clear();
                    for (int i = 0; i < mScanResults.size(); i++) {
                        Log.e("Scanned Wifi Name :- ", mScanResults.get(i).SSID);
                        mWifiList.add(mScanResults.get(i).SSID);

                        WifiListAdapter adapter = new WifiListAdapter(WifiList.this, mWifiList);
                        lst_wifilist.setAdapter(adapter);
                    }
                }
            }
        };
    }
</code>```

AndroidMenifest.xml

```<code><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
</code>```

Body:
I'm trying to list available wifi network by ScanResult.

Can anyone tell me what's wrong in my code? I'm not getting the desired output.

Here's My code:

public class Activity_scanwifi extends AppCompatActivity {

    Switch aSwitch;
    TextView textView;
    WifiManager wifiManager;
    WifiInfo wifiInfo;
    String info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scanwifi);

        aSwitch=(Switch) findViewById(R.id.s);
        textView=(TextView) findViewById(R.id.textView);
        wifiManager=(WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // switch on
                if(isChecked && ! wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(true);
                    wifiInfo=wifiManager.getConnectionInfo();
                }
                // switch off
                if (!isChecked && wifiManager.isWifiEnabled())
                {
                  wifiManager.setWifiEnabled(false);
                }
            }
        });
        broadcast b=new broadcast();
        registerReceiver(b,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    public class broadcast extends BroadcastReceiver{
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceive(Context context, Intent intent) {
            // onReceive method updates any change in the available wifi
            StringBuffer stringBuffer=new StringBuffer();
           /// List<WifiConfiguration> list=wifiManager.getConfiguredNetworks();
            List<ScanResult> list=wifiManager.getScanResults();
            //for(WifiConfiguration wifiConfiguration : list)
            for(ScanResult scanResult : list)
            {
                stringBuffer.append(scanResult);
            }

            textView.setText(stringBuffer);

        }
    }
}

Body:
Try this code

WifiList.java

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WifiList extends Activity {

            WifiManager mWifiManager;
            ArrayList<String> mWifiList;

            @BindView(R.id.lst_wifilist)
            ListView lst_wifilist;

            @BindView(R.id.ll_scan)
            LinearLayout ll_scan;

            @Override
            protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_wifilist);
                ButterKnife.bind(this);
                mWifiList = new ArrayList<>();
                mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                mWifiList.clear();

                scanNetwork();
    }

    private void scanNetwork() {
            registerReceiver(mWifiScanReceiver,
                    new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            mWifiManager.startScan();
        }

        private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent intent) {
                if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                    List<ScanResult> mScanResults = mWifiManager.getScanResults();
                    // add your logic here
                    mWifiList.clear();
                    for (int i = 0; i < mScanResults.size(); i++) {
                        Log.e("Scanned Wifi Name :- ", mScanResults.get(i).SSID);
                        mWifiList.add(mScanResults.get(i).SSID);

                        WifiListAdapter adapter = new WifiListAdapter(WifiList.this, mWifiList);
                        lst_wifilist.setAdapter(adapter);
                    }
                }
            }
        };
    }

AndroidMenifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>


问:
How to find the role after logging in to bigquery?
I already have access to Google analytics provided by my client and the bigquery has been configured to the project. But i want to know if i can create jobs. How do i find the role assigned to my id ?</p>

答:
i want to know if i can create jobs

Below is simple way to get this:
Just open Web UI and try to switch to project of your interest

a.  If you do have it in the list of available projects – just select it and then run (just in case) some simple query (SELECT 1)

If it is run successfully - you can create jobs in this project (because any query is in reality a job)

b.  If it is not in the initial list – select “Display Project” and enter project of your interest and also check “Make this my current project” box. If result is successful – most likely you again lucky and can create jobs in this project (but still – run some  simple query to be 110% sure

How do i find the role assigned to my id

This would be more involved – you will need to use respective IAM (Google Identity and Access Management) APIs

For example you can use testIamPermissions() API that allows you to test Cloud IAM permissions on a user for a resource. It takes the resource URL and a set of permissions as input parameters, and returns the set of permissions that the caller is allowed.

The permission you should look for is bigquery.jobs.create, but yo can pass to this API list of any permissions you want to check if you have


问:
Git LFS refused to track my large files properly, until I did the following

Problem

I had troubles trying to use git LFS, despite the many suggestions here on SO, on Git and GitHub's documentation, and on some Gists I'd run across.

My problem was as follows:

After performing the necessary steps:

```<code>git lfs install
git lfs track "<file of interest>"
git commit
</code>```

I would still not have any files being tracked.  If I performed

```<code>git lfs ls-files
</code>```

it would be blank.  If I went ahead & performed the push, the transaction would fail, saying that the files are too large.  (As expected, but I was desperate.)

答:
To track all files and sub directories of my_folder via LFS, you can do:

```<code>git lfs track "my_folder/**"
</code>```

It worked for me.

Doing the following is not working as of now to track whole my_folder directory:

```<code>git lfs track "my_folder/"
</code>```

is not working

Body:
Problem

I had troubles trying to use git LFS, despite the many suggestions here on SO, on Git and GitHub's documentation, and on some Gists I'd run across.

My problem was as follows:

After performing the necessary steps:

git lfs install
git lfs track "<file of interest>"
git commit

I would still not have any files being tracked.  If I performed

git lfs ls-files

it would be blank.  If I went ahead & performed the push, the transaction would fail, saying that the files are too large.  (As expected, but I was desperate.)

Body:
To track all files and sub directories of my_folder via LFS, you can do:

git lfs track "my_folder/**"

It worked for me.

Doing the following is not working as of now to track whole my_folder directory:

git lfs track "my_folder/"

is not working


问:
how to show image from url in php codeigniter
```<code> In controller:
public function submit_image() {
    $post = $this->input->post ();
    $this->common->submit_image ( $_FILES, $post );
    $this->session->set_flashdata ( 'success', "alert came" );
    redirect ( BASE_URL . 'admin/media_mgmt/' );
}

In model:
function submit_image($file, $data) {
    if ($fname = is_valid_val ( $data, 'name', FALSE )) {
        $this->db->set ( 'name', $this->db->escape_str ( htmlspecialchars ( $fname ) ) );
    }
    if ($fname = is_valid_val ( $data, 'tag', FALSE )) {
        $this->db->set ( 'tag', $this->db->escape_str ( htmlspecialchars ( $fname ) ) );
    }
    $name = upload_media_image ( $file );

    if ($name) {
        $data1 ['media_img'] =  BASE_PATH . MEDIA_PHOTO . '/' . $name;
        $this->db->set ( 'image', $this->db->escape_str ( htmlspecialchars ( $data1 ['media_img'] ) ) );
    }

    if ($id = is_valid_val ( $data, 'id', FALSE )) {
        $this->db->where ( 'id', $this->db->escape_str ( htmlspecialchars ( $id ) ) );
        $this->db->update ( TBL_MEDIA_PHOTO );
        if ($this->db->affected_rows () > 0) {
            return 1;
        } else {
            return FALSE;
        }
    } else {
        $this->db->insert ( TBL_MEDIA_PHOTO );
        if ($id = $this->db->insert_id ()) {
            return 1;
        }
    }
}

In php:
var image_list = $('#demo-foo-filtering').DataTable( {

     "processing": true,
     "serverSide": true,
     "ajax": {
         "url": "<?php echo BASE_URL;?>admin/ajax_image_list",
         "type": "POST"
     },
     "columns": [
         { "data": "id" },
         { "data": "name" },
         { "data": "tag" },
         { "data": "image" },

     ],

 } );
 $('#image_form').parsley().on('form:success', function() {
     var formdata = $('#image_form').serialize();
            $.ajax({
                url:"<?php echo BASE_URL.'admin/submit_image';?>",
                type: 'POST',
                data: formdata,
                success: function(res) {
                        if(res==1){
                            Custombox.close();
                            $('#success_edit').css("display",'block');
                            $('#success_edit').fadeIn().delay(3000).fadeOut();
                        }else{
                            //$('#error_edit').css("display",'block');

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

This is my controller model and php code.I want to display only image in admin panel.now the image is coming as "http://localhost/edudux_web/manage/media_photo//4.jpg" when getting from database. instead of url i want to show actual image on panel

答:
You have to pass image url in ajax response as well as controller :

In controller:

```<code>redirect ( BASE_URL . 'admin/media_mgmt/' );
</code>```

Change it to return :

```<code> public function submit_image() {
    $post = $this->input->post ();
    $name = $this->common->submit_image ( $_FILES, $post );
    $this->session->set_flashdata ( 'success', "alert came" );
    return BASE_URL . 'admin/media_mgmt/'.$name;
}
</code>```

In php:

```<code>if(res){
   Custombox.close();
   $('#success_edit').html('<img src="' + res + '" />'); }
   $('#success_edit').css("display",'block');
   $('#success_edit').fadeIn().delay(3000).fadeOut();
  }else{
     //$('#error_edit').css("display",'block');
  }
</code>```

in model:

In model:

```<code>function submit_image($file, $data) {
    if ($fname = is_valid_val ( $data, 'name', FALSE )) {
        $this->db->set ( 'name', $this->db->escape_str ( htmlspecialchars ( $fname ) ) );
    }
    if ($fname = is_valid_val ( $data, 'tag', FALSE )) {
        $this->db->set ( 'tag', $this->db->escape_str ( htmlspecialchars ( $fname ) ) );
    }
    $name = upload_media_image ( $file );

    if ($name) {
        $data1 ['media_img'] =  BASE_PATH . MEDIA_PHOTO . '/' . $name;
        $this->db->set ( 'image', $this->db->escape_str ( htmlspecialchars ( $data1 ['media_img'] ) ) );
    }

    if ($id = is_valid_val ( $data, 'id', FALSE )) {
        $this->db->where ( 'id', $this->db->escape_str ( htmlspecialchars ( $id ) ) );
        $this->db->update ( TBL_MEDIA_PHOTO );
        if ($this->db->affected_rows () > 0) {
            return $name;
        } else {
            return FALSE;
        }
    } else {
        $this->db->insert ( TBL_MEDIA_PHOTO );
        if ($id = $this->db->insert_id ()) {
            return $name;
        }
    }
}
</code>```

Body:
 In controller:
public function submit_image() {
    $post = $this->input->post ();
    $this->common->submit_image ( $_FILES, $post );
    $this->session->set_flashdata ( 'success', "alert came" );
    redirect ( BASE_URL . 'admin/media_mgmt/' );
}

In model:
function submit_image($file, $data) {
    if ($fname = is_valid_val ( $data, 'name', FALSE )) {
        $this->db->set ( 'name', $this->db->escape_str ( htmlspecialchars ( $fname ) ) );
    }
    if ($fname = is_valid_val ( $data, 'tag', FALSE )) {
        $this->db->set ( 'tag', $this->db->escape_str ( htmlspecialchars ( $fname ) ) );
    }
    $name = upload_media_image ( $file );

    if ($name) {
        $data1 ['media_img'] =  BASE_PATH . MEDIA_PHOTO . '/' . $name;
        $this->db->set ( 'image', $this->db->escape_str ( htmlspecialchars ( $data1 ['media_img'] ) ) );
    }

    if ($id = is_valid_val ( $data, 'id', FALSE )) {
        $this->db->where ( 'id', $this->db->escape_str ( htmlspecialchars ( $id ) ) );
        $this->db->update ( TBL_MEDIA_PHOTO );
        if ($this->db->affected_rows () > 0) {
            return 1;
        } else {
            return FALSE;
        }
    } else {
        $this->db->insert ( TBL_MEDIA_PHOTO );
        if ($id = $this->db->insert_id ()) {
            return 1;
        }
    }
}

In php:
var image_list = $('#demo-foo-filtering').DataTable( {

     "processing": true,
     "serverSide": true,
     "ajax": {
         "url": "<?php echo BASE_URL;?>admin/ajax_image_list",
         "type": "POST"
     },
     "columns": [
         { "data": "id" },
         { "data": "name" },
         { "data": "tag" },
         { "data": "image" },

     ],

 } );
 $('#image_form').parsley().on('form:success', function() {
     var formdata = $('#image_form').serialize();
            $.ajax({
                url:"<?php echo BASE_URL.'admin/submit_image';?>",
                type: 'POST',
                data: formdata,
                success: function(res) {
                        if(res==1){
                            Custombox.close();
                            $('#success_edit').css("display",'block');
                            $('#success_edit').fadeIn().delay(3000).fadeOut();
                        }else{
                            //$('#error_edit').css("display",'block');

                        }
                }
            })
     });

This is my controller model and php code.I want to display only image in admin panel.now the image is coming as "http://localhost/edudux_web/manage/media_photo//4.jpg" when getting from database. instead of url i want to show actual image on panel

Body:
You have to pass image url in ajax response as well as controller :

In controller:

redirect ( BASE_URL . 'admin/media_mgmt/' );

Change it to return :

 public function submit_image() {
    $post = $this->input->post ();
    $name = $this->common->submit_image ( $_FILES, $post );
    $this->session->set_flashdata ( 'success', "alert came" );
    return BASE_URL . 'admin/media_mgmt/'.$name;
}

In php:

if(res){
   Custombox.close();
   $('#success_edit').html('<img src="' + res + '" />'); }
   $('#success_edit').css("display",'block');
   $('#success_edit').fadeIn().delay(3000).fadeOut();
  }else{
     //$('#error_edit').css("display",'block');
  }

in model:

In model:

function submit_image($file, $data) {
    if ($fname = is_valid_val ( $data, 'name', FALSE )) {
        $this->db->set ( 'name', $this->db->escape_str ( htmlspecialchars ( $fname ) ) );
    }
    if ($fname = is_valid_val ( $data, 'tag', FALSE )) {
        $this->db->set ( 'tag', $this->db->escape_str ( htmlspecialchars ( $fname ) ) );
    }
    $name = upload_media_image ( $file );

    if ($name) {
        $data1 ['media_img'] =  BASE_PATH . MEDIA_PHOTO . '/' . $name;
        $this->db->set ( 'image', $this->db->escape_str ( htmlspecialchars ( $data1 ['media_img'] ) ) );
    }

    if ($id = is_valid_val ( $data, 'id', FALSE )) {
        $this->db->where ( 'id', $this->db->escape_str ( htmlspecialchars ( $id ) ) );
        $this->db->update ( TBL_MEDIA_PHOTO );
        if ($this->db->affected_rows () > 0) {
            return $name;
        } else {
            return FALSE;
        }
    } else {
        $this->db->insert ( TBL_MEDIA_PHOTO );
        if ($id = $this->db->insert_id ()) {
            return $name;
        }
    }
}


问:
How to store a list in a db column
I would like to store an object FOO in a database.
Lets say FOO contains three integers and a list of "Fruits".

The list can have any length, the only thing I know is that the all the fruits allowed are stored in another table.

Can I store the fruit list in a column?

答:
Its technically possible but would be very poor design, imo.

You could do it by building the string and storing it in a nvarchar(max) field (if using sql server or its equivalent).

OwnerDisplayName: Stumproot

Title: How to store a list in a db column

OwnerDisplayName: E.J. Brennan


问:
Delegating touch events
lets assume i have a LinearLayout , horizontal that contains a TextView and afterward a Spinner or another clicable TextView or an EditText.

I want that a click on any part of the line (if the layout has padding then the layout area as well!) will deleage the onTouchEvent to the Right part of the layout (EditText, TextView or Spinner) as if they were clicked themselves.

Doing it myself will require me either create my own versions of those widgets (too much work for little effect :-( ) or putting listeners on many items for the touch events and delegate them. I'm pretty sure Android has some methods or properties to do that, just didn't see any so far.

Can anyone help ?

答:
I had to do something similar to this a while back, and ended up writing my own delegate and assigning the onclicklisteners for all of the components in my layout to that delegate. It's cumbersome, but not too painful to implement, and it turned out well.

Point being, I didn't see anything in the API to handle that sort of thing. The only other thing I might offer is that it is certainly possible to assign an onclicklistener to a component and simply send the event to another component's onclicklistener like so:

```<code>thislinearlayout.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        getOtherComponent().performClick();
    }
});
</code>```

You can do the same thing with touch listeners.

Title: Delegating touch events

Body:
I had to do something similar to this a while back, and ended up writing my own delegate and assigning the onclicklisteners for all of the components in my layout to that delegate. It's cumbersome, but not too painful to implement, and it turned out well.

Point being, I didn't see anything in the API to handle that sort of thing. The only other thing I might offer is that it is certainly possible to assign an onclicklistener to a component and simply send the event to another component's onclicklistener like so:

thislinearlayout.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        getOtherComponent().performClick();
    }
});

You can do the same thing with touch listeners.


问:
Facebook Android SDK get user's Gender, Email, Cover, Timezone
I am using Facebook Android SDK 4+ and being able to successfully log in but how do I get the user Gender, Email, Cover, Timezone. This was available in Javascript API.

```<code>loginButton.setReadPermissions("public_profile");
</code>```

For getting the firstname and lastname I'm using this two method as mentioned in Facebook Docs.

Firstname: profile.getFirstName()
Lastname: profile.getFirstName()

For getting the gender, email, cover, timezone.

I tried using

```<code>String get_gender = (String) profile.getProperty("gender");
String get_email = (String) profile.getProperty("email_address");
String get_cover = (String) profile.getProperty("cover");
String get_tz = (String) profile.getProperty("timezone");
</code>```

but its not working
(Error: Cannot resolve method getProperty(java.lang.String))

Need help to resolve this issue. Thanks in advance.

答:
try this Facebook Graph API:</p>

```<code>private void faceBookLigin() {

        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_photos", "email", "user_birthday", "user_friends", "user_location"));
        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        // App code
                        accessToken = loginResult.getAccessToken();

                                /* make the API call */
                        GraphRequest request = GraphRequest.newMeRequest(
                                accessToken,
                                new GraphRequest.GraphJSONObjectCallback() {
                                    @Override
                                    public void onCompleted(JSONObject object, GraphResponse response) {
                                        if (object == null) {
                                            cUtils.Toast("Please try again!", getApplicationContext());
                                        } else {
                                            try {
                                                String str_datestr = object.getString("birthday");
                                                String strd = str_datestr.replaceAll("\\\\/", "/");
                                                String str_date = strd.replaceAll("/", "-");
                                                DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy", Locale.getDefault());
                                                Date date = null;
                                                try {
                                                    date = formatter.parse(str_date);
                                                } catch (java.text.ParseException e) {
                                                    // TODO Auto-generated catch block
                                                    e.printStackTrace();
                                                }
                                                long output = 0;
                                                if (date != null) {
                                                    output = date.getTime() / 1000L;
                                                }
                                                String str = Long.toString(output);
                                                actualTime = Long.parseLong(str);
//                                                Log.v("actualTime = ", " " + actualTime);
//                                                Log.v("Email = ", " " + object);
                                                email = object.getString("email");
                                                facebook_id = object.getString("id");
                                                first_name = object.getString("first_name");
                                                last_name = object.getString("last_name");
                                                user_location = object.getJSONObject("location");
                                                gender = object.getString("gender");
                                                verified = object.getBoolean("verified");
                                                id = object.getString("id");

                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                });

                        Bundle parameters = new Bundle();
                        parameters.putString("fields", "id,first_name,last_name,email,gender,verified,age_range,hometown, birthday,location");
                        request.setParameters(parameters);
                        request.executeAsync();

                        if (accessToken != null)
                            LoginManager.getInstance().logOut();
                    }

                    @Override
                    public void onCancel() {
                        // App code
//                        Log.e(TAG, "facebook login canceled");
                        utils.cToast("facebook login canceled", getApplicationContext());
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        // App code
//                        Log.e(TAG, "facebook login failed error" + exception);
                        utils.cToast("facebook login failed", getApplicationContext());
                    }
                });
    }
</code>```

Body:
I am using Facebook Android SDK 4+ and being able to successfully log in but how do I get the user Gender, Email, Cover, Timezone. This was available in Javascript API.

loginButton.setReadPermissions("public_profile");

For getting the firstname and lastname I'm using this two method as mentioned in Facebook Docs.

Firstname: profile.getFirstName()
Lastname: profile.getFirstName()

For getting the gender, email, cover, timezone.

I tried using

String get_gender = (String) profile.getProperty("gender");
String get_email = (String) profile.getProperty("email_address");
String get_cover = (String) profile.getProperty("cover");
String get_tz = (String) profile.getProperty("timezone");

but its not working
(Error: Cannot resolve method getProperty(java.lang.String))

Need help to resolve this issue. Thanks in advance.

Body:
try this Facebook Graph API:

private void faceBookLigin() {

        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_photos", "email", "user_birthday", "user_friends", "user_location"));
        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        // App code
                        accessToken = loginResult.getAccessToken();

                                /* make the API call */
                        GraphRequest request = GraphRequest.newMeRequest(
                                accessToken,
                                new GraphRequest.GraphJSONObjectCallback() {
                                    @Override
                                    public void onCompleted(JSONObject object, GraphResponse response) {
                                        if (object == null) {
                                            cUtils.Toast("Please try again!", getApplicationContext());
                                        } else {
                                            try {
                                                String str_datestr = object.getString("birthday");
                                                String strd = str_datestr.replaceAll("\\\\/", "/");
                                                String str_date = strd.replaceAll("/", "-");
                                                DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy", Locale.getDefault());
                                                Date date = null;
                                                try {
                                                    date = formatter.parse(str_date);
                                                } catch (java.text.ParseException e) {
                                                    // TODO Auto-generated catch block
                                                    e.printStackTrace();
                                                }
                                                long output = 0;
                                                if (date != null) {
                                                    output = date.getTime() / 1000L;
                                                }
                                                String str = Long.toString(output);
                                                actualTime = Long.parseLong(str);
//                                                Log.v("actualTime = ", " " + actualTime);
//                                                Log.v("Email = ", " " + object);
                                                email = object.getString("email");
                                                facebook_id = object.getString("id");
                                                first_name = object.getString("first_name");
                                                last_name = object.getString("last_name");
                                                user_location = object.getJSONObject("location");
                                                gender = object.getString("gender");
                                                verified = object.getBoolean("verified");
                                                id = object.getString("id");

                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                });

                        Bundle parameters = new Bundle();
                        parameters.putString("fields", "id,first_name,last_name,email,gender,verified,age_range,hometown, birthday,location");
                        request.setParameters(parameters);
                        request.executeAsync();

                        if (accessToken != null)
                            LoginManager.getInstance().logOut();
                    }

                    @Override
                    public void onCancel() {
                        // App code
//                        Log.e(TAG, "facebook login canceled");
                        utils.cToast("facebook login canceled", getApplicationContext());
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        // App code
//                        Log.e(TAG, "facebook login failed error" + exception);
                        utils.cToast("facebook login failed", getApplicationContext());
                    }
                });
    }


问:
Webpack extract text plugin outputting .js and .css file for styles entry
For a prod build I want my webpack config to have two entry points, one for JS and one for SCSS, and I want these to be output to two separate files (one JS, one CSS).

However extract-text-webpack-plugin is creating two JS files and one CSS file; ie the entry point for SCSS is producing both the desired CSS file plus a JS file that I don't want. This unused JS file contains nothing other than the webpack boilerplate and // removed by extract-text-webpack-plugin. So it's doing its job fine, but still creating this unnecessary file. My webpack config is (showing the pertinent parts):

```<code>const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        app: './client/src/app.js',
        style: './client/src/app.scss'
    },
    output: {
        path: __dirname + '/server/assets/',
        publicPath: '/',
        filename: 'bundle.[chunkhash].js',
    },
    module: {
        loaders: [{
        test: /\.js/,
        exclude: /node_modules/,
        include: /src/,
        loader: 'babel-loader'
        },{
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', 'css', 'sass'),
        },{
        test: /.*\.(woff|woff2|eot|ttf)$/i,
        loader: "url-loader?limit=10000&mimetype=application/font-woff"
        },{
        test: /.*\.(png|svg|jpg)$/i,
        loaders: [
        'file?hash=sha512&digest=hex&name=[hash].[ext]',
        'image-webpack?{progressive:true, optimizationLevel: 7, interlaced: false, pngquant:{quality: "65-90", speed: 4}}'
        ]
        }]
    },
    plugins: [
        new ExtractTextPlugin('bundle.[chunkhash].css', {
        allChunks: true
        })
    ]
};
</code>```

So essentially the output is creating two .js files, one for each entry and then the extract plugin is creating the actual desired .css file. How can I prevent the output from creating that unnecessary file?

答:
I put together a webpack plugin to remove extra files based on their final output size - given these files tend to be very small, it seems to just be a case of checking how large they are and removing the small, useless ones.

Install using npm or yarn

```<code>npm install webpack-extraneous-file-cleanup-plugin --save-dev
yarn add webpack-extraneous-file-cleanup-plugin --dev
</code>```

In your webpack.config.js file:

```<code>const ExtraneousFileCleanupPlugin = require('webpack-extraneous-file-cleanup-plugin');

module.exports = {
  ...
  plugins: [
    new ExtraneousFileCleanupPlugin({
      extensions: ['.js']
    })
  ]
}
</code>```

You can see the full list of options on the Webpack Extraneous File Cleanup Plugin Github Page

Body:
For a prod build I want my webpack config to have two entry points, one for JS and one for SCSS, and I want these to be output to two separate files (one JS, one CSS).

However extract-text-webpack-plugin is creating two JS files and one CSS file; ie the entry point for SCSS is producing both the desired CSS file plus a JS file that I don't want. This unused JS file contains nothing other than the webpack boilerplate and // removed by extract-text-webpack-plugin. So it's doing its job fine, but still creating this unnecessary file. My webpack config is (showing the pertinent parts):

const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        app: './client/src/app.js',
        style: './client/src/app.scss'
    },
    output: {
        path: __dirname + '/server/assets/',
        publicPath: '/',
        filename: 'bundle.[chunkhash].js',
    },
    module: {
        loaders: [{
        test: /\.js/,
        exclude: /node_modules/,
        include: /src/,
        loader: 'babel-loader'
        },{
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', 'css', 'sass'),
        },{
        test: /.*\.(woff|woff2|eot|ttf)$/i,
        loader: "url-loader?limit=10000&mimetype=application/font-woff"
        },{
        test: /.*\.(png|svg|jpg)$/i,
        loaders: [
        'file?hash=sha512&digest=hex&name=[hash].[ext]',
        'image-webpack?{progressive:true, optimizationLevel: 7, interlaced: false, pngquant:{quality: "65-90", speed: 4}}'
        ]
        }]
    },
    plugins: [
        new ExtractTextPlugin('bundle.[chunkhash].css', {
        allChunks: true
        })
    ]
};

So essentially the output is creating two .js files, one for each entry and then the extract plugin is creating the actual desired .css file. How can I prevent the output from creating that unnecessary file?

Body:
I put together a webpack plugin to remove extra files based on their final output size - given these files tend to be very small, it seems to just be a case of checking how large they are and removing the small, useless ones.

Install using npm or yarn

npm install webpack-extraneous-file-cleanup-plugin --save-dev
yarn add webpack-extraneous-file-cleanup-plugin --dev

In your webpack.config.js file:

const ExtraneousFileCleanupPlugin = require('webpack-extraneous-file-cleanup-plugin');

module.exports = {
  ...
  plugins: [
    new ExtraneousFileCleanupPlugin({
      extensions: ['.js']
    })
  ]
}

You can see the full list of options on the Webpack Extraneous File Cleanup Plugin Github Page


问:
Have two GoogleService-Info.plist (or more) in one target (GCM)
I am integrating GCM in an app and we happen to have several build configurations for the same target and some of them use different Bundle Ids (we have different accounts, enterprise and appstore) so if we want to enable GCM push notifications in both we need two different GoogleService-Info.plist files (each one for the different BundleID). I cannot find a way to tell the GCM sdk to initialize from a different named file but the default one. Does anyone know if this is possible?

I can think of a two solutions, but I would rather not do them.
- Write to the plist file the bundle id once the app is started (or before)
- Create a different Target each one with a different plist file

Thanks a lot.

Regards,
Javier

答:
I had a similar problem: Use User-Defined build settings in custom .plist file

You can use a Build Phase Script to copy the proper .plist file to your location:

Create a new folder (for example: GoogleServiceInfoPlists).

Copy there all .plist files (for example: GoogleService-Info-Debug.plist, GoogleService-Info-Stage.plist and GoogleService-Info-Prod.plist).

Add new Run Script Phase (Xcode: Target->Build Phases->"+" button)

Use script below to copy (replace) .plist file for given environment to the main directory (it's src in my case):

```<code>cp "${SRCROOT}/src/Resources/GoogleServiceInfoPlists/GoogleService-Info-$CONFIGURATION.plist" "${SRCROOT}/src/GoogleService-Info.plist"
</code>```

Please note that src/GoogleService-Info.plist file must be added to the Xcode project (Build Phases->Copy Bundle Resources) while /src/Resources/GoogleServiceInfoPlists/GoogleService-Info-* files not necessarily.

Body:
I had a similar problem: Use User-Defined build settings in custom .plist file

You can use a Build Phase Script to copy the proper .plist file to your location:

Create a new folder (for example: GoogleServiceInfoPlists).

Copy there all .plist files (for example: GoogleService-Info-Debug.plist, GoogleService-Info-Stage.plist and GoogleService-Info-Prod.plist).

Add new Run Script Phase (Xcode: Target->Build Phases->"+" button)

Use script below to copy (replace) .plist file for given environment to the main directory (it's src in my case):

cp "${SRCROOT}/src/Resources/GoogleServiceInfoPlists/GoogleService-Info-$CONFIGURATION.plist" "${SRCROOT}/src/GoogleService-Info.plist"

Please note that src/GoogleService-Info.plist file must be added to the Xcode project (Build Phases->Copy Bundle Resources) while /src/Resources/GoogleServiceInfoPlists/GoogleService-Info-* files not necessarily.


问:
find the sum of all the numbers in the Fibonacci series that are smaller or equal to that number
The Fibonacci numbers are the numbers in the following integer sequence.

```<code>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 . . .
</code>```

Given a specific number in this series Fn, your program needs to find the sum of all the numbers in the Fibonacci series that are smaller or equal to that number.

Input Format
Your program will be provided a number in the Fibonacci series on STDIN.

Constraints

```<code>0<<Fn<100000
</code>```

Sample Input

```<code>8
</code>```

Sample Output

```<code>The output for above input (8) should be 0 + 1 + 1 + 2 + 3 + 5 + 8
20
</code>```

To solve above problem I write a code like

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

class MyTest{
    public static Integer solveProblem(int n) {
        if (n>=0 || n<100000) {
        int fibo[] = new int[n+1];
        fibo[0] = 0; fibo[1] = 1;
        int sum = fibo[0] + fibo[1];
        for (int i=2; i<=n; i++) {
            fibo[i] = fibo[i-1]+fibo[i-2];
            if(n >= fibo[i]) {
                sum += fibo[i];
            } else {
                break;
            }
        }
        return sum;
        } else {
            return 0;
        }
    }

    public static void main (String[] args) throws java.lang.Exception {
        Scanner in = new Scanner(System.in);
        int sum = MyTest.solveProblem(in.nextInt());
        System.out.println("This is the output:"+sum);
    }
}
</code>```

I run the program it works fine with the sample test case as mentioned but when I submit this program on online test quiz then it run with their test case and it will fail.

Is something wrong in my program or I didn't understand the question properly. Please help me to find out exact answer of this problem.

答:
Your code seems to fail for n=0 and n=1.

For n=1 you return 1 but should return 2 (since there are two elements whose value is 1, and you should be adding both of them to the sum).

For n=0 you are throwing an exception.

You could fix this by adding a special check for these cases:

```<code>public static Integer solveProblem(int n) {
    if (n==0)
        return 0;
    else if (n==1)
        return 2;
    else if (n>=0 || n<100000) {
        int fibo[] = new int[n+1];
        fibo[0] = 0; fibo[1] = 1;
        int sum = fibo[0] + fibo[1];
        for (int i=2; i<=n; i++) {
            fibo[i] = fibo[i-1]+fibo[i-2];
            if(n >= fibo[i]) {
                sum += fibo[i];
            } else {
                break;
            }
        }
        return sum;
    } else {
        return 0;
    }
}
</code>```

Body:
The Fibonacci numbers are the numbers in the following integer sequence.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 . . .

Given a specific number in this series Fn, your program needs to find the sum of all the numbers in the Fibonacci series that are smaller or equal to that number.

Input Format
Your program will be provided a number in the Fibonacci series on STDIN.

Constraints

0<<Fn<100000

Sample Input

8

Sample Output

The output for above input (8) should be 0 + 1 + 1 + 2 + 3 + 5 + 8
20

To solve above problem I write a code like

import java.util.*;
import java.lang.*;
import java.io.*;

class MyTest{
    public static Integer solveProblem(int n) {
        if (n>=0 || n<100000) {
        int fibo[] = new int[n+1];
        fibo[0] = 0; fibo[1] = 1;
        int sum = fibo[0] + fibo[1];
        for (int i=2; i<=n; i++) {
            fibo[i] = fibo[i-1]+fibo[i-2];
            if(n >= fibo[i]) {
                sum += fibo[i];
            } else {
                break;
            }
        }
        return sum;
        } else {
            return 0;
        }
    }

    public static void main (String[] args) throws java.lang.Exception {
        Scanner in = new Scanner(System.in);
        int sum = MyTest.solveProblem(in.nextInt());
        System.out.println("This is the output:"+sum);
    }
}

I run the program it works fine with the sample test case as mentioned but when I submit this program on online test quiz then it run with their test case and it will fail.

Is something wrong in my program or I didn't understand the question properly. Please help me to find out exact answer of this problem.

Body:
Your code seems to fail for n=0 and n=1.

For n=1 you return 1 but should return 2 (since there are two elements whose value is 1, and you should be adding both of them to the sum).

For n=0 you are throwing an exception.

You could fix this by adding a special check for these cases:

public static Integer solveProblem(int n) {
    if (n==0)
        return 0;
    else if (n==1)
        return 2;
    else if (n>=0 || n<100000) {
        int fibo[] = new int[n+1];
        fibo[0] = 0; fibo[1] = 1;
        int sum = fibo[0] + fibo[1];
        for (int i=2; i<=n; i++) {
            fibo[i] = fibo[i-1]+fibo[i-2];
            if(n >= fibo[i]) {
                sum += fibo[i];
            } else {
                break;
            }
        }
        return sum;
    } else {
        return 0;
    }
}


问:
File upload .NET Core 'IFormFile' does not contain a definition for 'SaveAsASync' and no extension method
I'm trying to upload a file using ASP.NET Core Web Api.
As many i found this code:

```<code>namespace ModelBindingWebSite.Controllers
{
  public class HomeController : Controller
  {
    private IHostingEnvironment _environment;

    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Index(ICollection<IFormFile> files)
    {
        var uploads = Path.Combine(_environment.WebRootPath, "uploads");
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                await file.SaveAsAsync(Path.Combine(uploads, fileName));
            }
        }
        return View();
    }
}
</code>```

I get the error IFormFile does not contain a definition for SaveAsASync and no extension method.
Any idea?

答:
You can simply build a handy extension for later use

```<code> using System.IO;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Http;

 public static class FileSaveExtension
 {
     public static async Task SaveAsAsync(this IFormFile formFile, string filePath)
     {
         using (var stream = new FileStream(filePath, FileMode.Create))
         {
             await formFile.CopyToAsync(stream);
         }
     }

     public static void SaveAs(this IFormFile formFile, string filePath)
     {
         using (var stream = new FileStream(filePath, FileMode.Create))
         {
             formFile.CopyTo(stream);
         }
     }

 }
</code>```

Implementation:

```<code>formFile.SaveAsAsync("Your-File-Path"); // [ Async call ]
formFile.SaveAs("Your-File-Path");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to upload a file using ASP.NET Core Web Api.
As many i found this code:

namespace ModelBindingWebSite.Controllers
{
  public class HomeController : Controller
  {
    private IHostingEnvironment _environment;

    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Index(ICollection<IFormFile> files)
    {
        var uploads = Path.Combine(_environment.WebRootPath, "uploads");
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                await file.SaveAsAsync(Path.Combine(uploads, fileName));
            }
        }
        return View();
    }
}

I get the error IFormFile does not contain a definition for SaveAsASync and no extension method.
Any idea?

Body:
You can simply build a handy extension for later use

 using System.IO;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Http;

 public static class FileSaveExtension
 {
     public static async Task SaveAsAsync(this IFormFile formFile, string filePath)
     {
         using (var stream = new FileStream(filePath, FileMode.Create))
         {
             await formFile.CopyToAsync(stream);
         }
     }

     public static void SaveAs(this IFormFile formFile, string filePath)
     {
         using (var stream = new FileStream(filePath, FileMode.Create))
         {
             formFile.CopyTo(stream);
         }
     }

 }

Implementation:

formFile.SaveAsAsync("Your-File-Path"); // [ Async call ]
formFile.SaveAs("Your-File-Path");