问:
load component dynamically in angular4
i am trying to load components dynamically using ng-dynamic-component of angular4.

I keep getting this error in the browser console.Can anybody explain me what am i doing wrong?

The dynamic components i am trying to implement is:

http://www.muller.tech/post/2017/08/04/angular4-dynamically-add-component/

ERROR IMAGE

systemjs.config.js

```<code>(function (global) {
System.config({
    paths: {
        // paths serve as alias
        'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
        // our app is within the app folder
        app: '/app',
 'ng-dynamic-component': 'npm:/ng-dynamic-component/dist/src/index.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
        app: {
           main: 'main.js',

            defaultExtension: 'js'
        },
        rxjs: {
            defaultExtension: 'js'
        }
        ,
        'ng-dynamic-component': { defaultExtension: 'js'},
        'ng2-bs3-modal':
        { main: '/bundles/ng2-bs3-modal.js', defaultExtension: 'js' }

    }

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

app.module.ts

```<code>        import { AppComponent } from './app.component';
    import { HttpModule } from '@angular/http';
    import { AppRoutingModule } from './app.routing';
    import { DynamicModule } from 'ng-dynamic-component';
    import { CommonModule } from '@angular/common';
    import { CSSCarouselComponent } from './Components/Typescript/Slider';
    import { CSSCarouselService } from './Components/Service/CarouselService';
    import { EditorComponent } from './Components/Typescript/Editor';
    import { DynamicComponent } from './Components/Typescript/ComponentDynamic';

    @NgModule({
        imports: [CommonModule, BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, AppRoutingModule, Ng2Bs3ModalModule, DynamicModule.withComponents([CSSCarouselComponent, EditorComponent])],
        declarations: [AppComponent, MWRHomeComponent, MWRHomeNavbarComponent, CSSCarouselComponent, EditorComponent, DynamicComponent],
        providers: [{ provide: APP_BASE_HREF, useValue: '/' }, CSSCarouselService],
        bootstrap: [AppComponent]
    })

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

tsconfig.json

```<code>{
    "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "sourceMap": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es5",
    "importHelpers": true

    },
    "exclude": [
    "node_modules/*"
    ]
    }
</code>```

Folder structure of node modules where ng-dynamic-component has been included :

```<code> 1. nodemodules

       --ng-dynamic-component

             -dist
                 ->bundles
                  ->src
                      ->>index.js

             -script
             -src
</code>```

app.component.ts

```<code>import { Component } from "@angular/core"
//declare var jquery: any;

 @Component({

 selector: 'user-app',
 templateUrl: '../../app/body.html'
 })

 export class AppComponent {
 title = 'Tour of Heroes';

 components = [
    { type: 'a' },
    { type: 'b' }
  ];
}
</code>```

body.html

```<code><h1>
{{title}}

</h1>

<body-content></body-content>
<editor></editor>

<div *ngFor='let component of components'>
<app-hopla [type]='component.type'></app-hopla>
</div>
</code>```

ComponentDynamic.ts

```<code>import { Component, OnChanges, Input } from '@angular/core';
import { CSSCarouselComponent } from './Slider';
import { EditorComponent } from './Editor';

@Component({
selector: 'app-hopla',
template: `
<ndc-dynamic [ndcDynamicComponent]='selectedComponent'></ndc-dynamic>
`
})
export class DynamicComponent implements OnChanges {
@Input() type: string;

selectedComponent: any;

ngOnChanges() {

    if (this.type) {
        if (this.type === 'a') this.selectedComponent = CSSCarouselComponent;
        if (this.type === 'b') this.selectedComponent = EditorComponent ;
    }
   }
}
</code>```

答:
You have given extra back slash in the SystemConfig.js file for ng-dynamic-component

```<code>map: {
        // our app is within the app folder
        app: '/app',
       'ng-dynamic-component': 'npm:/ng-dynamic-component/dist/src/index.js'
    },
</code>```

as you defined in the path

```<code>'npm:': 'node_modules/'
</code>```

Please remove this extra backslash.

Title: load component dynamically in angular4

Body:
i am trying to load components dynamically using ng-dynamic-component of angular4.

I keep getting this error in the browser console.Can anybody explain me what am i doing wrong?

The dynamic components i am trying to implement is:

http://www.muller.tech/post/2017/08/04/angular4-dynamically-add-component/

ERROR IMAGE

systemjs.config.js

(function (global) {
System.config({
    paths: {
        // paths serve as alias
        'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
        // our app is within the app folder
        app: '/app',
 'ng-dynamic-component': 'npm:/ng-dynamic-component/dist/src/index.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
        app: {
           main: 'main.js',

            defaultExtension: 'js'
        },
        rxjs: {
            defaultExtension: 'js'
        }
        ,
        'ng-dynamic-component': { defaultExtension: 'js'},
        'ng2-bs3-modal':
        { main: '/bundles/ng2-bs3-modal.js', defaultExtension: 'js' }

    }

});
})(this);

app.module.ts

        import { AppComponent } from './app.component';
    import { HttpModule } from '@angular/http';
    import { AppRoutingModule } from './app.routing';
    import { DynamicModule } from 'ng-dynamic-component';
    import { CommonModule } from '@angular/common';
    import { CSSCarouselComponent } from './Components/Typescript/Slider';
    import { CSSCarouselService } from './Components/Service/CarouselService';
    import { EditorComponent } from './Components/Typescript/Editor';
    import { DynamicComponent } from './Components/Typescript/ComponentDynamic';

    @NgModule({
        imports: [CommonModule, BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, AppRoutingModule, Ng2Bs3ModalModule, DynamicModule.withComponents([CSSCarouselComponent, EditorComponent])],
        declarations: [AppComponent, MWRHomeComponent, MWRHomeNavbarComponent, CSSCarouselComponent, EditorComponent, DynamicComponent],
        providers: [{ provide: APP_BASE_HREF, useValue: '/' }, CSSCarouselService],
        bootstrap: [AppComponent]
    })

    export class AppModule { }

tsconfig.json

{
    "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "sourceMap": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es5",
    "importHelpers": true

    },
    "exclude": [
    "node_modules/*"
    ]
    }

Folder structure of node modules where ng-dynamic-component has been included :

 1. nodemodules

       --ng-dynamic-component

             -dist
                 ->bundles
                  ->src
                      ->>index.js

             -script
             -src

app.component.ts

import { Component } from "@angular/core"
//declare var jquery: any;

 @Component({

 selector: 'user-app',
 templateUrl: '../../app/body.html'
 })

 export class AppComponent {
 title = 'Tour of Heroes';

 components = [
    { type: 'a' },
    { type: 'b' }
  ];
}

body.html

{{title}}

<editor></editor>

<app-hopla [type]='component.type'></app-hopla>

ComponentDynamic.ts

import { Component, OnChanges, Input } from '@angular/core';
import { CSSCarouselComponent } from './Slider';
import { EditorComponent } from './Editor';

@Component({
selector: 'app-hopla',
template: `
<ndc-dynamic [ndcDynamicComponent]='selectedComponent'></ndc-dynamic>
`
})
export class DynamicComponent implements OnChanges {
@Input() type: string;

selectedComponent: any;

ngOnChanges() {

    if (this.type) {
        if (this.type === 'a') this.selectedComponent = CSSCarouselComponent;
        if (this.type === 'b') this.selectedComponent = EditorComponent ;
    }
   }
}

Body:
You have given extra back slash in the SystemConfig.js file for ng-dynamic-component

map: {
        // our app is within the app folder
        app: '/app',
       'ng-dynamic-component': 'npm:/ng-dynamic-component/dist/src/index.js'
    },

as you defined in the path

'npm:': 'node_modules/'

Please remove this extra backslash.


来源: stackexchange

问:
Typing Casting in Python Question
Im a AS3 developer, currently learning Python

In AS3 Id quite often do this:

```<code>for ( var foo in fooArray ) {
   trace(FooObject(foo).name);
}
</code>```

Typing casting the objects in the array, so that I get code hinting in my IDE

How would I do this in Python?

答:
Your best bet is to use logging.  Python has a default logging module (with five strict levels: debug, info, error, etc), but I prefer my own tagalog (which supports n arbitrary tags on log messages).

With python logging module:

```<code>import logging

for foo in foo_list:
    logging.log(type(foo))
</code>```

With tagalog:

```<code>import tagalog

for foo in foo_list:
    tagalog.log(type(foo))
</code>```

Either of these approaches will write entries to a log.  The output location for tagalog is always a file, which is specified in the 'log_file_path' variable here.  The output location for Python's logging module (docs here) depends on your configuration.

To watch a file in realtime, do this in the linux/unix/mac terminal:

```<code>tail -f /path/to/file
</code>```

ContentLicense: CC BY-SA 2.5

Title: Typing Casting in Python Question

Body:
Im a AS3 developer, currently learning Python

In AS3 Id quite often do this:

for ( var foo in fooArray ) {
   trace(FooObject(foo).name);
}

Typing casting the objects in the array, so that I get code hinting in my IDE

How would I do this in Python?

Body:
Your best bet is to use logging.  Python has a default logging module (with five strict levels: debug, info, error, etc), but I prefer my own tagalog (which supports n arbitrary tags on log messages).

With python logging module:

import logging

for foo in foo_list:
    logging.log(type(foo))

With tagalog:

import tagalog

for foo in foo_list:
    tagalog.log(type(foo))

Either of these approaches will write entries to a log.  The output location for tagalog is always a file, which is specified in the 'log_file_path' variable here.  The output location for Python's logging module (docs here) depends on your configuration.

To watch a file in realtime, do this in the linux/unix/mac terminal:

tail -f /path/to/file


问:
Apache Solr 6.6 replace document instead of update
I have configured solr 6.6.1 for a testing setup. After indexing few documents, I have to update few fields. I am using python client of solr. To update, following is my code snippet

```<code>import solr

def update_solr_index(_id, _value):
    print solr_conn2.add( id = _id, group2 = _value)

core_ulr = "http://localhost:8983/solr/use"
solr_conn2 = solr.SolrConnection(core_ulr)
update_solr_index(doc_id, field_value)
</code>```

After execution (and commit), all other fields are removed from all documents and only two fields left that are doc_id and group2. What is the problem is this API or in my code?

答:
There is no problem in the API. You are asking solr to add a document with an ID field that is already present in your collection. The following actions happen in solr.

Remove the existing document which has the same ID

Add new document with only the fields specified in that API call

The solution you are looking for is a partial update of a document.

Refer to the reference link to understand more on this Atomic updates

You need to send a map object for the field you want to update in your document.

```<code>solr_conn2.add(id=_id, group2=*****)
</code>```

The value to group2 must be a map like this {'set':'value...'}

You can probably refer to this similar stackoverflow solution similar answer

ContentLicense: CC BY-SA 3.0

Body:
I have configured solr 6.6.1 for a testing setup. After indexing few documents, I have to update few fields. I am using python client of solr. To update, following is my code snippet

import solr

def update_solr_index(_id, _value):
    print solr_conn2.add( id = _id, group2 = _value)

core_ulr = "http://localhost:8983/solr/use"
solr_conn2 = solr.SolrConnection(core_ulr)
update_solr_index(doc_id, field_value)

After execution (and commit), all other fields are removed from all documents and only two fields left that are doc_id and group2. What is the problem is this API or in my code?

Body:
There is no problem in the API. You are asking solr to add a document with an ID field that is already present in your collection. The following actions happen in solr.

Remove the existing document which has the same ID

Add new document with only the fields specified in that API call

The solution you are looking for is a partial update of a document.

Refer to the reference link to understand more on this Atomic updates

You need to send a map object for the field you want to update in your document.

solr_conn2.add(id=_id, group2=*****)

The value to group2 must be a map like this {'set':'value...'}

You can probably refer to this similar stackoverflow solution similar answer


问:
Change chrome extension icon when tab or url changes
I'm working on an extension and I want the icon to change when the active tab or url changes. Here's what i have so far:

manifest.json

```<code>{
  "manifest_version": 2,

  "name": "Link2QR",
  "description": "chrome_extension",
  "version": "1.0",

  "browser_action": {
    "default_icon":"icon.png",
    "default_popup": "popup.html"
   },

  "permissions": [
  "activeTab",
  "https://ajax.googleapis.com/",
  "tabs"
   ],

 "content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content.js"]
   }
 ]
}
</code>```

content.js

```<code>if(onSupportedPageNeedChangeIcon) {
    chrome.runtime.sendMessage({ "newIconPath" : "testimage.png" });
}
</code>```

popup.js

```<code>chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
   chrome.browserAction.setIcon({
       path: request.newIconPath,
       tabId: sender.tab.id
   });
});
</code>```

答:
You are handling the message in popup.js, which I suppose is running in the browser_action popup page.

popup.js thus only runs when the extension button is clicked.

You should instead handle it in background.js:

manifest.json

```<code>{
  "manifest_version": 2,
  "name": "test",
  "version": "0.0.1",
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_icon": {
      "24": "icon.png",
      "25": "icon.png"
    }
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}
</code>```

background.js

```<code>chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
   chrome.browserAction.setIcon({
       path: request.newIconPath,
       tabId: sender.tab.id
   });
});
</code>```

Body:
I'm working on an extension and I want the icon to change when the active tab or url changes. Here's what i have so far:

manifest.json

{
  "manifest_version": 2,

  "name": "Link2QR",
  "description": "chrome_extension",
  "version": "1.0",

  "browser_action": {
    "default_icon":"icon.png",
    "default_popup": "popup.html"
   },

  "permissions": [
  "activeTab",
  "https://ajax.googleapis.com/",
  "tabs"
   ],

 "content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content.js"]
   }
 ]
}

content.js

if(onSupportedPageNeedChangeIcon) {
    chrome.runtime.sendMessage({ "newIconPath" : "testimage.png" });
}

popup.js

chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
   chrome.browserAction.setIcon({
       path: request.newIconPath,
       tabId: sender.tab.id
   });
});

Body:
You are handling the message in popup.js, which I suppose is running in the browser_action popup page.

popup.js thus only runs when the extension button is clicked.

You should instead handle it in background.js:

manifest.json

{
  "manifest_version": 2,
  "name": "test",
  "version": "0.0.1",
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_icon": {
      "24": "icon.png",
      "25": "icon.png"
    }
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

background.js

chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
   chrome.browserAction.setIcon({
       path: request.newIconPath,
       tabId: sender.tab.id
   });
});


问:
Why are the subviews out of the bounds of my custom View not drawn?
I implement a custom SpinNumberView: it is square shaped (say 40x40), it has a vertical LinearLayout as a subview, within this linear layout are a bunch of 40x40 cells stacked vertically. I want to animate the cells to scroll vertically by changing offsetY of the LinearLayout.

But there is one problem: only the cell initially in bounds (the first) is rendered, the cells outside of the bounds are not drawn, so when I animate the LinearLayout to scroll, the linear layout is spinning, but only the first cell is visible, others are blank spaces. Here is my entire code for the custom View:

```<code>public class SpinNumberView extends RelativeLayout {
private int startNumber;
private int endNumber;
private int number;
private int gridsize;
private int index;
public static final double stepDuration = 0.1;

private boolean inAnimation = true;
ArrayList<Integer> numbers;
public LinearLayout container;

public SpinNumberView(Context context) {
    super(context);
}

public SpinNumberView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    // draw the background black solid circle
    float radius = (float)(this.gridsize);
    Paint p = new Paint();
    p.setStyle(Paint.Style.FILL);
    p.setARGB(192, 0, 0, 0);
    canvas.drawCircle(radius/2, radius/2, radius/2, p);
    // draw 1px white border
    Paint pp = new Paint();
    pp.setStyle(Paint.Style.STROKE);
    pp.setStrokeWidth(2.0f);
    pp.setARGB(192, 255, 255, 255);
    canvas.drawCircle(radius/2, radius/2, radius/2-1, pp);
    // clip to the circle
    Path path = new Path();
    RectF r = new RectF((float)0.0, (float)0.0, radius, radius);
    path.addRoundRect(r, radius/2, radius/2, Path.Direction.CW);
    canvas.clipPath(path);

    super.dispatchDraw(canvas);
}

@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
    super.onLayout(b, i, i1, i2, i3);
}

class AniListener implements Animator.AnimatorListener {
    @Override
    public void onAnimationStart(Animator animator) {}

    @Override
    public void onAnimationEnd(Animator animator) {
        SpinNumberView.this.animateStep();
    }

    @Override
    public void onAnimationCancel(Animator animator) {}

    @Override
    public void onAnimationRepeat(Animator animator) {}
}

public void animateStep() {
    this.container.setTranslationY(0);

    float offset;
    TimeInterpolator inter;

    if(this.inAnimation) {
        offset = (float)this.gridsize * this.numbers.size();
        inter = new LinearInterpolator();
    } else {
        offset = (float)this.gridsize * this.index;
        inter = new DecelerateInterpolator();
    }
    long duration = (long)(SpinNumberView.stepDuration * this.numbers.size() * 1000);

    ViewPropertyAnimator ani = this.container.animate().translationYBy(-offset).setDuration(duration);
    ani.setInterpolator(inter);
    if(this.inAnimation) {
        ani.setListener(new AniListener());
    } else {
        ani.setListener(null);
    }
    ani.start();
}

public void stopAnimation() {
    this.inAnimation = false;
}

public void startAnimation() {
    this.inAnimation = true;
    float offset = (float)this.gridsize * this.numbers.size();
    long duration = (long)(SpinNumberView.stepDuration * this.numbers.size() * 1000);
    ViewPropertyAnimator ani = this.container.animate().translationYBy(-offset).setDuration(duration);
    TimeInterpolator inter = new AccelerateInterpolator();
    ani.setInterpolator(inter);
    ani.setListener(new AniListener());
    ani.start();
}

public void setup(int number, int start, int end, int gridsize) {
    this.setBackgroundColor(Color.TRANSPARENT);
    this.setAlpha((float) 0.5);
    this.setClipChildren(false);

    this.number = number;
    this.startNumber = start;
    this.endNumber = end;
    this.gridsize = gridsize;
    this.numbers = new ArrayList<>();
    for(int i=start; i<=end;i++) {
        this.numbers.add(i);
    }
    Collections.shuffle(this.numbers);
    // Find index of target number within shuffled array
    this.index = this.numbers.indexOf(this.number);

    this.container = new LinearLayout(this.getContext());
    this.container.setOrientation(LinearLayout.VERTICAL);
    this.container.setGravity(Gravity.CENTER_HORIZONTAL);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(this.gridsize, this.gridsize * (this.numbers.size()+1));
    this.container.setLayoutParams(params);
    this.addView(this.container);

    int offsety = 0;
    // setup all the number views
    for(int k=0;k<this.numbers.size()+1;k++) {
        String txt;
        if(k==this.numbers.size()) {
            txt = Integer.toString(this.numbers.get(0));
        } else {
            txt = Integer.toString(this.numbers.get(k));
        }

        TextView tv = new TextView(this.getContext());
        tv.setLayoutParams(new LayoutParams(this.gridsize, this.gridsize));
        tv.setText(txt);
        tv.setTextSize(24.0f);
        tv.setTextColor(Color.WHITE);
        tv.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
        tv.setLines(1);
        tv.setGravity(Gravity.CENTER_VERTICAL);
        this.container.addView(tv);

        offsety += this.gridsize;
    }

    this.invalidate();
}
}
</code>```

Why is this happening?

BTW: I take a screenshot with getDrawingCache() of screen content, the cells are visible in the screenshot!

答: Glad you solved it by yourself, in iOS, we use something like Redraw method for these scenarios. Hopefully it will help you to further optimize your code.</p>

Body:
I implement a custom SpinNumberView: it is square shaped (say 40x40), it has a vertical LinearLayout as a subview, within this linear layout are a bunch of 40x40 cells stacked vertically. I want to animate the cells to scroll vertically by changing offsetY of the LinearLayout.

But there is one problem: only the cell initially in bounds (the first) is rendered, the cells outside of the bounds are not drawn, so when I animate the LinearLayout to scroll, the linear layout is spinning, but only the first cell is visible, others are blank spaces. Here is my entire code for the custom View:

public class SpinNumberView extends RelativeLayout {
private int startNumber;
private int endNumber;
private int number;
private int gridsize;
private int index;
public static final double stepDuration = 0.1;

private boolean inAnimation = true;
ArrayList<Integer> numbers;
public LinearLayout container;

public SpinNumberView(Context context) {
    super(context);
}

public SpinNumberView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    // draw the background black solid circle
    float radius = (float)(this.gridsize);
    Paint p = new Paint();
    p.setStyle(Paint.Style.FILL);
    p.setARGB(192, 0, 0, 0);
    canvas.drawCircle(radius/2, radius/2, radius/2, p);
    // draw 1px white border
    Paint pp = new Paint();
    pp.setStyle(Paint.Style.STROKE);
    pp.setStrokeWidth(2.0f);
    pp.setARGB(192, 255, 255, 255);
    canvas.drawCircle(radius/2, radius/2, radius/2-1, pp);
    // clip to the circle
    Path path = new Path();
    RectF r = new RectF((float)0.0, (float)0.0, radius, radius);
    path.addRoundRect(r, radius/2, radius/2, Path.Direction.CW);
    canvas.clipPath(path);

    super.dispatchDraw(canvas);
}

@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
    super.onLayout(b, i, i1, i2, i3);
}

class AniListener implements Animator.AnimatorListener {
    @Override
    public void onAnimationStart(Animator animator) {}

    @Override
    public void onAnimationEnd(Animator animator) {
        SpinNumberView.this.animateStep();
    }

    @Override
    public void onAnimationCancel(Animator animator) {}

    @Override
    public void onAnimationRepeat(Animator animator) {}
}

public void animateStep() {
    this.container.setTranslationY(0);

    float offset;
    TimeInterpolator inter;

    if(this.inAnimation) {
        offset = (float)this.gridsize * this.numbers.size();
        inter = new LinearInterpolator();
    } else {
        offset = (float)this.gridsize * this.index;
        inter = new DecelerateInterpolator();
    }
    long duration = (long)(SpinNumberView.stepDuration * this.numbers.size() * 1000);

    ViewPropertyAnimator ani = this.container.animate().translationYBy(-offset).setDuration(duration);
    ani.setInterpolator(inter);
    if(this.inAnimation) {
        ani.setListener(new AniListener());
    } else {
        ani.setListener(null);
    }
    ani.start();
}

public void stopAnimation() {
    this.inAnimation = false;
}

public void startAnimation() {
    this.inAnimation = true;
    float offset = (float)this.gridsize * this.numbers.size();
    long duration = (long)(SpinNumberView.stepDuration * this.numbers.size() * 1000);
    ViewPropertyAnimator ani = this.container.animate().translationYBy(-offset).setDuration(duration);
    TimeInterpolator inter = new AccelerateInterpolator();
    ani.setInterpolator(inter);
    ani.setListener(new AniListener());
    ani.start();
}

public void setup(int number, int start, int end, int gridsize) {
    this.setBackgroundColor(Color.TRANSPARENT);
    this.setAlpha((float) 0.5);
    this.setClipChildren(false);

    this.number = number;
    this.startNumber = start;
    this.endNumber = end;
    this.gridsize = gridsize;
    this.numbers = new ArrayList<>();
    for(int i=start; i<=end;i++) {
        this.numbers.add(i);
    }
    Collections.shuffle(this.numbers);
    // Find index of target number within shuffled array
    this.index = this.numbers.indexOf(this.number);

    this.container = new LinearLayout(this.getContext());
    this.container.setOrientation(LinearLayout.VERTICAL);
    this.container.setGravity(Gravity.CENTER_HORIZONTAL);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(this.gridsize, this.gridsize * (this.numbers.size()+1));
    this.container.setLayoutParams(params);
    this.addView(this.container);

    int offsety = 0;
    // setup all the number views
    for(int k=0;k<this.numbers.size()+1;k++) {
        String txt;
        if(k==this.numbers.size()) {
            txt = Integer.toString(this.numbers.get(0));
        } else {
            txt = Integer.toString(this.numbers.get(k));
        }

        TextView tv = new TextView(this.getContext());
        tv.setLayoutParams(new LayoutParams(this.gridsize, this.gridsize));
        tv.setText(txt);
        tv.setTextSize(24.0f);
        tv.setTextColor(Color.WHITE);
        tv.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
        tv.setLines(1);
        tv.setGravity(Gravity.CENTER_VERTICAL);
        this.container.addView(tv);

        offsety += this.gridsize;
    }

    this.invalidate();
}
}

Why is this happening?

BTW: I take a screenshot with getDrawingCache() of screen content, the cells are visible in the screenshot!


问:
Get object thymelaf
I have a for:each like this:

```<code><tbody>
    <tr th:each="bill : ${bills}" id="bill">
        <td th:text="${bill.bill_id}"></td>
        <td th:text="${bill.client.phone}"></td>
        <td th:text="${bill.date}"></td>
        <td><a href="#" class="btn btn-info btn-xs" data-toggle="modal"
    id="open-modal">Ver detalles</a></td>
    </tr>
</tbody>
</code>```

The question is how can I get the entire ${bill} to a variable in JavaScript or jQuery because I need more information. I saw the documentation and it said:

```<code> <script th:inline="javascript">
   /*<![CDATA[*/
   ...

    var user  name = /*[[${bill}]]*/ '';

    ...
   /*]]>*/
 </script>
</code>```

I have tried this on a external JavaScript file and it does not work.

答:
You can use the "data" attribute in your HTML:

```<code><td th-data:id="${bill.id}" th-data:name="${bill.nome}" class="js-datas">
</code>```

And in your javascript, then you can get:

```<code>var id = $('.js-datas').data('id');
var nome = $('.js-datas').data('name');
</code>```

You have to use the follow namespace in your HTML:

```<code>xmlns:data="http://www.thymeleaf.org/extras/data"
</code>```

Title: Get object thymelaf

Body:
I have a for:each like this:

        Ver detalles

The question is how can I get the entire ${bill} to a variable in JavaScript or jQuery because I need more information. I saw the documentation and it said:

I have tried this on a external JavaScript file and it does not work.

Body:
You can use the "data" attribute in your HTML:

<td th-data:id="${bill.id}" th-data:name="${bill.nome}" class="js-datas">

And in your javascript, then you can get:

var id = $('.js-datas').data('id');
var nome = $('.js-datas').data('name');

You have to use the follow namespace in your HTML:

xmlns:data="http://www.thymeleaf.org/extras/data"


问:
Show join table results even on condition is null
I have five table name books,categories,publications,author,reviews.

in my app user can review the book after login. so reviews table stay empty until user post a review.

I am trying to run the flowing query in codeigniter model to get book details by category_id and it's working perfect when their review is exist otherwise it's return empty array. this is happening because of this $this>db>join('reviews','reviews.book_id = books.book_id'); condition return false

how can i show result even reviews table on condition is not match?

```<code>public function get_book_details($cat_id) {

        $this->db->select('*');
        $this->db->from('books');
        $this->db->join('categories', 'categories.id = books.category_id');
        $this->db->join('publications', 'publications.id = books.publication_id');
        $this->db->join('author', 'author.id = books.author_id');
        $this->db->join('reviews', 'reviews.book_id = books.book_id');
        $this->db->where('categories.id', $cat_id);

        $query = $this->db->get();
        return $query->result();
    }
</code>```

答:
Use LEFT JOIN to get the result if there are no matching associations are found

```<code>$this->db->join('reviews', 'reviews.book_id = books.book_id','LEFT');
</code>```

Body:
I have five table name books,categories,publications,author,reviews.

in my app user can review the book after login. so reviews table stay empty until user post a review.

I am trying to run the flowing query in codeigniter model to get book details by category_id and it's working perfect when their review is exist otherwise it's return empty array. this is happening because of this $this>db>join('reviews','reviews.book_id = books.book_id'); condition return false

how can i show result even reviews table on condition is not match?

public function get_book_details($cat_id) {

        $this->db->select('*');
        $this->db->from('books');
        $this->db->join('categories', 'categories.id = books.category_id');
        $this->db->join('publications', 'publications.id = books.publication_id');
        $this->db->join('author', 'author.id = books.author_id');
        $this->db->join('reviews', 'reviews.book_id = books.book_id');
        $this->db->where('categories.id', $cat_id);

        $query = $this->db->get();
        return $query->result();
    }

Body:
Use LEFT JOIN to get the result if there are no matching associations are found

$this->db->join('reviews', 'reviews.book_id = books.book_id','LEFT');


问:
java.lang.NullPointerException: while take photo
Im getting this error, when click deny permission in  "Allow app to access photos, media and files on your device ? "

```<code>    FATAL EXCEPTION: main
   Process: com.viantti.app, PID: 12349
   java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
</code>```

java error line,

```<code>public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}
</code>```

答:
java code here,

Img_profile_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Build.VERSION.SDK_INT >= 23) {
                    // Marshmallow+
                    if (!checkAccessFineLocationPermission() || !checkWriteExternalStoragePermission()) {
                        requestPermission();
                    } else {
                        chooseimage();
                    }
                } else {
                    chooseimage();
                }

            }
        });

    }

    private void takePicture() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camera_FileUri = getOutputMediaFileUri(1);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, camera_FileUri);
        // start the image capture Intent
        startActivityForResult(intent, REQUEST_TAKE_PHOTO);
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, galleryRequestCode);
    }

    /**
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == 1) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else {
            return null;
        }

        return mediaFile;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putParcelable("file_uri", camera_FileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        camera_FileUri = savedInstanceState.getParcelable("file_uri");
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_TAKE_PHOTO ||  requestCode == UCrop.REQUEST_CROP) {
                try {
                    if (requestCode == REQUEST_TAKE_PHOTO) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 8;

                        final Bitmap bitmap = BitmapFactory.decodeFile(camera_FileUri.getPath(), options);
                        Bitmap thumbnail = bitmap;
                        final String picturePath = camera_FileUri.getPath();
//                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                        File curFile = new File(picturePath);
                        try {
                            ExifInterface exif = new ExifInterface(curFile.getPath());
                            int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                            int rotationInDegrees = exifToDegrees(rotation);

                            Matrix matrix = new Matrix();
                            if (rotation != 0f) {
                                matrix.preRotate(rotationInDegrees);
                            }
                        //    thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
                        } catch (IOException ex) {
                            Log.e("TAG", "Failed to get Exif data", ex);
                        }

                        System.out.println("edit-----" + Iconstant.Edit_profile_image_url);

                        Uri picUri = Uri.fromFile(curFile);

                        UCrop.of(picUri, picUri)
                                .withAspectRatio(4, 4)
                                .withMaxResultSize(8000, 8000)
                                .start(ProfilePage.this);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if (requestCode == galleryRequestCode) {

                Uri selectedImage = data.getData();
                if (selectedImage.toString().startsWith("content://com.sec.android.gallery3d.provider")) {
                    String[] filePath = {MediaStore.Images.Media.DATA};
                    Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    final String picturePath = c.getString(columnIndex);
                    c.close();
                    File curFile = new File(picturePath);

                    Picasso.with(ProfilePage.this).load(picturePath).resize(100, 100).into(new Target() {
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                            Bitmap thumbnail = bitmap;
                            mSelectedFilePath = picturePath;
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
                        }

                        @Override
                        public void onBitmapFailed(Drawable errorDrawable) {
                        }

                        @Override
                        public void onPrepareLoad(Drawable placeHolderDrawable) {
                        }
                    });

                    Uri picUri = Uri.fromFile(curFile);

                    UCrop.of(picUri, picUri)
                            .withAspectRatio(4, 4)
                            .withMaxResultSize(8000, 8000)
                            .start(ProfilePage.this);

                } else {
                    String[] filePath = {MediaStore.Images.Media.DATA};
                    Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                    c.moveToFirst();

                    int columnIndex = c.getColumnIndex(filePath[0]);
                    final String picturePath = c.getString(columnIndex);
                    Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
                    Bitmap thumbnail = bitmap; //getResizedBitmap(bitmap, 600);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    File curFile = new File(picturePath);

                    try {
                        ExifInterface exif = new ExifInterface(curFile.getPath());
                        int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                        int rotationInDegrees = exifToDegrees(rotation);

                        Matrix matrix = new Matrix();
                        if (rotation != 0f) {
                            matrix.preRotate(rotationInDegrees);
                        }
                        thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
                    } catch (IOException ex) {
                        Log.e("TAG", "Failed to get Exif data", ex);
                    }
                    thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);

                    c.close();
                                        Uri picUri = Uri.fromFile(curFile);

                    UCrop.of(picUri, picUri)
                            .withAspectRatio(4, 4)
                            .withMaxResultSize(8000, 8000)
                            .start(ProfilePage.this);
                                    }
            }

            if ( requestCode == UCrop.REQUEST_CROP) {

                final Uri resultUri = UCrop.getOutput(data);
                try {
                    selectedBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
                byteArray = byteArrayOutputStream.toByteArray();
                Img_profile_pic.setImageBitmap(selectedBitmap);
                Img_profile_pic.setImageURI(resultUri);
                UploadDriverImage(Iconstant.Edit_profile_image_url);

            } else if (resultCode == UCrop.RESULT_ERROR) {
                final Throwable cropError = UCrop.getError(data);
                System.out.println("========muruga cropError==========="+cropError);
            }

        }

    }

    private static int exifToDegrees(int exifOrientation) {
        if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
            return 90;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
            return 180;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
            return 270;
        }
        return 0;
    }

    private void UploadDriverImage(String url) {

        dialog = new Dialog(ProfilePage.this);
        dialog.getWindow();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.custom_loading);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        TextView dialog_title = (TextView) dialog.findViewById(R.id.custom_loading_textview);
        dialog_title.setText(getResources().getString(R.string.action_loading));

        VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {

                System.out.println("------------- image response-----------------"+response.data);

                String resultResponse = new String(response.data);
                System.out.println("-------------  response-----------------"+resultResponse);
                String sStatus = "", sResponse = "",SUser_image="",Smsg="";
                try {
                    JSONObject jsonObject = new JSONObject(resultResponse);
                    sStatus = jsonObject.getString("status");
                    if (sStatus.equalsIgnoreCase("1")) {
                //        JSONObject responseObject = jsonObject.getJSONObject("response");
                    //    SUser_image = jsonObject.getString("image");
                        Smsg = jsonObject.getString("image_url");

                 //       Img_profile_pic.setImageBitmap(bitMapThumbnail);
                        session.setuser_image(Smsg);
                        Picasso.with(ProfilePage.this).load(Smsg).placeholder(R.drawable.no_user_image).into(Img_profile_pic);

                        NavigationDrawer.navigationNotifyChange();
                        Locale locale = null;
                        switch (language_code){

                            case "en":
                                locale = new Locale("en");
                                session.setlamguage("en","en");

                                break;
                            case "es":
                                locale = new Locale("es");
                                session.setlamguage("es","es");
                                //      session.setlamguage("Ar",language_change.getSelectedItem().toString());
                                //     System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
                                //     Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
                                //     finish();
                                //     startActivity(i);

//                        Intent bii = new Intent();
//                        bii.setAction("homepage");
//                        sendBroadcast(bii);
//                        finish();
                                break;
                            case "ta":
                                locale = new Locale("ta");
                                session.setlamguage("ta","ta");
                                //      session.setlamguage("Ar",language_change.getSelectedItem().toString());
                                //     System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
                                //     Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
                                //     finish();
                                //     startActivity(i);

//                        Intent bii = new Intent();
//                        bii.setAction("homepage");
//                        sendBroadcast(bii);
//                        finish();
                                break;
                            default:
                                locale = new Locale("en");
                                session.setlamguage("en","en");
                                break;
                        }

                        Locale.setDefault(locale);
                        Configuration config = new Configuration();
                        config.locale = locale;
                        getApplicationContext().getResources().updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics());

                        Alert(getResources().getString(R.string.action_success),getResources().getString(R.string.edit_profile_success_label));

                    } else {
                        sResponse = jsonObject.getString("response");
                        Alert(getResources().getString(R.string.my_rides_rating_header_sorry_textview), sResponse);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                catch (Exception e) {
                    Toast.makeText(ProfilePage.this,"Something happened , try again",Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                dialog.dismiss();

                NetworkResponse networkResponse = error.networkResponse;
                String errorMessage = "Unknown error";
                if (networkResponse == null) {
                    if (error.getClass().equals(TimeoutError.class)) {
                        errorMessage = "Request timeout";
                    } else if (error.getClass().equals(NoConnectionError.class)) {
                        errorMessage = "Failed to connect server";
                    }
                } else {
                    String result = new String(networkResponse.data);
                    try {
                        JSONObject response = new JSONObject(result);
                        String status = response.getString("status");
                        String message = response.getString("message");

                        Log.e("Error Status", status);
                        Log.e("Error Message", message);

                        if (networkResponse.statusCode == 404) {
                            errorMessage = "Resource not found";
                        } else if (networkResponse.statusCode == 401) {
                            errorMessage = message + " Please login again";
                        } else if (networkResponse.statusCode == 400) {
                            errorMessage = message + " Check your inputs";
                        } else if (networkResponse.statusCode == 500) {
                            errorMessage = message + " Something is getting wrong";
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                Log.i("Error", errorMessage);
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                System.out.println("------------Authkey------cabily---------" + Agent_Name);
                System.out.println("------------userid----------cabily-----" + UserID);
                System.out.println("------------apptoken----------cabily-----" + gcmID);
                System.out.println("------------applanguage----------cabily-----" + language_code);
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authkey", Agent_Name);
                headers.put("isapplication",Iconstant.cabily_IsApplication);
                headers.put("applanguage",language_code);
                headers.put("apptype", Iconstant.cabily_AppType);
                headers.put("userid",UserID);
                headers.put("apptoken",gcmID);
              /*  System.out.println("servicereques  apptype------------------"+Iconstant.cabily_AppType);
                System.out.println("servicereques apptoken------------------"+gcmID);
                System.out.println("servicereques userid------------------"+UserID);
                Map<String, String> headers = new HashMap<String, String>();

                headers.put("User-agent",Iconstant.cabily_userAgent);
                headers.put("isapplication",Iconstant.cabily_IsApplication);
                headers.put("applanguage",Iconstant.cabily_AppLanguage);
                headers.put("apptype",Iconstant.cabily_AppType);
                headers.put("apptoken",gcmID);
                headers.put("userid",UserID);*/

                return headers;
            }
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("user_id",UserID);
                System.out.println("user_id---------------"+UserID);
                return params;
            }

            @Override
            protected Map<String, DataPart> getByteData() {
                Map<String, DataPart> params = new HashMap<>();
                params.put("user_image",new DataPart("cabily_user.jpg", byteArray));

                System.out.println("user_image--------edit------"+byteArray);

                return params;
            }
        };

        //to avoid repeat request Multiple Time
        DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        multipartRequest.setRetryPolicy(retryPolicy);
        multipartRequest.setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        multipartRequest.setShouldCache(false);
        AppController.getInstance().addToRequestQueue(multipartRequest);

    }

    // --------------------Method for choose image to edit profileimage--------------------
    private void chooseimage() {
        photo_dialog = new Dialog(ProfilePage.this);
        photo_dialog.getWindow();
        photo_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        photo_dialog.setContentView(R.layout.image_upload_dialog);
        photo_dialog.setCanceledOnTouchOutside(true);
        photo_dialog.getWindow().getAttributes().windowAnimations = R.style.Animations_photo_Picker;
        photo_dialog.show();
        photo_dialog.getWindow().setGravity(Gravity.CENTER);

        RelativeLayout camera = (RelativeLayout) photo_dialog
                .findViewById(R.id.profilelayout_takephotofromcamera);
        RelativeLayout gallery = (RelativeLayout) photo_dialog
                .findViewById(R.id.profilelayout_takephotofromgallery);

        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
                photo_dialog.dismiss();
            }
        });

        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
                photo_dialog.dismiss();
            }
        });
    }

    private boolean checkAccessFineLocationPermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    private boolean checkAccessCoarseLocationPermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    private boolean checkWriteExternalStoragePermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ||  grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
                    chooseimage();
                } else {
                    finish();
                }
                break;
        }
    }```

Body:
Im getting this error, when click deny permission in  "Allow app to access photos, media and files on your device ? "

    FATAL EXCEPTION: main
   Process: com.viantti.app, PID: 12349
   java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)

java error line,

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}


问:
every request from a django app increasing mysql number of connections
I have a project built using django 1.11 and i am sending a request from my admin view and it is creating a new DB connection on every request(using django development server, runserver).

But the same thing using gunicorn as server does not increase the number of connections in DB it uses same connection that was created in first request.

In my database settings CONN_MAX_AGE is set to 300 which is 5mins. I am sending second request within 5 mins, so it is supposed to use same connection that was created in first request.

Any idea why, with runserver, django is creating new DB connection on every request and not following persistent connections behavior of django ?

答:
From the docs:

The development server creates a new thread for each request it
  handles, negating the effect of persistent connections. Don’t enable
  them during development.


问:
htaccess multiple domain, force specific domain and its paths to www and exclude a path but redirect excluded path
How to force a specific domain name and all its path to www except a specific path but redirect that specific path to another domain. So what I want is to force
en.one and all its paths to www.en.one except en.one/admin. but on top of that I want the excluded en.one/admin to go to another domain http://www.en.me.

So far I have managed to exclude en.one/admin but I still have failed to redirect en.one/admin to http://www.en.me.

My code

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^en.one$
RewriteCond %{THE_REQUEST} !/admin //This excludes the /admin
RewriteRule (.*) http://www.en.one/$1 [R=301,L]
</code>```

Note: this is a multisite and multiple domains are managed by this single .htaccess file so solution is really important to be domain specific.

答:
Thanks to @Christophe for helping me find a solution. You can check out our conversation as comments within Christophe's answer. The solution was to repeat the HTTP_HOST condition again. So in the end my .htaccess looked like this.

```<code>RewriteEngine on
RewriteCond %{HTTP_host} ^en.one$
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/admin
RewriteRule ^(.*) http://www.en.one/$1 [R=301,L]
RewriteCond %{HTTP_host} ^en.one$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/admin
RewriteRule ^(.*) http://www.en.me/ [R=301,L]
</code>```

I am sure there could be better solutions but this works for me just as I wanted.

Body:
How to force a specific domain name and all its path to www except a specific path but redirect that specific path to another domain. So what I want is to force
en.one and all its paths to www.en.one except en.one/admin. but on top of that I want the excluded en.one/admin to go to another domain http://www.en.me.

So far I have managed to exclude en.one/admin but I still have failed to redirect en.one/admin to http://www.en.me.

My code

RewriteEngine on
RewriteCond %{HTTP_HOST} ^en.one$
RewriteCond %{THE_REQUEST} !/admin //This excludes the /admin
RewriteRule (.*) http://www.en.one/$1 [R=301,L]

Note: this is a multisite and multiple domains are managed by this single .htaccess file so solution is really important to be domain specific.

Body:
Thanks to @Christophe for helping me find a solution. You can check out our conversation as comments within Christophe's answer. The solution was to repeat the HTTP_HOST condition again. So in the end my .htaccess looked like this.

RewriteEngine on
RewriteCond %{HTTP_host} ^en.one$
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/admin
RewriteRule ^(.*) http://www.en.one/$1 [R=301,L]
RewriteCond %{HTTP_host} ^en.one$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/admin
RewriteRule ^(.*) http://www.en.me/ [R=301,L]

I am sure there could be better solutions but this works for me just as I wanted.


问:
Invalid Syntax (near date)
i found this code in stackoverflow. suits my requirements. i'm using an mysql db that consists of id, date, gender, name and surname. i have made few changes to the code so that i can obtain the date and other info between the start date and the end date.

```<code>import mysql
import mysql.connector
import command
import datetime

def findarbs(startdate, enddate):
      con = mysql.connector.connect(user='root', password='root',
host='localhost',port='3306',database='testdb')
      cur = con.cursor()
      command = ("SELECT DISTINCT id, date FROM babyrop", WHERE 'date1'
      > ('%s') AND 'date2' < ('%s'), ORDER BY date asc % (startdate,
enddate))
print ('command')
cursor.execute(command)
result = cur.fetchone()
print (result)
while result is not None:
print (result[1])
result = cursor.fetchone()
cur = con.cursor()
cur.execute('select id, date weight from babyrop')

data = cursor.fetchall()
cur.close()
con.close()
</code>```

when i tried executing it i'm getting an error "invalid syntax" near date. let me know what corrections to are required.

答:
You are terminating the string way too early. You also have invalid commas in the query.

```<code>command = ("SELECT DISTINCT id, date FROM babyrop", WHERE 'date1'
      > ('%s') AND 'date2' < ('%s'), ORDER BY date asc % (startdate,
enddate))
</code>```

"should" be

```<code>    command = ("SELECT DISTINCT id, date FROM babyrop WHERE 'date1'
  > ('%s') AND 'date2' < ('%s') ORDER BY date asc" % (startdate,
enddate))
</code>```

I wrote "should" because you should not use string concatenation in queries since it exposes your code to SQL injection. You should use parametrized queries instead. It also recommended to use triple quotes for query strings so they can be broken apart nicely:

```<code>    command = """SELECT DISTINCT id, date
                 FROM babyrop
                 WHERE 'date1' > ('%s') AND 'date2' < ('%s')
                 ORDER BY date asc"""

    cursor.execute(command, (startdate, enddate))
</code>```

Also, I'm pretty sure that you don't need the single quotes (') around the columns names and the placeholders in the where clause but that might be a MySQL thing.

Title: Invalid Syntax (near date)

Body:
i found this code in stackoverflow. suits my requirements. i'm using an mysql db that consists of id, date, gender, name and surname. i have made few changes to the code so that i can obtain the date and other info between the start date and the end date.

import mysql
import mysql.connector
import command
import datetime

def findarbs(startdate, enddate):
      con = mysql.connector.connect(user='root', password='root',
host='localhost',port='3306',database='testdb')
      cur = con.cursor()
      command = ("SELECT DISTINCT id, date FROM babyrop", WHERE 'date1'
      > ('%s') AND 'date2' < ('%s'), ORDER BY date asc % (startdate,
enddate))
print ('command')
cursor.execute(command)
result = cur.fetchone()
print (result)
while result is not None:
print (result[1])
result = cursor.fetchone()
cur = con.cursor()
cur.execute('select id, date weight from babyrop')

data = cursor.fetchall()
cur.close()
con.close()

when i tried executing it i'm getting an error "invalid syntax" near date. let me know what corrections to are required.

Body:
You are terminating the string way too early. You also have invalid commas in the query.

command = ("SELECT DISTINCT id, date FROM babyrop", WHERE 'date1'
      > ('%s') AND 'date2' < ('%s'), ORDER BY date asc % (startdate,
enddate))

"should" be

    command = ("SELECT DISTINCT id, date FROM babyrop WHERE 'date1'
  > ('%s') AND 'date2' < ('%s') ORDER BY date asc" % (startdate,
enddate))

I wrote "should" because you should not use string concatenation in queries since it exposes your code to SQL injection. You should use parametrized queries instead. It also recommended to use triple quotes for query strings so they can be broken apart nicely:

    command = """SELECT DISTINCT id, date
                 FROM babyrop
                 WHERE 'date1' > ('%s') AND 'date2' < ('%s')
                 ORDER BY date asc"""

    cursor.execute(command, (startdate, enddate))

Also, I'm pretty sure that you don't need the single quotes (') around the columns names and the placeholders in the where clause but that might be a MySQL thing.


问:
Jquery Fittext not work with bootstrap carousel
JSFiddle

```<code>Link jsfiddle  https://jsfiddle.net/jimmyphong/867wvc9u/2/
</code>```

Im using jquery Fittext with bootstrap carousel , for first and active item work fine , so with another item or (hidden maybe) it not work !

any help !

Thanks

答:
Its an old question but here is a quick solution if anyone else come seek for an answer.

bootstrap have 2 triggers in the carousel plugin slide and slid (Read Documentation). But you can not use slide as it triggers just before it starts sliding and that stage the next slide is in display:none and fitText plugin will add the minFontSize to it. And you can use slid. It will trigger just after sliding is completed. So in this case to avoid flickering on this we need to find a place where it has to be just after display:none is gone. so the ideal place is animated state. So in order to do that you need to observe the element with class change and trigger a element resize.

Please find below the solution,

Initiate fitText, Documentation

```<code>$(".fittext").fitText(0.2, { minFontSize: '20px', maxFontSize: '100px' });
</code>```

Write an observer extension to jquery addClass

```<code>// Extends functionality of ".addClass()"
(function(){
    var originalAddClassMethod = jQuery.fn.addClass;
    $.fn.addClass = function(){
        var result = originalAddClassMethod.apply( this, arguments );
        $(this).trigger('addClassChanged');
        return result;
    }
})();
</code>```

And run the element resize event on class change.

```<code>$('.carousel-item').on('addClassChanged', function(){
    $(window).resize();
});
</code>```

Updated jsfiddle: https://jsfiddle.net/867wvc9u/12/

Note:- Since resize event keeps listen to the DOM, we can tweak the fitText plugin a bit to overcome unexpected call stack overkill issues.

Update the window event line in the fitText plugin.

```<code>...
$(window).on('resize.fittext click.fittext orientationchange.fittext', resizer);
...
</code>```

and do a click instead, in the addClassChanged event,

```<code>$('.carousel-item').on('addClassChanged', function(){
    $(window).click();
});
</code>```

Body:
JSFiddle

Link jsfiddle  https://jsfiddle.net/jimmyphong/867wvc9u/2/

Im using jquery Fittext with bootstrap carousel , for first and active item work fine , so with another item or (hidden maybe) it not work !

any help !

Thanks

Body:
Its an old question but here is a quick solution if anyone else come seek for an answer.

bootstrap have 2 triggers in the carousel plugin slide and slid (Read Documentation). But you can not use slide as it triggers just before it starts sliding and that stage the next slide is in display:none and fitText plugin will add the minFontSize to it. And you can use slid. It will trigger just after sliding is completed. So in this case to avoid flickering on this we need to find a place where it has to be just after display:none is gone. so the ideal place is animated state. So in order to do that you need to observe the element with class change and trigger a element resize.

Please find below the solution,

Initiate fitText, Documentation

$(".fittext").fitText(0.2, { minFontSize: '20px', maxFontSize: '100px' });

Write an observer extension to jquery addClass

// Extends functionality of ".addClass()"
(function(){
    var originalAddClassMethod = jQuery.fn.addClass;
    $.fn.addClass = function(){
        var result = originalAddClassMethod.apply( this, arguments );
        $(this).trigger('addClassChanged');
        return result;
    }
})();

And run the element resize event on class change.

$('.carousel-item').on('addClassChanged', function(){
    $(window).resize();
});

Updated jsfiddle: https://jsfiddle.net/867wvc9u/12/

Note:- Since resize event keeps listen to the DOM, we can tweak the fitText plugin a bit to overcome unexpected call stack overkill issues.

Update the window event line in the fitText plugin.

...
$(window).on('resize.fittext click.fittext orientationchange.fittext', resizer);
...

and do a click instead, in the addClassChanged event,

$('.carousel-item').on('addClassChanged', function(){
    $(window).click();
});


问:
Xamarin.Android : ListView not scrolling correctly in Coordinator Layout and CollapsingToolbarLayout
Good morning everyone!

I'm facing a scrolling issue in my app. I have a Coordinator Layout and a Listview. I want the top layout to be collapsing when I scroll in my listview.
I searched and found that this is not possible without a NestedScrollView so I added one.

The problem is that when I scroll, only the coordinator layout is scrolling.

As an example, when I scroll to the down, the listview is stuck like that:

I also tried to set the layout_height of my Listview to match_parent but it doesn't change anything.

Here is my code:

main.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ActionBarNoShadowLight"
        android:fitsSystemWindows="true"
        app:elevation="0dp">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            android:fitsSystemWindows="true">
            <ImageView
                android:id="@+id/mainImage"
                android:layout_width="175dp"
                android:layout_height="175dp"
                android:layout_marginTop="50dp"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/ic_document"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />
            <android.support.v7.widget.Toolbar
                android:id="@+id/edit_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/BackgroundWhite"
                app:layout_collapseMode="pin"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:clipToPadding="false"
        android:scrollbars="none"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <ListView
                android:id="@+id/lstTask"
                android:layout_height="match_parent"
                android:layout_width="fill_parent"
                android:nestedScrollingEnabled="true"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:divider="@null"
                />
            <ImageView
                android:id="@+id/empty"
                android:layout_height="200dp"
                android:layout_width="200dp"
                android:layout_marginTop="50dp"
                android:scaleType="fitCenter"
                android:gravity="center"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                app:srcCompat="@drawable/bg_notasks" />
        </FrameLayout>
    </android.support.v4.widget.NestedScrollView>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_plus" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Thanks a lot for your future help,
Clément.

答:
Create a NonScrollListView class like below

```<code>public class NonScrollListView extends ListView{

public NonScrollListView(Context context) {
    super(context);
}

public NonScrollListView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
            Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
    ViewGroup.LayoutParams params = getLayoutParams();
    params.height = getMeasuredHeight();
}
}
</code>```

And in your xml add layout behaviour

```<code><android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/ll_pro_profile_reviews"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

<com.vanitee.services.home.customer.shops.detail.reviews.NonScrollExpandableListView
    android:id="@+id/rcv_pro_profile_reviews"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/spacing_8"/>

</android.support.v4.widget.NestedScrollView>
</code>```

And finally in your code where you initialize your listView you need to disable nested scrolling

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   listView.setNestedScrollingEnabled(false);
} else {
   ViewCompat.setNestedScrollingEnabled(listView, false);
}
</code>```

Body:
Good morning everyone!

I'm facing a scrolling issue in my app. I have a Coordinator Layout and a Listview. I want the top layout to be collapsing when I scroll in my listview.
I searched and found that this is not possible without a NestedScrollView so I added one.

The problem is that when I scroll, only the coordinator layout is scrolling.

As an example, when I scroll to the down, the listview is stuck like that:

I also tried to set the layout_height of my Listview to match_parent but it doesn't change anything.

Here is my code:

main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ActionBarNoShadowLight"
        android:fitsSystemWindows="true"
        app:elevation="0dp">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            android:fitsSystemWindows="true">
            <ImageView
                android:id="@+id/mainImage"
                android:layout_width="175dp"
                android:layout_height="175dp"
                android:layout_marginTop="50dp"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/ic_document"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />
            <android.support.v7.widget.Toolbar
                android:id="@+id/edit_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/BackgroundWhite"
                app:layout_collapseMode="pin"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:clipToPadding="false"
        android:scrollbars="none"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <ListView
                android:id="@+id/lstTask"
                android:layout_height="match_parent"
                android:layout_width="fill_parent"
                android:nestedScrollingEnabled="true"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:divider="@null"
                />
            <ImageView
                android:id="@+id/empty"
                android:layout_height="200dp"
                android:layout_width="200dp"
                android:layout_marginTop="50dp"
                android:scaleType="fitCenter"
                android:gravity="center"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                app:srcCompat="@drawable/bg_notasks" />
        </FrameLayout>
    </android.support.v4.widget.NestedScrollView>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_plus" />
</android.support.design.widget.CoordinatorLayout>

Thanks a lot for your future help,
Clément.

Body:
Create a NonScrollListView class like below

public class NonScrollListView extends ListView{

public NonScrollListView(Context context) {
    super(context);
}

public NonScrollListView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
            Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
    ViewGroup.LayoutParams params = getLayoutParams();
    params.height = getMeasuredHeight();
}
}

And in your xml add layout behaviour

<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/ll_pro_profile_reviews"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

<com.vanitee.services.home.customer.shops.detail.reviews.NonScrollExpandableListView
    android:id="@+id/rcv_pro_profile_reviews"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/spacing_8"/>

</android.support.v4.widget.NestedScrollView>

And finally in your code where you initialize your listView you need to disable nested scrolling

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   listView.setNestedScrollingEnabled(false);
} else {
   ViewCompat.setNestedScrollingEnabled(listView, false);
}


问:
Glide 4.3.1 override and placeholder features not work
I update my glide to 4.3.1 but all over I use glide the feature .override() and .placeholder() get error: cannot find symbol method.

```<code>Glide.with(this)
            .load(imageUrl)
            .override(200, 200)
            .placeholder(R.drawable.ic_avatar_sign_up)
            .into(ivAvatar);
</code>```

How can I fix this?

答:
Try This</p>

```<code>Glide.with(this)
     .load(imageUrl)
     .apply(new RequestOptions().placeholder(R.drawable.ic_launcher).override(200, 200))
     .into(ivAvatar);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I update my glide to 4.3.1 but all over I use glide the feature .override() and .placeholder() get error: cannot find symbol method.

Glide.with(this)
            .load(imageUrl)
            .override(200, 200)
            .placeholder(R.drawable.ic_avatar_sign_up)
            .into(ivAvatar);

How can I fix this?

Body:
Try This

Glide.with(this)
     .load(imageUrl)
     .apply(new RequestOptions().placeholder(R.drawable.ic_launcher).override(200, 200))
     .into(ivAvatar);


问:
Template error when displaying hostname in Spring Boot sample application - pet clinic
I'm using the sample spring-petclinic Spring Boot app for a demo I'm building. I'm trying to do something that seems super basic, but am struggling (I'm a Java n00b).

Here's the sample app: https://github.com/spring-projects/spring-petclinic

Essentially I want to display the server hostname on the welcome page of the website.

In the WelcomeController.java file (spring-petclinic/src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java) I have the following:

```<code>package org.springframework.samples.petclinic.system;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
class WelcomeController {

    @RequestMapping("/")
    public String welcome() {
        return "Hello from " + System.getenv("HOSTNAME") + String.format("%n");
    }
}
</code>```

All I have replaced is the return value from return "welcome" to what you see above.

The build completes and I can run the application, but the page loads with the following error:

```<code>Something happened...

Error resolving template "Hello from d7710dcc2456 ", template might not exist or might not be accessible by any of the configured Template Resolvers
</code>```

I've played around with model.addAttribute and adding additional public String blocks, but am a little out of my depth! Any ideas?

答:
UPDATE - after edit the question

To get hostname of running machine, try the following

```<code>import java.net.InetAddress;
import java.net.UnknownHostException;

String hostname;
try {
    InetAddress ia = InetAddress.getLocalHost();
    hostname =  ia.getHostName();
} catch (UnknownHostException e) {
    e.printStackTrace();
}
//assuming your thymeleaf template file called 'welcome'
model.addAttribute("hostname", hostname);
return "welcome";
</code>```

And in your template file

```<code><h1>Hello from <span th:text="${hostname}">hostname</span></h1>
</code>```

Body:
I'm using the sample spring-petclinic Spring Boot app for a demo I'm building. I'm trying to do something that seems super basic, but am struggling (I'm a Java n00b).

Here's the sample app: https://github.com/spring-projects/spring-petclinic

Essentially I want to display the server hostname on the welcome page of the website.

In the WelcomeController.java file (spring-petclinic/src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java) I have the following:

package org.springframework.samples.petclinic.system;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
class WelcomeController {

    @RequestMapping("/")
    public String welcome() {
        return "Hello from " + System.getenv("HOSTNAME") + String.format("%n");
    }
}

All I have replaced is the return value from return "welcome" to what you see above.

The build completes and I can run the application, but the page loads with the following error:

Something happened...

Error resolving template "Hello from d7710dcc2456 ", template might not exist or might not be accessible by any of the configured Template Resolvers

I've played around with model.addAttribute and adding additional public String blocks, but am a little out of my depth! Any ideas?

Body:
UPDATE - after edit the question

To get hostname of running machine, try the following

import java.net.InetAddress;
import java.net.UnknownHostException;

String hostname;
try {
    InetAddress ia = InetAddress.getLocalHost();
    hostname =  ia.getHostName();
} catch (UnknownHostException e) {
    e.printStackTrace();
}
//assuming your thymeleaf template file called 'welcome'
model.addAttribute("hostname", hostname);
return "welcome";

And in your template file

<h1>Hello from <span th:text="${hostname}">hostname</span></h1>


问:
How to realize with a serializer, when the admin user request, serialize all the fields, but the normal user request, serialize part fields?
How to realize with a serializer, when the admin user request, serialize all the fields, but the normal user request, serialize part fields in Rest Framework?

In my serializers:

```<code>class UserListSerializer(ModelSerializer):
    """
    user serializer
    """
    account = AccountSerializer(many=False, read_only=True)
    class Meta:
        model = User
        exclude = [
            'password',
        ]
...

class AccountSerializer(ModelSerializer):
    """
    user's accout
    """
    class Meta:
        model = Account
        exclude = [
            'total_charge',
            'total_consume',
        ]
</code>```

In the views:

```<code> class UserListAPIView(ListAPIView):
    """
    the user view
    """
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)
    serializer_class = UserListSerializer
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['username', 'qq', 'email']
    pagination_class = UserPageNumberPagination

    class Meta:
       ordering = ['-id']
</code>```

My requirement is that when I use normal user request the APIView, I want to exclude the bellow fields:

```<code>'total_charge','total_consume'
</code>```

If I use the admin user request the APIView, I want to serialize all the fields.

EDIT

I add the get_serializer_class merhod:

```<code>class UserListAPIView(ListAPIView):
    """
    返回普通用户列表
    """
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)

    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['username', 'qq', 'email']
    pagination_class = UserPageNumberPagination

    class Meta:
       ordering = ['-id']

    def get_serializer_class(self):
        if self.request.user.is_superuser:
            return UserAdminListSerializer
        else:
            return UserListSerializer

    serializer_class = get_serializer_class()  # if I put this line in the front of `def get_serializer_class(self)` I will get not find error.
</code>```

when I run the server, it get issue here:

The traceback:

```<code> File "/Users/xsx/Desktop/xsx/Project/xss/qiyun_admin_usermanage/api/views.py", line 40, in <module>
    class UserListAPIView(ListAPIView):
  File "/Users/xsx/Desktop/xsx/Project/xss/qiyun_admin_usermanage/api/views.py", line 59, in UserListAPIView
    serializer_class = get_serializer_class()
TypeError: get_serializer_class() missing 1 required positional argument: 'self'
</code>```

答:
You can create two serializers and override get_serializer_class in view like this.

```<code>def get_serializer_class(self):
    if self.request.user.is_superuser:
        return FullAccountSerializer
    return BasicAccountSerializer
</code>```

Body:
How to realize with a serializer, when the admin user request, serialize all the fields, but the normal user request, serialize part fields in Rest Framework?

In my serializers:

class UserListSerializer(ModelSerializer):
    """
    user serializer
    """
    account = AccountSerializer(many=False, read_only=True)
    class Meta:
        model = User
        exclude = [
            'password',
        ]
...

class AccountSerializer(ModelSerializer):
    """
    user's accout
    """
    class Meta:
        model = Account
        exclude = [
            'total_charge',
            'total_consume',
        ]

In the views:

 class UserListAPIView(ListAPIView):
    """
    the user view
    """
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)
    serializer_class = UserListSerializer
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['username', 'qq', 'email']
    pagination_class = UserPageNumberPagination

    class Meta:
       ordering = ['-id']

My requirement is that when I use normal user request the APIView, I want to exclude the bellow fields:

'total_charge','total_consume'

If I use the admin user request the APIView, I want to serialize all the fields.

EDIT

I add the get_serializer_class merhod:

class UserListAPIView(ListAPIView):
    """
    返回普通用户列表
    """
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)

    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['username', 'qq', 'email']
    pagination_class = UserPageNumberPagination

    class Meta:
       ordering = ['-id']

    def get_serializer_class(self):
        if self.request.user.is_superuser:
            return UserAdminListSerializer
        else:
            return UserListSerializer

    serializer_class = get_serializer_class()  # if I put this line in the front of `def get_serializer_class(self)` I will get not find error.

when I run the server, it get issue here:

The traceback:

 File "/Users/xsx/Desktop/xsx/Project/xss/qiyun_admin_usermanage/api/views.py", line 40, in <module>
    class UserListAPIView(ListAPIView):
  File "/Users/xsx/Desktop/xsx/Project/xss/qiyun_admin_usermanage/api/views.py", line 59, in UserListAPIView
    serializer_class = get_serializer_class()
TypeError: get_serializer_class() missing 1 required positional argument: 'self'

Body:
You can create two serializers and override get_serializer_class in view like this.

def get_serializer_class(self):
    if self.request.user.is_superuser:
        return FullAccountSerializer
    return BasicAccountSerializer


问:
Parsing command line input for numbers
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

```<code>$ myapp -n 3,4,5,6
</code>```

or

```<code>$ myapp -n 3-6
</code>```

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

```<code>$ myapp -n 22-27, 51-64
</code>```

Title: Parsing command line input for numbers

Body:
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

$ myapp -n 3,4,5,6

or

$ myapp -n 3-6

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

$ myapp -n 22-27, 51-64

Body:
If you have the n-arg in a string you can do:

def f(s):
    if '-' in s:
        i = s.index('-')
        return range(*map(int, s.split('-')))
    return map(int, s.split(','))

Some examples:

In [3]: s = '1, 2, 3, 4, 5, 6'

In [4]: f(s)
Out[4]: [1, 2, 3, 4, 5, 6]

In [5]: f('3-6')
Out[5]: [3, 4, 5]

In [6]: f('3-16-3')
Out[6]: [3, 6, 9, 12, 15]


问:
Adjust layout images and size
I'm trying to adjust the images and size depending the page size to doesn't go outside the grid, but I couldn't make it.

I tried add theses lines below in CSS but it bugged the others images

img{
    width: 100%;
    max-width: 800px;
}
```

The content should adjust the size of the image, but it isn't working

The image going outside the grid:

You can see the live preview here

答:
do the exact opposite you are doing

img {
  width:800px; /* this is optional */
  max-width: 100%;
}
```

OP's comment:

I already dropped it (the width:800px), but it messed with the images at right sidebar.

Then create a class something like img-resposive and for that class apply max-width: 100%. And use that class in images you want/need to

Title: Adjust layout images and size

Body:
I'm trying to adjust the images and size depending the page size to doesn't go outside the grid, but I couldn't make it.

I tried add theses lines below in CSS but it bugged the others images

img{
    width: 100%;
    max-width: 800px;
}

The content should adjust the size of the image, but it isn't working

The image going outside the grid:

You can see the live preview here

Body:
do the exact opposite you are doing

img {
  width:800px; /* this is optional */
  max-width: 100%;
}

OP's comment:

I already dropped it (the width:800px), but it messed with the images at right sidebar.

Then create a class something like img-resposive and for that class apply max-width: 100%. And use that class in images you want/need to