问:
How to use SASS/SCSS with Phoenix framework?
Is there a way to use sass/scss for stylesheets when using Phoenix Framework? And if there is, then how ?</p>

答:
Some answers here suggest to modify brunch-config.js, others package.json. For Phoenix 1.3 compatibility issues are resolved, it is possible to use both npm install and brunch.

Add sass to brunch-config plugins section:

```<code>// brunch-config.js
plugins: {
  sass: {
    mode: "native" // This is the important part!
  }
}
</code>```

Add sass to package.json devDependencies section:

```<code>// package.json
{
  "devDependencies": {
    "sass-brunch": "2.10.4" // check latest version on sass-brunch page
  }
}
</code>```

Then

```<code>cd assets
npm install
</code>```

Body:
Some answers here suggest to modify brunch-config.js, others package.json. For Phoenix 1.3 compatibility issues are resolved, it is possible to use both npm install and brunch.

Add sass to brunch-config plugins section:

// brunch-config.js
plugins: {
  sass: {
    mode: "native" // This is the important part!
  }
}

Add sass to package.json devDependencies section:

// package.json
{
  "devDependencies": {
    "sass-brunch": "2.10.4" // check latest version on sass-brunch page
  }
}

Then

cd assets
npm install


来源: stackexchange

问:
Cannot find module 'internal/fs' after upgrading to node 7
We've recently tried to upgrade to node v7.0.0 on our build server, but started to have issues during the application build task failing on the "bower_concat" step:

```<code>Loading "bower-concat.js" tasks...ERROR
Error: Cannot find module 'internal/fs'
</code>```

What we have installed:

node v7.0.0 (installed via yum "nodesource" repository)

npm 4.0.1

using grunt (if this is relevant)

grunt-bower-concat 0.6.0

The grunt build task configuration:

```<code>grunt.registerTask(
    'build:prod', [
        'clean:prod',
        'copy:prod',
        'replace',
        'bower_concat',
        'ngtemplates',
        'concat',
        'uglify',
        'cssmin',
        'injector:prod',
        'copy:cssfix',
        'copy:dist',
        'bowercopy:dist',
        'bowercopy:fonts',
        'template:setProdVersion'
    ]
);
</code>```

And the grunt bower_concat task:

```<code>bower_concat: {
    all: {
        dest: '<%= app.build %>/bower.js',
        cssDest: '<%= app.build %>/bower.css',
        dependencies: {
            'bootstrap': 'jquery'
        },
        mainFiles: {
            "angular-app-modules": [
                "app/dist/angular-app-modules.min.js",
                "app/dist/angular-app-modules.min.css"
            ]
        }
    }
},
</code>```

Note that it works without any problems on node v6.9.0.

What can be causing the issue? Can we workaround the problem without downgrading to node v6?

There is also this relevant issue, but, as of now, the information there does not help in our case.

答:
On Win10 this worked for me: (adjust to relevant node version and username)

Uninstall node (via node-v7.8.0-x64.msi)

Remove the folders 'npm' and 'npm-cache' in 'C:\Users\yourusername\AppData\Roaming

Install node again (via node-v7.8.0-x64.msi)

ContentLicense: CC BY-SA 3.0

Body:
We've recently tried to upgrade to node v7.0.0 on our build server, but started to have issues during the application build task failing on the "bower_concat" step:

Loading "bower-concat.js" tasks...ERROR
Error: Cannot find module 'internal/fs'

What we have installed:

node v7.0.0 (installed via yum "nodesource" repository)

npm 4.0.1

using grunt (if this is relevant)

grunt-bower-concat 0.6.0

The grunt build task configuration:

grunt.registerTask(
    'build:prod', [
        'clean:prod',
        'copy:prod',
        'replace',
        'bower_concat',
        'ngtemplates',
        'concat',
        'uglify',
        'cssmin',
        'injector:prod',
        'copy:cssfix',
        'copy:dist',
        'bowercopy:dist',
        'bowercopy:fonts',
        'template:setProdVersion'
    ]
);

And the grunt bower_concat task:

bower_concat: {
    all: {
        dest: '<%= app.build %>/bower.js',
        cssDest: '<%= app.build %>/bower.css',
        dependencies: {
            'bootstrap': 'jquery'
        },
        mainFiles: {
            "angular-app-modules": [
                "app/dist/angular-app-modules.min.js",
                "app/dist/angular-app-modules.min.css"
            ]
        }
    }
},

Note that it works without any problems on node v6.9.0.

What can be causing the issue? Can we workaround the problem without downgrading to node v6?

There is also this relevant issue, but, as of now, the information there does not help in our case.


问:
Does laravel not detect request locale automatically?
I am learning laravel 5.4 locale chapter. When I write code to test, I get a question. For example, I have two language directories in my resources/lang directory:

```<code>/resources
    /lang
        /en
            messages.php
        /zh-CN
            messages.php
</code>```

I set default locale is zh-CN, fallback locale is en. When I set Accept-Language to zh-CN, I can get translation string in zh-CN. But when I set Accept-Language to en, I still get string in zh-CN. So laravel does not detect request locale automatically? And If my application want to show english to those Accept-Language is en, and show chinese to those Accept-Language is zh-CN, I need to do it manually, is that correct? I though laravel will detect request locale automatically.

答:
After doing those changes it is always recommended to run these commands:</p>

```<code>php artisan cache:clear
php artisan view:clear
php artisan route:clear
</code>```

Body:
I am learning laravel 5.4 locale chapter. When I write code to test, I get a question. For example, I have two language directories in my resources/lang directory:

/resources
    /lang
        /en
            messages.php
        /zh-CN
            messages.php

I set default locale is zh-CN, fallback locale is en. When I set Accept-Language to zh-CN, I can get translation string in zh-CN. But when I set Accept-Language to en, I still get string in zh-CN. So laravel does not detect request locale automatically? And If my application want to show english to those Accept-Language is en, and show chinese to those Accept-Language is zh-CN, I need to do it manually, is that correct? I though laravel will detect request locale automatically.

Body:
After doing those changes it is always recommended to run these commands:

php artisan cache:clear
php artisan view:clear
php artisan route:clear


问:
Setting and getting values using service angular 2
basically its setting and getting an array.

```<code> import { Injectable } from '@angular/core';

 @Injectable()
 export class Svc {

     constructor() {}

     private _updatedArray: Array < any > = [];
     setColDefs(columns: any) {
         this._updatedArray.push(columns);
         console.log(columns);
     }
     getColDef() {
         return this._updatedArray;
     }
}
</code>```

In one of my componnet i set the array as below:

```<code>...
this._listSvc.setColDefs(colDefArray);
...
</code>```

In my other componnet,

```<code>...
import { Svc } from '../services/mySvc.svc';

@Component({
...
})

export class EditComponent implements OnInit, OnDestroy{

    constructor(
        private _editCompSvc: Svc
    ){}

    ngOnInit() {
        console.log(this._editCompSvc.getColDef());
    }
</code>```

But no idea why the getColDef always giving an empty list. Even in my service the getter function returns an empty list. Any idea guys? Thanks inadvance.

My module:

```<code>import { NgModule } from '@angular/core';
import { routing } from './routes/myroute.route';
import { Svc } from './services/mySvc.svc'

import { ListComponent } from './actions/list.comp';
import { EditComponent } from './actions/edit.comp';

@NgModule({
    imports:
    [
        routing
    ],

    declarations:
    [
        ListComponent,
        EditComponent
    ],

    providers:
    [Svc]
})

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

答:
You're most probably calling that update function after the ngOnInit of EditComponent

```<code>ngOnInit() {  // I'm sure this is happening before that update
   console.log(this._editCompSvc.getColDef());
}
</code>```

And by the way, it's nicer to write this  :

```<code>export class Svc {

constructor() { }

private _updatedArray:Array<any> = [];
   set colDefs(columns: any) {
     this._updatedArray.push(columns);
     console.log('setting the colDefs',columns);
   }
   get colDef(){
        console.log('getting the colDefs',this._updatedArray);
     return this._updatedArray;
   }
</code>```

To prove , run above code, you should see "setting the colDefs" before getting it

Body:
basically its setting and getting an array.

 import { Injectable } from '@angular/core';

 @Injectable()
 export class Svc {

     constructor() {}

     private _updatedArray: Array < any > = [];
     setColDefs(columns: any) {
         this._updatedArray.push(columns);
         console.log(columns);
     }
     getColDef() {
         return this._updatedArray;
     }
}

In one of my componnet i set the array as below:

...
this._listSvc.setColDefs(colDefArray);
...

In my other componnet,

...
import { Svc } from '../services/mySvc.svc';

@Component({
...
})

export class EditComponent implements OnInit, OnDestroy{

    constructor(
        private _editCompSvc: Svc
    ){}

    ngOnInit() {
        console.log(this._editCompSvc.getColDef());
    }

But no idea why the getColDef always giving an empty list. Even in my service the getter function returns an empty list. Any idea guys? Thanks inadvance.

My module:

import { NgModule } from '@angular/core';
import { routing } from './routes/myroute.route';
import { Svc } from './services/mySvc.svc'

import { ListComponent } from './actions/list.comp';
import { EditComponent } from './actions/edit.comp';

@NgModule({
    imports:
    [
        routing
    ],

    declarations:
    [
        ListComponent,
        EditComponent
    ],

    providers:
    [Svc]
})

export class Module { }

Body:
You're most probably calling that update function after the ngOnInit of EditComponent

ngOnInit() {  // I'm sure this is happening before that update
   console.log(this._editCompSvc.getColDef());
}

And by the way, it's nicer to write this  :

export class Svc {

constructor() { }

private _updatedArray:Array<any> = [];
   set colDefs(columns: any) {
     this._updatedArray.push(columns);
     console.log('setting the colDefs',columns);
   }
   get colDef(){
        console.log('getting the colDefs',this._updatedArray);
     return this._updatedArray;
   }

To prove , run above code, you should see "setting the colDefs" before getting it


问:
AMQPlib nodejs consumer task concurrency
I'm building a background task management system with rabbitmq and nodejs using the amqlib module.

Some of the tasks are really CPU-consuming, so if I'm launching a lot of them and I have only a few workers up, my server can get killed (using too much CPU).

I'm wondering if there is a way to create an amqp queue so that my consumers will only consume one task of this queue at a time (i.e. Before an ack or a reject, do not send a task of this kind to this consumer).
Or should I handle this myself in the code (maybe keeping a reference in my worker that I'm handling a task of this queue and rejecting all tasks of this queue while I'm executing the task ?).

Here is my sample code :

I'm creating the amqp connection like that

```<code>const amqpConn = require('amqplib').connect('amqp://localhost');
</code>```

My queue name is tasks :

amqpConn.then((conn) => {
  return conn.createChannel();
}).then((ch) => {
  return ch.assertQueue('tasks').then((ok) => {
    ch.sendToQueue(q, new Buffer(`something to do ${i}`));
  });
}).catch(console.warn);
```

<p>And here is my consumer (I guess this is where I should do the work to limit only one concurrent task of this queue) :</p>

```amqpConn.then((conn) => {
  return conn.createChannel();
}).then((ch) => {
  return ch.assertQueue('tasks').then((ok) => {
    return ch.consume('tasks', (msg) => {
      if (msg !== null) {
        console.log(msg.content.toString());
        ch.ack(msg);
      }
    });
  });
}).catch(console.warn);
```

Thanks a lot !

答:
I'm wondering if there is a way to create an amqp queue so that my consumers will only consume one task of this queue at a time

If this is what you really need then yes, simply have exactly one consumer and declare the queue exclusive. In that way one tasks is consumed at the time.

Body:
I'm building a background task management system with rabbitmq and nodejs using the amqlib module.

Some of the tasks are really CPU-consuming, so if I'm launching a lot of them and I have only a few workers up, my server can get killed (using too much CPU).

I'm wondering if there is a way to create an amqp queue so that my consumers will only consume one task of this queue at a time (i.e. Before an ack or a reject, do not send a task of this kind to this consumer).
Or should I handle this myself in the code (maybe keeping a reference in my worker that I'm handling a task of this queue and rejecting all tasks of this queue while I'm executing the task ?).

Here is my sample code :

I'm creating the amqp connection like that

const amqpConn = require('amqplib').connect('amqp://localhost');

My queue name is tasks :

amqpConn.then((conn) => {
  return conn.createChannel();
}).then((ch) => {
  return ch.assertQueue('tasks').then((ok) => {
    ch.sendToQueue(q, new Buffer(`something to do ${i}`));
  });
}).catch(console.warn);

And here is my consumer (I guess this is where I should do the work to limit only one concurrent task of this queue) :

amqpConn.then((conn) => {
  return conn.createChannel();
}).then((ch) => {
  return ch.assertQueue('tasks').then((ok) => {
    return ch.consume('tasks', (msg) => {
      if (msg !== null) {
        console.log(msg.content.toString());
        ch.ack(msg);
      }
    });
  });
}).catch(console.warn);

Thanks a lot !


问:
Convert sorted array to binary tree in Java
Given a sorted array, convert it into a binary search tree in Java (Leetcode problem)

```<code>   /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            if(nums.length == 0) {return null;}
            TreeNode ans = helper(nums, 0, nums.length);
            return ans;
        }

        public TreeNode helper(int [] nums, int start, int end){
            int mid = start + (end - start)/2;
            if(start == end){
                TreeNode lastNode = new TreeNode(nums[start]);
                lastNode.right = null;
                lastNode.left = null;
                return lastNode;
            }
            int mi = nums[mid];
            TreeNode newNode = new TreeNode(mi);
            TreeNode left = helper(nums, start, mid - 1);
            TreeNode right = helper(nums, mid + 1, end);
            newNode.left = left;
            newNode.right = right;
            return newNode;
        }
    }
</code>```

I get a stackoverflowerror at the line:

```<code>TreeNode left = helper(nums, start, mid - 1);
</code>```

But I don't see why I get the error?

I tried it out with the sample array: [1, 2, 3] and I got the error. Can someone help me out on why this is happening?

答:
That is because the condition (start == end) doesn't happens and recursive still calling

Try to make it (nums.length -1) instead of nums.length

Body:
Given a sorted array, convert it into a binary search tree in Java (Leetcode problem)

   /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            if(nums.length == 0) {return null;}
            TreeNode ans = helper(nums, 0, nums.length);
            return ans;
        }

        public TreeNode helper(int [] nums, int start, int end){
            int mid = start + (end - start)/2;
            if(start == end){
                TreeNode lastNode = new TreeNode(nums[start]);
                lastNode.right = null;
                lastNode.left = null;
                return lastNode;
            }
            int mi = nums[mid];
            TreeNode newNode = new TreeNode(mi);
            TreeNode left = helper(nums, start, mid - 1);
            TreeNode right = helper(nums, mid + 1, end);
            newNode.left = left;
            newNode.right = right;
            return newNode;
        }
    }

I get a stackoverflowerror at the line:

TreeNode left = helper(nums, start, mid - 1);

But I don't see why I get the error?

I tried it out with the sample array: [1, 2, 3] and I got the error. Can someone help me out on why this is happening?


问:
Custom SQL query, for sorting values with "-" as separators
I am trying to create an ORDER BY to sort my values properly.

The values contain a string and anywhere from zero to three sets of numbers separated by a -.

Example:

```<code>dog-2-13
dog-13-54-3
dog-25
cat-63-12
cat
</code>```

I want them to be sorted firstly by the string in front and then by each of the "number sections" so that: dog-2-14 > dog-2-13 but dog-1-14 < dog-2-13.

Expected result (with more examples to make it clearer):

```<code>cat
cat-63-12
dog-2-13
dog-2-14
dog-3
dog-13-53-3
dog-13-54-3
dog-13-54-4
dog-25
</code>```

I'm a SQL novice and completely lost. Thank you!

Body:
I am trying to create an ORDER BY to sort my values properly.

The values contain a string and anywhere from zero to three sets of numbers separated by a -.

Example:

dog-2-13
dog-13-54-3
dog-25
cat-63-12
cat

I want them to be sorted firstly by the string in front and then by each of the "number sections" so that: dog-2-14 > dog-2-13 but dog-1-14 < dog-2-13.

Expected result (with more examples to make it clearer):

cat
cat-63-12
dog-2-13
dog-2-14
dog-3
dog-13-53-3
dog-13-54-3
dog-13-54-4
dog-25

I'm a SQL novice and completely lost. Thank you!

Body:
You can use a Query like this:

SELECT *
FROM yourTable
ORDER BY SUBSTRING_INDEX( SUBSTRING_INDEX(cat,'-',2), '-', -1);

sample

mysql> SELECT SUBSTRING_INDEX('dog-13-54-4','-',2);
+--------------------------------------+
| SUBSTRING_INDEX('dog-13-54-4','-',2) |
+--------------------------------------+
| dog-13                               |
+--------------------------------------+
1 row in set (0,00 sec)

mysql>

mysql> SELECT SUBSTRING_INDEX( SUBSTRING_INDEX( 'dog-13-54-4','-',2), '-', -1);
+------------------------------------------------------------------+
| SUBSTRING_INDEX( SUBSTRING_INDEX( 'dog-13-54-4','-',2), '-', -1) |
+------------------------------------------------------------------+
| 13                                                               |
+------------------------------------------------------------------+
1 row in set (0,00 sec)

mysql>


问:
Javascript reading json file deprecated, updating code
I am reading a json file with javascript using this code:

```<code>var json = $.getJSON({'url': "data.json", 'async': false});
    json = JSON.parse(json.responseText);
    console.log(json);
</code>```

The browser keeps telling me:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

So, I'm guessing I shouldn't be doing this in this way?

What is the better way to do this, javascript or jquery?

答:
Setting the 'async' to false is not recommended. This will block your next statement from execution.

```<code>$.getJSON("data.json", function(response){
    console.log(JSON.parse(response))
})
</code>```

If you still want your code to be synchronous, use $.ajax with async: false. http://api.jquery.com/jQuery.ajax/

Body:
I am reading a json file with javascript using this code:

var json = $.getJSON({'url': "data.json", 'async': false});
    json = JSON.parse(json.responseText);
    console.log(json);

The browser keeps telling me:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

So, I'm guessing I shouldn't be doing this in this way?

What is the better way to do this, javascript or jquery?

Body:
Setting the 'async' to false is not recommended. This will block your next statement from execution.

$.getJSON("data.json", function(response){
    console.log(JSON.parse(response))
})

If you still want your code to be synchronous, use $.ajax with async: false. http://api.jquery.com/jQuery.ajax/


问:
How to create folder which is not readonly
Following code creates readonly folder in the Temp folder.

```<code>System.IO.Directory.CreateDirectory(path:=IO.Path.GetTempPath & "Myfolder")
</code>```

directorySecurity:= part of following code need to repaired

```<code>System.IO.Directory.CreateDirectory(path:=IO.Path.GetTempPath & "Myfolder", directorySecurity:=I need help here)
</code>```

So, how to create folder which is not readonly.

答:
ReadOnly is an attribute, not a security option. Though creating a folder shouldn't make it read-only by default...

To remove the ReadOnly attribute you can create an instance of the DirectoryInfo class and modify its Attributes property. I also strongly recommend that you use Path.Combine() when constructing paths.

```<code>Dim DirPath As String = Path.Combine(Path.GetTempPath(), "Myfolder")
Directory.CreateDirectory(DirPath)

Dim Dir As New DirectoryInfo(DirPath)
Dir.Attributes = Dir.Attributes And Not FileAttributes.ReadOnly 'Bitwise removal.
</code>```

Body:
Following code creates readonly folder in the Temp folder.

System.IO.Directory.CreateDirectory(path:=IO.Path.GetTempPath & "Myfolder")

directorySecurity:= part of following code need to repaired

System.IO.Directory.CreateDirectory(path:=IO.Path.GetTempPath & "Myfolder", directorySecurity:=I need help here)

So, how to create folder which is not readonly.

Body:
ReadOnly is an attribute, not a security option. Though creating a folder shouldn't make it read-only by default...

To remove the ReadOnly attribute you can create an instance of the DirectoryInfo class and modify its Attributes property. I also strongly recommend that you use Path.Combine() when constructing paths.

Dim DirPath As String = Path.Combine(Path.GetTempPath(), "Myfolder")
Directory.CreateDirectory(DirPath)

Dim Dir As New DirectoryInfo(DirPath)
Dir.Attributes = Dir.Attributes And Not FileAttributes.ReadOnly 'Bitwise removal.


问:
Should I use $_GET to dynamically load html?
I am working on a social networking site using PHP, MySQL(PDO), JQuery, and HTML(CSS). I'm working on the profile page right now and I want to determine if the user is on their own page or another's to determine what inputs they'll have. I would like to keep a framework for the profile page and load the respective options rather than having 2 different pages (my profile vs other profile).

I'm learning JQuery and PHP as I go, so right now I am thinking, in JQuery, I can get the $_GET (?username= ) and compare it to the user id of who's logged in, then load the components I need based on that.

Or I determine the user in PHP then run a certain scrip to load the components.

Would on of these ways work, or is there a different/better way to do this?

答:
Simply declare one hidden field on page

```<code><input type="hidden" id="username" value="<?php echo $_GET['username'];?>">
</code>```

Get username value in it.
Then simply fetch that value in jquery

```<code><script>
$(document).ready(function(){
var username = $("#username").val();
if(username == "abc"){
$("#div_one").show();
$("#div_two").hide();
}
});
</script>
</code>```

using if() condition and hide() , show() method load component which you want to show to user.

Body:
Simply declare one hidden field on page

<input type="hidden" id="username" value="<?php echo $_GET['username'];?>">

Get username value in it.
Then simply fetch that value in jquery

<script>
$(document).ready(function(){
var username = $("#username").val();
if(username == "abc"){
$("#div_one").show();
$("#div_two").hide();
}
});
</script>

using if() condition and hide() , show() method load component which you want to show to user.


问:
Setting different text of a textview from an arraylist
I have a textview created programmatically in a loop. On a click of a button i want to fill each textview created with different values from the array how do i achieve this. Here is what happens when the button is clicked. Thanks for the help.

```<code>    btnPnar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            listLayout.removeAllViews();

            for (EditText et : editTextCollection)
            {
                gottenText = et.getText().toString();
                inputList.add(gottenText);
                Collections.shuffle(inputList);
            }
            // Creating alert Dialog with one Button
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,R.style.DialogeTheme);

            // Setting Dialog Title
            alertDialog.setTitle("PNAR");

            // Setting Dialog Message
            alertDialog.setMessage("Enter Amount of Numbers to Pick");
            final EditText input; input = new EditText(MainActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            input.setTextColor(Color.parseColor("#f06292"));
            input.setInputType(2);
            alertDialog.setView(input);
            alertDialog.setPositiveButton("DONE",
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    pnarGotten = Integer.parseInt(input.getText().toString());
                    Collections.shuffle(inputList);

                    for (int n =0; n<pnarGotten; n++) {

                        TextView textView = new TextView(MainActivity.this);
                        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textView.setGravity(Gravity.CENTER);
                        textView.setTextColor(Color.WHITE);
                        textView.setText(inputList.get(0));
                        textView.setText(inputList.get(1));
                        listLayout.addView(textView);

                    }
                }
            });

            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("CANCEL",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Write your code here to execute after dialog
                            dialog.cancel();
                        }
                    });
            // Showing Alert Message
            alertDialog.create();
            alertDialog.show();

        }

    });
</code>```

UPDATE
This is what i added to the code inside the for loop but it shows only one output

```<code>    for (int n =0; n<pnarGotten; n++) {

                        textViewForPnar = new TextView(MainActivity.this);
                        textViewForPnar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textViewForPnar.setGravity(Gravity.CENTER);
                        textViewForPnar.setTextColor(Color.WHITE);
                        while (iterator.hasNext())
                        {
                            textViewForPnar.setText(iterator.next());

                        }
                        listLayout.addView(textViewForPnar);

                    }
</code>```

答:
You should use Iterator object of your inputList collection to retvieve elements from it:

```<code>    Iterator<String> iterator = inputList.iterator();
    while (iterator.hasNext())
    {
        textView.setText(iterator.next());
    }
</code>```

Body:
I have a textview created programmatically in a loop. On a click of a button i want to fill each textview created with different values from the array how do i achieve this. Here is what happens when the button is clicked. Thanks for the help.

    btnPnar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            listLayout.removeAllViews();

            for (EditText et : editTextCollection)
            {
                gottenText = et.getText().toString();
                inputList.add(gottenText);
                Collections.shuffle(inputList);
            }
            // Creating alert Dialog with one Button
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,R.style.DialogeTheme);

            // Setting Dialog Title
            alertDialog.setTitle("PNAR");

            // Setting Dialog Message
            alertDialog.setMessage("Enter Amount of Numbers to Pick");
            final EditText input; input = new EditText(MainActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            input.setTextColor(Color.parseColor("#f06292"));
            input.setInputType(2);
            alertDialog.setView(input);
            alertDialog.setPositiveButton("DONE",
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    pnarGotten = Integer.parseInt(input.getText().toString());
                    Collections.shuffle(inputList);

                    for (int n =0; n<pnarGotten; n++) {

                        TextView textView = new TextView(MainActivity.this);
                        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textView.setGravity(Gravity.CENTER);
                        textView.setTextColor(Color.WHITE);
                        textView.setText(inputList.get(0));
                        textView.setText(inputList.get(1));
                        listLayout.addView(textView);

                    }
                }
            });

            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("CANCEL",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Write your code here to execute after dialog
                            dialog.cancel();
                        }
                    });
            // Showing Alert Message
            alertDialog.create();
            alertDialog.show();

        }

    });

UPDATE
This is what i added to the code inside the for loop but it shows only one output

    for (int n =0; n<pnarGotten; n++) {

                        textViewForPnar = new TextView(MainActivity.this);
                        textViewForPnar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textViewForPnar.setGravity(Gravity.CENTER);
                        textViewForPnar.setTextColor(Color.WHITE);
                        while (iterator.hasNext())
                        {
                            textViewForPnar.setText(iterator.next());

                        }
                        listLayout.addView(textViewForPnar);

                    }

Body:
You should use Iterator object of your inputList collection to retvieve elements from it:

    Iterator<String> iterator = inputList.iterator();
    while (iterator.hasNext())
    {
        textView.setText(iterator.next());
    }


问:
How to change EditText field for various spinner values
I want to change EditText field for each spinner selection, my EditText field should be able to take input in Feet+inch or in Cms based on the input selected by user for unit’s field, i.e. if User selects Metric System then EditText should change into cm format, for FPS system the EditText should change to Feet+inch format, something like following image

I guess I have to use onClickListener on spinner and then have to change EditText, but I don't know how to do that.

答:
Thank you for your time I got what I wanted , I just used a workaround,
I deploeyd three feilds Ft,In and cms; Ft for feet , In for inches and cms for centimeters, In spinner ft+in , and cms are two options, I set the visibility of non selected option as VISIBLE.GONE. </p>


问:
Change The index of a comboBox in windows Application in c#
i have 100 objects of areas which have id and name i want to show name in combobox and their id's as index of combobox but this code is not working</p>

```<code>private void Areadropdown()//show Areadropdown
    {
        List<Area> list = Area.Dropdown();

        foreach (Area a in list)
        {

          metroComboBox1.Items.Insert(a.Id,a.Areaname);
        }
    }
</code>```

答:
```<code> List<Area> list = new  List<Area>();

 metroComboBox1.DisplayMember = "PropertyName" //for you want to display in dropdown so give that class property name
 metroComboBox1.ValueMember = "ProprtyName" // use for take  value of those selection

  metroComboBox1.DataSource = list; //your data list

this code help to solve your problem
</code>```

<p>FYI
Please refereed below example </p>

```<code>  districtComboBox.DisplayMember = "Name";
  districtComboBox.ValueMember = "Id";
  districtComboBox.DataSource = districts.Where(d => d.StateId == (int)stateComboBox.SelectedValue).ToList()
</code>```

Body:
i have 100 objects of areas which have id and name i want to show name in combobox and their id's as index of combobox but this code is not working

private void Areadropdown()//show Areadropdown
    {
        List<Area> list = Area.Dropdown();

        foreach (Area a in list)
        {

          metroComboBox1.Items.Insert(a.Id,a.Areaname);
        }
    }

Body:
 List<Area> list = new  List<Area>();

 metroComboBox1.DisplayMember = "PropertyName" //for you want to display in dropdown so give that class property name
 metroComboBox1.ValueMember = "ProprtyName" // use for take  value of those selection

  metroComboBox1.DataSource = list; //your data list

this code help to solve your problem

FYI
Please refereed below example

  districtComboBox.DisplayMember = "Name";
  districtComboBox.ValueMember = "Id";
  districtComboBox.DataSource = districts.Where(d => d.StateId == (int)stateComboBox.SelectedValue).ToList()


问:
Why does gprof significantly underestimate the program's running time?
I have this program that takes 2.34 seconds to run, and gprof says it only takes 1.18 seconds. I've read answers elsewhere suggesting that gprof can get it wrong if e.g the program is I/O bound, but this program clearly isn't.

This also happens for a useful program I'm trying to profile. It's not specific to this trivial test case.

(Also in this case gprof says that main() takes more than 100% of the program's running time, which is a pretty stupid bug but not really causing problems for me.)

```<code>$ cat test.c
int main() {
    int i;
    for (i=0;i<1000000000;i++);
}

$ gcc test.c -o test

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gcc test.c -o test -pg

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gprof test |head
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
101.33      1.18     1.18                             main

 %         the percentage of the total running time of the
time       program used by this function.
</code>```

答:
First, to answer your question, gprof does not count blocked time, so if anything else is going on in the machine at "the same time" you will see that discrepancy. Also, if your program does any I/O, that will not be counted either.

gprof is really only useful for a very restricted class of programs.
Here is a list of the issues.

ContentLicense: CC BY-SA 2.5

Body:
I have this program that takes 2.34 seconds to run, and gprof says it only takes 1.18 seconds. I've read answers elsewhere suggesting that gprof can get it wrong if e.g the program is I/O bound, but this program clearly isn't.

This also happens for a useful program I'm trying to profile. It's not specific to this trivial test case.

(Also in this case gprof says that main() takes more than 100% of the program's running time, which is a pretty stupid bug but not really causing problems for me.)

$ cat test.c
int main() {
    int i;
    for (i=0;i<1000000000;i++);
}

$ gcc test.c -o test

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gcc test.c -o test -pg

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gprof test |head
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
101.33      1.18     1.18                             main

 %         the percentage of the total running time of the
time       program used by this function.


问:
Populate select option on change odoo 9
How populate select option on change other field. For example:

Default value for select option is store in database tbl_car (Audi, Opel, Mercedes, VW, Bmw). In other table tbl_car_user I store car_name and user_name ('Peter','Audi'). Now I want after change user_id (Select user Peter) in car select option get all car not include Audi (User Peter already use Audi).

Maybe like this:

for car in self.env['tbl.car'].search([]):
    for car_user in self.env['car.user'].search([('user_id','=','self.user_id.id]):
    if (car.name = car_user.name):
       print("DUPLICATE")
    else:
       print("ADD TO SELECT OPTION")
```

Any simple solution?

答:
my first answar is correct now i will give a solution if you don't want to change the selection:

Create a wizard to affect a car to user :

class AffectCar(model.TransientModel):
    _name = 'affect.user.car.wizard'
    use_id = fields.Many2one(..) # you know how you do it
    car_name = fields.Selection(selection='_get_car_selection', 'Car name')

    def _get_car_selection(self):
     """
       generate a selection for field car_name according to
       the default user_id passed to this form
     """
     # get all car name that this user don't have
     # generate the selection [('car_name','car_name')..]
     return computed_selection

   def create_user_car(self):
    """ save a new tbbl_car_user record  """
    # this method is called from the form of the wizard
    # save the user_id and the car_name in tbl_car_user
```

<p>now add a button to the user form and call a method to open the wizard form with user_id by default is the
same user</p>

<pre class="lang-py prettyprint-override"><code>@api.multi()
def add_car(self):
    """
      open the wizard to add a car
      to this user
    """
    return {
        'type': 'ir.actions.act_window',
        'view_mode': 'form',
        'view_type': 'form',
        'res_model':'affect.user.car.wizard',
        'target': 'new',
        'context': {
             # pass the id the the user to the wizard
            'default_use_id': self.id,
        },
        }
</code>```

one thing to prevent the user of you application from changing the user_id when the popup is shown
make the user is in the form view of the wizard invisble="1"

<record id="add_car_wizard" model="ir.ui.view">
    <field name="name">tax.adjustments.wizard.form</field>
    <field name="model">tax.adjustments.wizard</field>
    <field name="arch" type="xml">
    <form>
        <group>
            <field name="user_id" invisible="1"/>
            <field name="car_name"/>
        </group>

            <button name="create_user_car" string="Add car" type="object" class="oe_highlight"/>
            or
            <button string="Cancel" special="cancel" />

    </form>
    </field>
</record>
```

Title: Populate select option on change odoo 9

Body:
How populate select option on change other field. For example:

Default value for select option is store in database tbl_car (Audi, Opel, Mercedes, VW, Bmw). In other table tbl_car_user I store car_name and user_name ('Peter','Audi'). Now I want after change user_id (Select user Peter) in car select option get all car not include Audi (User Peter already use Audi).

Maybe like this:

for car in self.env['tbl.car'].search([]):
    for car_user in self.env['car.user'].search([('user_id','=','self.user_id.id]):
    if (car.name = car_user.name):
       print("DUPLICATE")
    else:
       print("ADD TO SELECT OPTION")

Any simple solution?

Body:
my first answar is correct now i will give a solution if you don't want to change the selection:

Create a wizard to affect a car to user :

class AffectCar(model.TransientModel):
    _name = 'affect.user.car.wizard'
    use_id = fields.Many2one(..) # you know how you do it
    car_name = fields.Selection(selection='_get_car_selection', 'Car name')

    def _get_car_selection(self):
     """
       generate a selection for field car_name according to
       the default user_id passed to this form
     """
     # get all car name that this user don't have
     # generate the selection [('car_name','car_name')..]
     return computed_selection

   def create_user_car(self):
    """ save a new tbbl_car_user record  """
    # this method is called from the form of the wizard
    # save the user_id and the car_name in tbl_car_user

now add a button to the user form and call a method to open the wizard form with user_id by default is the
same user

@api.multi()
def add_car(self):
    """
      open the wizard to add a car
      to this user
    """
    return {
        'type': 'ir.actions.act_window',
        'view_mode': 'form',
        'view_type': 'form',
        'res_model':'affect.user.car.wizard',
        'target': 'new',
        'context': {
             # pass the id the the user to the wizard
            'default_use_id': self.id,
        },
        }

one thing to prevent the user of you application from changing the user_id when the popup is shown
make the user is in the form view of the wizard invisble="1"

<record id="add_car_wizard" model="ir.ui.view">
    <field name="name">tax.adjustments.wizard.form</field>
    <field name="model">tax.adjustments.wizard</field>
    <field name="arch" type="xml">
    <form>
        <group>
            <field name="user_id" invisible="1"/>
            <field name="car_name"/>
        </group>
        <footer>
            <button name="create_user_car" string="Add car" type="object" class="oe_highlight"/>
            or
            <button string="Cancel" special="cancel" />
        </footer>
    </form>
    </field>
</record>


问:
index match value error
When I try to do an index-match lookup with 2 conditions, I always get a #Value! error even though I seem to be doing everything about in the exact same way as every excel tutorial out there.

Need it for a file with over 400'000 rows, so anything manual isn't really an option. Any advice? Thanks a million in advance!

Table 1

X1        X2          Y

Apple   01.05.2010  CHF 10

Apple   30.02.2010  CHF 15

Mango   20.01.2008  CHF 5

Mango   10.12.2011  CHF 4

…   …   …

Table 2

X1        X2          Y

Apple   01.05.2010  #VALUE!

Formula in field Y of Table 2:

```<code>=INDEX(D4:D7;MATCH(H4&I4;B4:B7&C4:C7;0))
</code>```

答:
When you enter more than one range into a MATCH, you need to enter as an array formula i.e. type the formula and press CTRL+SHIFT+ENTER.

You will know if this has worked because Excel will surround the formula with curly brackets {}.

Title: index match value error

Body:
When I try to do an index-match lookup with 2 conditions, I always get a #Value! error even though I seem to be doing everything about in the exact same way as every excel tutorial out there.

Need it for a file with over 400'000 rows, so anything manual isn't really an option. Any advice? Thanks a million in advance!

Table 1

X1        X2          Y

Apple   01.05.2010  CHF 10

Apple   30.02.2010  CHF 15

Mango   20.01.2008  CHF 5

Mango   10.12.2011  CHF 4

…   …   …

Table 2

X1        X2          Y

Apple   01.05.2010  #VALUE!

Formula in field Y of Table 2:

=INDEX(D4:D7;MATCH(H4&I4;B4:B7&C4:C7;0))


问:
Instantiating model in spring rest controller
I just need short explanation of one part of my spring web app that I don't understand exactly.

I have a simple mvc spring web app with StudentController. For data I have a class StudentDataModelStub that implements IStudentDataModel interface witch has some simple functions for working with data stored in the List in StudentDataModelStub class.

In StudentController class I have

@Autowired
private IStudentDataModel model;

When I delete @Autowired annotation I get NullPointerException which is expected, because I don't instantiate StudentDataModelStub. But how does the spring knows which class to instantiate IStudentDataModel with, because multiple classes can implement IStudentDataModel interface, and why model must be @Autowired?

This is one part of the StudentDataModelStub class.

```<code>public class StudentDataModelStub implements IStudentDataModel {

private final Map<Integer, Student> data = new HashMap<>();

@Override
public List<Student> getStudents() {
    // TODO Auto-generated method stub
    return new ArrayList<>(data.values());
}

@Override
public Student getStudent(int id) throws IdNotFoundException {
    // TODO Auto-generated method stub
    if(!data.containsKey(id)){
        throw new IdNotFoundException("...");
    }

    return data.get(id);

}
</code>```

答:
When I delete @Autowired annotation I get NullPointerException which
  is expected, because I don't instantiate StudentDataModelStub. But how
  does the spring knows which class to instantiate IStudentDataModel
  with, because multiple classes can implement IStudentDataModel
  interface?

Spring container scans for the dependencies inside packages specified in @Componentscan (or <context:component-scan> inside xml) and injects them into the beans.

Now regarding which implementation to inject, you can find the below text from Spring doc (also look here) (emphasis mine)

@Primary is an effective way to use autowiring by type with several
  instances when one primary candidate can be determined. When more
  control over the selection process is required, Spring’s @Qualifier
  annotation can be used. You can associate qualifier values with
  specific arguments, narrowing the set of type matches so that a
  specific bean is chosen for each argument.

In short, if multiple implementations are defined for the same interface then you need to tell the container which bean to be injected by specifying @Primary or @Qualifier.

Why model must be @Autowired?

Your StudentDataModelStub class is not actually a Model (Entity) class, it is actually caching the student's data and returning it based upon the id.

Body:
I just need short explanation of one part of my spring web app that I don't understand exactly.

I have a simple mvc spring web app with StudentController. For data I have a class StudentDataModelStub that implements IStudentDataModel interface witch has some simple functions for working with data stored in the List in StudentDataModelStub class.

In StudentController class I have

@Autowired
private IStudentDataModel model;

When I delete @Autowired annotation I get NullPointerException which is expected, because I don't instantiate StudentDataModelStub. But how does the spring knows which class to instantiate IStudentDataModel with, because multiple classes can implement IStudentDataModel interface, and why model must be @Autowired?

This is one part of the StudentDataModelStub class.

public class StudentDataModelStub implements IStudentDataModel {

private final Map<Integer, Student> data = new HashMap<>();

@Override
public List<Student> getStudents() {
    // TODO Auto-generated method stub
    return new ArrayList<>(data.values());
}

@Override
public Student getStudent(int id) throws IdNotFoundException {
    // TODO Auto-generated method stub
    if(!data.containsKey(id)){
        throw new IdNotFoundException("...");
    }

    return data.get(id);

}


问:
Java regular expression to match a alphanumeric string of length greater than one which has atleast one different character
In the below regular expression

```<code>^(?:(?!(\w)\1\b).)*$
</code>```

Does not match string which has last two characters same. For example 1233

What is the issue?

答:
If you want to (not) match the same character, try the following code:

```<code>public static void main (String[] args)
{
    final String SAME_CHAR = "(.)\\1*";
    final List<String> list1 = Arrays.asList("Apple","Aa", "A1a", "AAg");
    final List<String> list2 = Arrays.asList("AAA", "111", "aaaaa", "a");

    for (String str: list1) {
        System.out.println(str + ": " + !str.matches(SAME_CHAR));
    }
    for (String str: list2) {
        System.out.println(str + ": " + !str.matches(SAME_CHAR));
    }
}
</code>```

The resulting output would be:

```<code>Apple: true
Aa: true
A1a: true
AAg: true
AAA: false
111: false
aaaaa: false
a: false
</code>```

Body:
In the below regular expression

^(?:(?!(\w)\1\b).)*$

Does not match string which has last two characters same. For example 1233

What is the issue?

Body:
If you want to (not) match the same character, try the following code:

public static void main (String[] args)
{
    final String SAME_CHAR = "(.)\\1*";
    final List<String> list1 = Arrays.asList("Apple","Aa", "A1a", "AAg");
    final List<String> list2 = Arrays.asList("AAA", "111", "aaaaa", "a");

    for (String str: list1) {
        System.out.println(str + ": " + !str.matches(SAME_CHAR));
    }
    for (String str: list2) {
        System.out.println(str + ": " + !str.matches(SAME_CHAR));
    }
}

The resulting output would be:

Apple: true
Aa: true
A1a: true
AAg: true
AAA: false
111: false
aaaaa: false
a: false


问:
Is is possible to send a link via email or text to an Android device that will open your own custom app with contained parameters?
I can't really add much more to the title. I want to send out alerts to users with links that open up my app directly.

Is this possible, and if so, how?

答:
yes you can do this simply by adding intent to send your data.
i am sharing a code sample just implement it and you will get what you want:

```<code>Intent share = new Intent(android.content.Intent.ACTION_SEND);
        share.setType("text/plain");
        share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        // Add data to the intent, the receiving app will decide
        // what to do with it.

        share.putExtra(Intent.EXTRA_REFERRER_NAME,"example");
        // share.putExtra(Intent.EXTRA_SUBJECT, "your text");

        share.putExtra(Intent.EXTRA_TEXT, "click on com.example.yourApp");

        startActivity(Intent.createChooser(share, ""));
</code>```

Just place your app complete name with package name on place of com.example.yourApp

Body:
yes you can do this simply by adding intent to send your data.
i am sharing a code sample just implement it and you will get what you want:

Intent share = new Intent(android.content.Intent.ACTION_SEND);
        share.setType("text/plain");
        share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        // Add data to the intent, the receiving app will decide
        // what to do with it.

        share.putExtra(Intent.EXTRA_REFERRER_NAME,"example");
        // share.putExtra(Intent.EXTRA_SUBJECT, "your text");

        share.putExtra(Intent.EXTRA_TEXT, "click on com.example.yourApp");

        startActivity(Intent.createChooser(share, ""));

Just place your app complete name with package name on place of com.example.yourApp


问:
TensorFlow: Create a new tensor based on list of indices
I'm learning tensorflow right now, and I have a question that I couldn't find via google. I find it easier to work on a problem and look up documentation as I stumble on issues, so if this is somewhere in the documentation and I haven't applied, I apologize.

I have a tensor. Let's say it's 100 x 1. Let's call it t1. I also have a list of integers, ranging in [0, 99], of size 5000, call it l. I want to transform t1 into a 5000 x 1 tensor, call it t2.

The relationship is as follows: suppose the i^th entry of l is j. Then, I want the i^th entry of t2 to be equal to the j^th entry of t1.

Now, if these were numpy arrays, I would simply do:

```<code>    t2 = t1[l]
</code>```

But I don't think this is an efficient way of doing it in tensorflow, and it doesn't even seem to work anyways.

Suggestions?

答:
What you are looking for is tf.gather:
https://www.tensorflow.org/api_docs/python/tf/gather</p>

```<code>import tensorflow as tf
tf.InteractiveSession()
t1 = tf.random_normal((100, 1))
l = tf.random_uniform((5000, ), minval=0, maxval=99, dtype=tf.int32)
t2 = tf.gather(t1, l)
</code>```

Body:
I'm learning tensorflow right now, and I have a question that I couldn't find via google. I find it easier to work on a problem and look up documentation as I stumble on issues, so if this is somewhere in the documentation and I haven't applied, I apologize.

I have a tensor. Let's say it's 100 x 1. Let's call it t1. I also have a list of integers, ranging in [0, 99], of size 5000, call it l. I want to transform t1 into a 5000 x 1 tensor, call it t2.

The relationship is as follows: suppose the i^th entry of l is j. Then, I want the i^th entry of t2 to be equal to the j^th entry of t1.

Now, if these were numpy arrays, I would simply do:

    t2 = t1[l]

But I don't think this is an efficient way of doing it in tensorflow, and it doesn't even seem to work anyways.

Suggestions?

Body:
What you are looking for is tf.gather:
https://www.tensorflow.org/api_docs/python/tf/gather

import tensorflow as tf
tf.InteractiveSession()
t1 = tf.random_normal((100, 1))
l = tf.random_uniform((5000, ), minval=0, maxval=99, dtype=tf.int32)
t2 = tf.gather(t1, l)


问:
How to uncheck checked items in Navigation View?
I know it's possible to highlight a navigation view item by calling setCheckedItem() or return true value in onNavigationItemSelected to display the item as the selected item, but How can I uncheck the checked items of a navigation view?

答:
To uncheck all MenuItems including SubMenu items you have to use recursion -

```<code>    private void unCheckAllMenuItems(@NonNull final Menu menu) {
        int size = menu.size();
        for (int i = 0; i < size; i++) {
            final MenuItem item = menu.getItem(i);
            if(item.hasSubMenu()) {
                // Un check sub menu items
                unCheckAllMenuItems(item.getSubMenu());
            } else {
                item.setChecked(false);
            }
        }
    }
</code>```

Call above method for unchecking all items, like below -

```<code>unCheckAllMenuItems(navigationView.getMenu());
</code>```

Body:
To uncheck all MenuItems including SubMenu items you have to use recursion -

    private void unCheckAllMenuItems(@NonNull final Menu menu) {
        int size = menu.size();
        for (int i = 0; i < size; i++) {
            final MenuItem item = menu.getItem(i);
            if(item.hasSubMenu()) {
                // Un check sub menu items
                unCheckAllMenuItems(item.getSubMenu());
            } else {
                item.setChecked(false);
            }
        }
    }

Call above method for unchecking all items, like below -

unCheckAllMenuItems(navigationView.getMenu());


问:
Objective-C Programming: Will Learning C and/or Smalltalk Help?
Objective-C is an object-oriented programming language that adds Smalltalk-style messaging to the C programming language. I understand that learning Smalltalk might be good in the same way that learning Lisp is good for one's knowledge, but I want to know if learning Smalltalk-specific concepts will help me to understand Objective-C more completely, given Smalltalk's role in its "origin story". If so, what specifically?

Assuming that one already knows C programming, what can we learn from Smalltalk? Obviously, there's a lot of concepts in Objective-C that just aren't in C (ie. messaging, interfaces, protocols, dynamic typing, delegation, reflection; it's object-oriented!) but are derived from Smalltalk.

Edit: I've added the C programming language to the question, as the general consensus is that learning C is a better use of one's time than learning Smalltalk (when it comes to programming in Objective-C).

答:
Yes, the Objective parts of Objective-C are very similar to Smalltalk.  If you learn Smalltalk first, some of the concepts of Objective-C will be easier and the syntax of sending messages will be less of a shock.  However, I don't think Smalltalk is necessarily any easier to learn than Objective-C, certainly not if you know C already, so you might as well learn Objective-C straight off.

Having said that, Smalltalk is a nice language IMO and worth learning for its own sake.


问:
How to validate whether opened correct activity - Espresso
I created android UI test with espresso and done Button click and opening an Activity. Now I want to validate whether opened correct activity or not.</p>

答:
You want get the instance of activity rule which you have register and compare it with the activity which you want.</p>

```<code>// Define activity rule
    @Rule
        public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>
                MainActivity.class);

    // compare activity rule activity with the activity you want to check.

    Assert.assertEquals(mActivityRule.getActivity(), MainActivity.class);
</code>```

Body:
You want get the instance of activity rule which you have register and compare it with the activity which you want.

// Define activity rule
    @Rule
        public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>
                MainActivity.class);

    // compare activity rule activity with the activity you want to check.

    Assert.assertEquals(mActivityRule.getActivity(), MainActivity.class);


问:
Vulkan and glfw - glfwVulkanSupported() always return false
I'm trying to run a basic Vulkan test using GLFW3.2 :

```<code>#include <vulkan/vulkan.h>
#include <GLFW/glfw3.h>

#include <iostream>

int main(int argc, char *argv[])
{
    if (glfwVulkanSupported())
    {
        std::cout << "vulkan supported !" << std::endl;

    }
    else
    {
        std::cout << "vulkan NOT supported !" << std::endl;

    }
    return 0;
}
</code>```

Which i build using the following cmake :

```<code>cmake_minimum_required(VERSION 3.5.1)
project(vktest)

set (CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_COMPILER "/usr/bin/g++-4.9")

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(Vulkan REQUIRED)
find_package(glfw3 3.2 REQUIRED)
include_directories(${Vulkan_INCLUDE_DIRS})

message("kek")
message(${Vulkan_INCLUDE_DIRS})
message(${Vulkan_LIBRARIES})
message(${Vulkan_LIBRARY})

add_executable(vktest vulkanTest.cpp)

target_link_libraries(vktest ${Vulkan_LIBRARIES})
target_link_libraries(vktest glfw)
</code>```

Building this works just fine.

But when i run the program i always get in the else statement.

I installed nvidia last driver, lunarg's vulkan sdk with the following
environment variables :

```<code>export VULKAN_SDK=/home/mathias/vulkan/VulkanSDK/1.0.42.2/x86_64
set PATH $VULKAN_SDK/bin $PATH
set LD_LIBRARY_PATH $VULKAN_SDK/lib $LD_LIBRARY_PATH
set VK_LAYER_PATH $VULKAN_SDK/etc/explicit_layer.d
</code>```

Besides i can run the cube example.

Any idea of why it never returns true ?

答:
Your code is missing #define GLFW_INCLUDE_VULKAN , does it not?

```<code>#define GLFW_INCLUDE_VULKAN //as required by GLFW
#include "vulkan\vk_cpp.hpp"
#include "GLFW\glfw3.h"
#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    if (!glfwInit()) //Initialize GLFW
    {
        std::cout << "GLFW not initialized.\n";
        abort();
    }
    if (!glfwVulkanSupported()) //Any Vulkan-related function requires GLFW initialized
    {
        std::cout << "Vulkan not supported.\n";
        abort();
    }
    uint32_t ext_count; // an output placeholder
    auto ext_list = glfwGetRequiredInstanceExtensions(&ext_count);

    std::copy(&ext_list[0], &ext_list[ext_count-1], std::ostream_iterator<const char *>(cout, "\n"));

    //feed extension list into InstanceCreateInfo struct in prepare for Vulkan instance creation
    vk::InstanceCreateInfo ifo{ vk::InstanceCreateFlags(), nullptr, 0, nullptr, ext_count, ext_list };
    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // Comment out this if you need OpenGL also
    GLFWwindow* hWnd = glfwCreateWindow(640, 480, "Foobar", NULL, NULL); // The usual window
    auto inst = vk::createInstance(ifo); // Vulkan instance creation
    vk::SurfaceKHR surf{};
    auto psurf = VkSurfaceKHR(surf); // you can cast vk::* object to Vk* using a type cast
    auto r = glfwCreateWindowSurface(VkInstance(inst), hWnd, NULL, &psurf); //VK_SUCCESS is somehow...0
    // Draw stuff here

    // Finish drawing
    vkDestroySurfaceKHR((VkInstance)inst, VkSurfaceKHR(surf), nullptr);//vkcpp seems have no destructor for surface object
    glfwDestroyWindow(hWnd); //Destroy the surface before the window
    glfwTerminate(); // Free GLFW resource
    return 0;
}
</code>```

if there are typos in this code free to fix them. I have no way to compile it at current location

Body:
I'm trying to run a basic Vulkan test using GLFW3.2 :

#include <vulkan/vulkan.h>
#include <GLFW/glfw3.h>

#include <iostream>

int main(int argc, char *argv[])
{
    if (glfwVulkanSupported())
    {
        std::cout << "vulkan supported !" << std::endl;

    }
    else
    {
        std::cout << "vulkan NOT supported !" << std::endl;

    }
    return 0;
}

Which i build using the following cmake :

cmake_minimum_required(VERSION 3.5.1)
project(vktest)

set (CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_COMPILER "/usr/bin/g++-4.9")

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(Vulkan REQUIRED)
find_package(glfw3 3.2 REQUIRED)
include_directories(${Vulkan_INCLUDE_DIRS})

message("kek")
message(${Vulkan_INCLUDE_DIRS})
message(${Vulkan_LIBRARIES})
message(${Vulkan_LIBRARY})

add_executable(vktest vulkanTest.cpp)

target_link_libraries(vktest ${Vulkan_LIBRARIES})
target_link_libraries(vktest glfw)

Building this works just fine.

But when i run the program i always get in the else statement.

I installed nvidia last driver, lunarg's vulkan sdk with the following
environment variables :

export VULKAN_SDK=/home/mathias/vulkan/VulkanSDK/1.0.42.2/x86_64
set PATH $VULKAN_SDK/bin $PATH
set LD_LIBRARY_PATH $VULKAN_SDK/lib $LD_LIBRARY_PATH
set VK_LAYER_PATH $VULKAN_SDK/etc/explicit_layer.d

Besides i can run the cube example.

Any idea of why it never returns true ?

Body:
Your code is missing #define GLFW_INCLUDE_VULKAN , does it not?

#define GLFW_INCLUDE_VULKAN //as required by GLFW
#include "vulkan\vk_cpp.hpp"
#include "GLFW\glfw3.h"
#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    if (!glfwInit()) //Initialize GLFW
    {
        std::cout << "GLFW not initialized.\n";
        abort();
    }
    if (!glfwVulkanSupported()) //Any Vulkan-related function requires GLFW initialized
    {
        std::cout << "Vulkan not supported.\n";
        abort();
    }
    uint32_t ext_count; // an output placeholder
    auto ext_list = glfwGetRequiredInstanceExtensions(&ext_count);

    std::copy(&ext_list[0], &ext_list[ext_count-1], std::ostream_iterator<const char *>(cout, "\n"));

    //feed extension list into InstanceCreateInfo struct in prepare for Vulkan instance creation
    vk::InstanceCreateInfo ifo{ vk::InstanceCreateFlags(), nullptr, 0, nullptr, ext_count, ext_list };
    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // Comment out this if you need OpenGL also
    GLFWwindow* hWnd = glfwCreateWindow(640, 480, "Foobar", NULL, NULL); // The usual window
    auto inst = vk::createInstance(ifo); // Vulkan instance creation
    vk::SurfaceKHR surf{};
    auto psurf = VkSurfaceKHR(surf); // you can cast vk::* object to Vk* using a type cast
    auto r = glfwCreateWindowSurface(VkInstance(inst), hWnd, NULL, &psurf); //VK_SUCCESS is somehow...0
    // Draw stuff here

    // Finish drawing
    vkDestroySurfaceKHR((VkInstance)inst, VkSurfaceKHR(surf), nullptr);//vkcpp seems have no destructor for surface object
    glfwDestroyWindow(hWnd); //Destroy the surface before the window
    glfwTerminate(); // Free GLFW resource
    return 0;
}

if there are typos in this code free to fix them. I have no way to compile it at current location


问:
PHP - magic quotes gpc and stripslashes question
Okay my hosting company has magic_quotes_gpc turned ON and I coded my PHP script using stripslashes() in preparation of this. But now the hosting company says its going to turn magic_quotes_gpc OFF and I was wondering what will happen now to my data now when stripslashes() is present should I go through all my millions of lines of code and get rid of stripslashes()? or leave the stripslashes() function alone? will leaving the stripslashes() ruin my data?

答:
meagar has the correct answer.

But to traverse the situation, you need something like Notepad++ with a Search within files function. Copy a snippet of meagar's code and search for stripslashes()


问:
Pass multiple parameters to event handlers in React
So im trying to make react work with ES6 syntax. In ES5 I had setInitialState without a constructor which worked with the function binding syntax. I have a list of prices which is arbitrary and I want the state to change when the input element is changed. But the right price has to be changed.

I'm not even quite sure this is the right way to do it. Can someone please tell me the most recent way this should be done?

Here is my code:

```<code>import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.css';

export default class PriceTable extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      pid: this.props.pid || "12345",
      name: this.props.name || "name",
      prices: this.props.prices || [
        {count: 1, desc: 'one', price: 8.25},
        {count: 6, desc: 'six', price: 7.60},
        {count: 12, desc: 'twelve', price: 6.953}
      ]
    };

    this.setPid = this.setPid.bind(this);
    this.setName = this.setName.bind(this);
    this.setCount = this.setCount.bind(this, i);
    this.setDesc = this.setDesc.bind(this, i);
    this.setPrice = this.setPrice.bind(this, i);
    this.logDebug = this.logDebug.bind(this);
  }

  setPid(e) {
    this.setState({pid: e.target.value})
  }

  setName(e) {
    this.setState({name: e.target.value})
  }

  setCount(i, e) {
    var newPrices = this.state.prices
    newPrices[i].count = e.target.value
    this.setState({prices: newPrices})
  }

  setDesc(i, e) {
    var newPrices = this.state.prices
    newPrices[i].sec = e.target.value
    this.setState({prices: newPrices})
  }

  setPrice(i, e) {
    var newPrices = this.state.prices
    newPrices[i].price = e.target.value
    this.setState({prices: newPrices})
  }

  _renderPriceRow(price, i) {
    return (
      <tr key={i}>
        <td >
          <input type="text" className="form-control" defaultValue={price.count} onChange={this.setCount(this, i).bind(this, i)}/>
        </td>
        <td >
          <input type="text" className="form-control" defaultValue={price.desc} onChange={this.setDesc(this, i).bind(this, i)}/>
        </td>
        <td >
          <input type="text" className="form-control" defaultValue={price.price} onChange={this.setPrice(this, i).bind(this, i)}/>
        </td>
      </tr>
    );
  }

  render() {
    return (
      <div className="row">
       ...
      </div>
    );
  }
}
</code>```

And this is the error...

```<code>PriceTable.jsx:21 Uncaught ReferenceError: i is not defined
    at new PriceTable (PriceTable.jsx:21)
</code>```

答:
Use the onChange method like this:

```<code>onChange={this.setCount.bind(this, i)}
onChange={this.setDesc.bind(this, i)}
onChange={this.setPrice.bind(this, i)}
</code>```

Remove these lines from constructor:

```<code>this.setCount = this.setCount.bind(this, i);
this.setDesc = this.setDesc.bind(this, i);
this.setPrice = this.setPrice.bind(this, i);
</code>```

We can bind the function in constructor, where no extra parameter is required, like the these functions in your case:

```<code>this.setPid = this.setPid.bind(this);
this.setName = this.setName.bind(this);
this.logDebug = this.logDebug.bind(this);
</code>```

But if in any function you want to pass any extra parameter, then you need to use either arrow function or bind that function by using .bind(this, parameter).

Note:

Another thing that you need to change here is, the way you are updating the state values, You should never mutate state variable directly. When you assign an array to any variable, that variable will have the reference of that array, means whatever changes you will do to that variable will affect the original array.

So you need to create a copy of that variable and then do the changes on that and use setState to update the values.

As per DOC:

Never mutate this.state directly, as calling setState() afterwards may
  replace the mutation you made. Treat this.state as if it were
  immutable.

Body:
So im trying to make react work with ES6 syntax. In ES5 I had setInitialState without a constructor which worked with the function binding syntax. I have a list of prices which is arbitrary and I want the state to change when the input element is changed. But the right price has to be changed.

I'm not even quite sure this is the right way to do it. Can someone please tell me the most recent way this should be done?

Here is my code:

import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.css';

export default class PriceTable extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      pid: this.props.pid || "12345",
      name: this.props.name || "name",
      prices: this.props.prices || [
        {count: 1, desc: 'one', price: 8.25},
        {count: 6, desc: 'six', price: 7.60},
        {count: 12, desc: 'twelve', price: 6.953}
      ]
    };

    this.setPid = this.setPid.bind(this);
    this.setName = this.setName.bind(this);
    this.setCount = this.setCount.bind(this, i);
    this.setDesc = this.setDesc.bind(this, i);
    this.setPrice = this.setPrice.bind(this, i);
    this.logDebug = this.logDebug.bind(this);
  }

  setPid(e) {
    this.setState({pid: e.target.value})
  }

  setName(e) {
    this.setState({name: e.target.value})
  }

  setCount(i, e) {
    var newPrices = this.state.prices
    newPrices[i].count = e.target.value
    this.setState({prices: newPrices})
  }

  setDesc(i, e) {
    var newPrices = this.state.prices
    newPrices[i].sec = e.target.value
    this.setState({prices: newPrices})
  }

  setPrice(i, e) {
    var newPrices = this.state.prices
    newPrices[i].price = e.target.value
    this.setState({prices: newPrices})
  }

  _renderPriceRow(price, i) {
    return (

          <input type="text" className="form-control" defaultValue={price.count} onChange={this.setCount(this, i).bind(this, i)}/>

          <input type="text" className="form-control" defaultValue={price.desc} onChange={this.setDesc(this, i).bind(this, i)}/>

          <input type="text" className="form-control" defaultValue={price.price} onChange={this.setPrice(this, i).bind(this, i)}/>

    );
  }

  render() {
    return (

       ...

    );
  }
}

And this is the error...

PriceTable.jsx:21 Uncaught ReferenceError: i is not defined
    at new PriceTable (PriceTable.jsx:21)

Body:
Use the onChange method like this:

onChange={this.setCount.bind(this, i)}
onChange={this.setDesc.bind(this, i)}
onChange={this.setPrice.bind(this, i)}

Remove these lines from constructor:

this.setCount = this.setCount.bind(this, i);
this.setDesc = this.setDesc.bind(this, i);
this.setPrice = this.setPrice.bind(this, i);

We can bind the function in constructor, where no extra parameter is required, like the these functions in your case:

this.setPid = this.setPid.bind(this);
this.setName = this.setName.bind(this);
this.logDebug = this.logDebug.bind(this);

But if in any function you want to pass any extra parameter, then you need to use either arrow function or bind that function by using .bind(this, parameter).

Note:

Another thing that you need to change here is, the way you are updating the state values, You should never mutate state variable directly. When you assign an array to any variable, that variable will have the reference of that array, means whatever changes you will do to that variable will affect the original array.

So you need to create a copy of that variable and then do the changes on that and use setState to update the values.

As per DOC:

Never mutate this.state directly, as calling setState() afterwards may
  replace the mutation you made. Treat this.state as if it were
  immutable.


问:
Ruby On Rails error during run the project

I have cloned this project from gitlab , I tried to run this in locally but i cant able to run, when I tried to  install bundle, this error is coming that i mentioned in above picture. Please some one help me to run this project, i have installed railsinstaller to run the project... Is there any other tool need to run big project ??

答:
As the error message clearly states you need to install a gem called kgio before doing bundle install.

So do this

```<code>gem install kgio -v 2.11.0
</code>```

Then run bundle install

Body:
As the error message clearly states you need to install a gem called kgio before doing bundle install.

So do this

gem install kgio -v 2.11.0

Then run bundle install


问:
Images rotate automatically
I have a iPhone app that uploads pictures to my server. One major issue I am having is a rotating one.

For some reason if I upload a picture from my iPhone, some pictures will automatically rotate. The one's that do get rotated are the ones in portrait mode. I have no code in my script that rotates the images.

How does a server exactly process tall images? Should I modify my php file to check to rotate it ahead after it automatically rotates? Should I code something in my iPhone app that will check this?

Any help is appreciated!

PS: If you need code, feel free to ask!

答:
Or a better way is to use this library

https://github.com/Intervention/image

And simply use like this-

```<code>$img = Image::make('foo.jpg')->orientate();
</code>```

More can be found here.

Title: Images rotate automatically

Body:
Or a better way is to use this library

https://github.com/Intervention/image

And simply use like this-

$img = Image::make('foo.jpg')->orientate();

More can be found here.


问:
Spring boot: thymeleaf is not rendering fragments correctly
I am creating the spring boot web Application. For templating purpose I am using thymeleaf. I am creating separate html page fragment and I am creating two different layout from these fragments. However, When I connecting the content page I am not getting proper output.

Please check the code snippets/

view resolver

```<code>@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public TemplateResolver templateResolver() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/views/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("html5");
    return templateResolver;
}

@Bean
public SpringTemplateEngine setTemplateEngine() {
    SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
    springTemplateEngine.setTemplateResolver(templateResolver());
    return springTemplateEngine;
}

@Bean
public ViewResolver viewResolver(){
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(setTemplateEngine());
    viewResolver.setOrder(1);
    return viewResolver;
}
</code>```

Directory structure

```<code>src/
  main/
    webapp/
        WEB-INF/
            views/
                fragments/
                         header.html
                         footer.html
                         navBar.html
                layouts/
                         appLayout.html
                         baseLayout.html
                 welcome.html
</code>```

appLayout.html

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
</head>
<body>

<div th:replace="/fragments/header :: header"></div>
<div th:replace="/fragments/navbar :: navbar"></div>
<div class="container">
    <div layout:fragment="content">
    <p>Content goes here...</p>
    </div>
    <footer>
    <div th:replace="/fragments/footer :: footer"></div>
    </footer>
</div>
</body>
</html>
</code>```

Footer fragment footer.html

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
    <div th:fragment="footer">
    Footer
    </div>
</body>
</html>
</code>```

Different fragments are created using this method.

main method class aka startup

```<code>@ComponentScan(basePackages={"xyz.abc"})
@SpringBootApplication
public class AppApplication {

    public static void main(String[] args) {
        System.out.println("Started");
        SpringApplication.run(AppApplication.class, args);
    }
}
</code>```

welcome.html

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layouts/appLayout}">

<head>
</head>

<body>
<th:block layout:fragment="content">
    <div class="hero-unit">
    <h1>My Content</h1>
    </div>
</th:block>
</body>
</html>
</code>```

Now when I access the server, I am getting only welcome.html and nothing from appLayout and fragments

What am I missing?

One more issue I have gone through many projects and some of them are keeping views under src/main/resource and I am keeping it under src/main/web/WEB-INF what is the difference between these two approaches?

答:
Here is a complete example for you.

Gradle Dependency:

```<code>compile('org.springframework.boot:spring-boot-starter-thymeleaf')
</code>```

If you want to use spring-security dialect [optional] add this:

```<code>  compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE")
</code>```

On SpringBoot you dont need view configuration all your views should go to:
src/resources/templates

Does this mean all views under templates dir are public?

No.

Where do I put publicly accessible static files(js & css)?

src/resources/templates/static

How to create Layouts?

In Thymleaf it is easy to handle vertical and horizontal view fragment relationships.

1. Vertical Layout Relationship:

Say you have a master page where you
    include all your common js and css files, side nav, app bar nav
    ..etc. This view will be vertically in herited by almost all of your
    views so in this case you want to somehow embed all your views
    within your master page.  Say you have employee_list page; when the user requests for the employee_list page, the employee_list page will be inserted into your main layout and the user will be seeing employee_list page + master page elements.

Master Page:

On this page all you have to do is add layout:fragment="content". content is the name of the child view fragment that will be embedded in this page.

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      xmlns:sec="http://www.w3.org/1999/xhtml">
<head>

</head>

<body>

    <div id = "page_wrapper">

        <div id="side_menu">
            <!--side menu content-->
        </div>

        <div id="content_wrapper">

            <!--page content-->
            <div layout:fragment="content">

            </div>

        </div>

        <script type="text/javascript" th:inline="javascript">

           //common js here

            /* ]]> */

        </script>

    </div>

</body>

</html>
</code>```

Employee List Page:

To put employee_list page with in the master all you need to do is add layout:decorator="layouts/master" to the html tag of the page. I have put all my layouts under src/resources/templates/layouts dir that why I am using layouts/master instead just saying master. Also pay attention to the layout:fragment="content" attribute; this attribute is indicating whatever is in this view will be embedded on the master page.

```<code> <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org"
          xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
          layout:decorator="layouts/master">

    <body>

        <div id = "content" class = "content layout-list" layout:fragment="content">

            <div>

               <table>

              </table>

            </div>

        </div>

    </body>

    </html>
</code>```

Result:

Horizontal Layout Relationship:

What if you want to include a common view instead of vertically inheriting it like we did on the previous example? Say on the above example you want to include a pagination view on your employee_list page; in this case the relationship becomes horizontal.

Pagination Fragment:

This is a working example btw; the Page class is my own custom class that I created to wrap paginated responses. It is very simple class all I do is I put the response list and pagination info in it.
Fragment name is indicated using th:fragment="pagination"

```<code><div th:if = "${page.totalNumberOfItems > 0 and page.numberOfItems > 0}" class = "pagination-wrapper" th:fragment="pagination" xmlns:th="http://www.thymeleaf.org">

    <div class = "valign-wrapper right">

        <div id = "items_per_page_wrapper">

            <div class="valign-wrapper">

                <span  th:text="#{ui.pagination.rows.per.page.label}" style="padding-right: 10px">Rows per page:</span>

                <select  id="items_per_page_select" name = "itemsPerPage">
                    <option th:each="items_per_page : ${page.ITEMS_PER_PAGE_OPTIONS_LIST}" th:text="${items_per_page}" th:value = "${items_per_page}" th:selected="${items_per_page} == ${page.itemsPerPage}">10</option>
                </select>

            </div>

        </div>

        <label  class="current_page_info"
                th:text="#{ui.pagination.current.page.info(${page.currentPageFirstItemNumber}, ${page.currentPageLastItemNumber}, ${page.totalNumberOfItems})}"></label>

        <ul class="pagination right">

            <li th:classappend="${page.pageNumber > 0 } ? '' : 'disabled'">
                <a id="previous_page_link" href="javascript:void(0)">
                    <i class="material-icons">navigate_before</i>
                </a>
            </li>

            <li th:classappend="${page.currentPageLastItemNumber == page.totalNumberOfItems} ? 'disabled' : ''">
                <a id="next_page_link"  href="javascript:void(0)">
                    <i class="material-icons">navigate_next</i>
                </a>
            </li>
        </ul>

    </div>

</div>
</code>```

Employee List Page:

Add this snippet under the table tag.

```<code>  <div th:replace="common/pagination :: pagination">
        <!--pagination content-->
    </div>
</code>```

Result:

Body:
I am creating the spring boot web Application. For templating purpose I am using thymeleaf. I am creating separate html page fragment and I am creating two different layout from these fragments. However, When I connecting the content page I am not getting proper output.

Please check the code snippets/

view resolver

@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public TemplateResolver templateResolver() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/views/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("html5");
    return templateResolver;
}

@Bean
public SpringTemplateEngine setTemplateEngine() {
    SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
    springTemplateEngine.setTemplateResolver(templateResolver());
    return springTemplateEngine;
}

@Bean
public ViewResolver viewResolver(){
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(setTemplateEngine());
    viewResolver.setOrder(1);
    return viewResolver;
}

Directory structure

src/
  main/
    webapp/
        WEB-INF/
            views/
                fragments/
                         header.html
                         footer.html
                         navBar.html
                layouts/
                         appLayout.html
                         baseLayout.html
                 welcome.html

appLayout.html

<!DOCTYPE html>

Content goes here...

Footer fragment footer.html

<!DOCTYPE html>

    Footer

Different fragments are created using this method.

main method class aka startup

@ComponentScan(basePackages={"xyz.abc"})
@SpringBootApplication
public class AppApplication {

    public static void main(String[] args) {
        System.out.println("Started");
        SpringApplication.run(AppApplication.class, args);
    }
}

welcome.html

<!DOCTYPE html>

My Content

Now when I access the server, I am getting only welcome.html and nothing from appLayout and fragments

What am I missing?

One more issue I have gone through many projects and some of them are keeping views under src/main/resource and I am keeping it under src/main/web/WEB-INF what is the difference between these two approaches?

Body:
Here is a complete example for you.

Gradle Dependency:

compile('org.springframework.boot:spring-boot-starter-thymeleaf')

If you want to use spring-security dialect [optional] add this:

  compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE")

On SpringBoot you dont need view configuration all your views should go to:
src/resources/templates

Does this mean all views under templates dir are public?

No.

Where do I put publicly accessible static files(js & css)?

src/resources/templates/static

How to create Layouts?

In Thymleaf it is easy to handle vertical and horizontal view fragment relationships.

1. Vertical Layout Relationship:

Say you have a master page where you
    include all your common js and css files, side nav, app bar nav
    ..etc. This view will be vertically in herited by almost all of your
    views so in this case you want to somehow embed all your views
    within your master page.  Say you have employee_list page; when the user requests for the employee_list page, the employee_list page will be inserted into your main layout and the user will be seeing employee_list page + master page elements.

Master Page:

On this page all you have to do is add layout:fragment="content". content is the name of the child view fragment that will be embedded in this page.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      xmlns:sec="http://www.w3.org/1999/xhtml">
<head>

</head>

<body>

    <div id = "page_wrapper">

        <div id="side_menu">
            <!--side menu content-->
        </div>

        <div id="content_wrapper">

            <!--page content-->
            <div layout:fragment="content">

            </div>

        </div>

        <script type="text/javascript" th:inline="javascript">

           //common js here

            /* ]]> */

        </script>

    </div>

</body>

</html>

Employee List Page:

To put employee_list page with in the master all you need to do is add layout:decorator="layouts/master" to the html tag of the page. I have put all my layouts under src/resources/templates/layouts dir that why I am using layouts/master instead just saying master. Also pay attention to the layout:fragment="content" attribute; this attribute is indicating whatever is in this view will be embedded on the master page.

 <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org"
          xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
          layout:decorator="layouts/master">

    <body>

        <div id = "content" class = "content layout-list" layout:fragment="content">

            <div>

               <table>

              </table>

            </div>

        </div>

    </body>

    </html>

Result:

Horizontal Layout Relationship:

What if you want to include a common view instead of vertically inheriting it like we did on the previous example? Say on the above example you want to include a pagination view on your employee_list page; in this case the relationship becomes horizontal.

Pagination Fragment:

This is a working example btw; the Page class is my own custom class that I created to wrap paginated responses. It is very simple class all I do is I put the response list and pagination info in it.
Fragment name is indicated using th:fragment="pagination"

<div th:if = "${page.totalNumberOfItems > 0 and page.numberOfItems > 0}" class = "pagination-wrapper" th:fragment="pagination" xmlns:th="http://www.thymeleaf.org">

    <div class = "valign-wrapper right">

        <div id = "items_per_page_wrapper">

            <div class="valign-wrapper">

                <span  th:text="#{ui.pagination.rows.per.page.label}" style="padding-right: 10px">Rows per page:</span>

                <select  id="items_per_page_select" name = "itemsPerPage">
                    <option th:each="items_per_page : ${page.ITEMS_PER_PAGE_OPTIONS_LIST}" th:text="${items_per_page}" th:value = "${items_per_page}" th:selected="${items_per_page} == ${page.itemsPerPage}">10</option>
                </select>

            </div>

        </div>

        <label  class="current_page_info"
                th:text="#{ui.pagination.current.page.info(${page.currentPageFirstItemNumber}, ${page.currentPageLastItemNumber}, ${page.totalNumberOfItems})}"></label>

        <ul class="pagination right">

            <li th:classappend="${page.pageNumber > 0 } ? '' : 'disabled'">
                <a id="previous_page_link" href="javascript:void(0)">
                    <i class="material-icons">navigate_before</i>
                </a>
            </li>

            <li th:classappend="${page.currentPageLastItemNumber == page.totalNumberOfItems} ? 'disabled' : ''">
                <a id="next_page_link"  href="javascript:void(0)">
                    <i class="material-icons">navigate_next</i>
                </a>
            </li>
        </ul>

    </div>

</div>

Employee List Page:

Add this snippet under the table tag.

  <div th:replace="common/pagination :: pagination">
        <!--pagination content-->
    </div>

Result:


问:
Checking if a Python array only includes a set list of numbers
To check user input, I'm trying to see of the input only includes a list of numbers. The input is a 100x100 array with numbers -1,0 and 1. And now I'm trying with an if statement to check if this array only includes the above numbers.

```<code>if np.all(Array) == (-1,0,1):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

I also tried:

```<code>if np.any(Array) == -1 and np.any(Array) == 0 and np.any(Array) == 1:

if np.all(Array) == -1 and 0 and 1:
</code>```

But nothing worked...

答:
Maybe you can try to turn the array to set:

```<code>import numpy as np

x=np.array([[-1,0,-1],[1,1,1]])
if set(x.flatten())=={1,0,-1}:
    print "yes"
</code>```

Or use unique() method to find the unique elements of an array.:

```<code>if set(np.unique(x))=={1,0,-1}:
    print "yes"
</code>```

Body:
To check user input, I'm trying to see of the input only includes a list of numbers. The input is a 100x100 array with numbers -1,0 and 1. And now I'm trying with an if statement to check if this array only includes the above numbers.

if np.all(Array) == (-1,0,1):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I also tried:

if np.any(Array) == -1 and np.any(Array) == 0 and np.any(Array) == 1:

if np.all(Array) == -1 and 0 and 1:

But nothing worked...

Body:
Maybe you can try to turn the array to set:

import numpy as np

x=np.array([[-1,0,-1],[1,1,1]])
if set(x.flatten())=={1,0,-1}:
    print "yes"

Or use unique() method to find the unique elements of an array.:

if set(np.unique(x))=={1,0,-1}:
    print "yes"


问:
Focus li which is in center of page
I am trying to create form like typeForm.
You can find example here https://showroom.typeform.com/to/DYJEHG

I sucessfully implemented design but problem is i want to focus li which comes in vertical center of page.
I tried everything but fails, There is no tutorial on google how we can do this.
Please help.

答:
If i am not wrong, you want the form field to be in the center(horizontally and vertically) and to be full page, right?

Here's a working example of what you might be looking for: http://codepen.io/anon/pen/ZewEMM

In that case,

To focus on one input field per scroll:

Use this small plugin called fullPage.js. This will allow you to have focus on one input field per scroll. It's really easy to use, check it out!
Here an example of your form with fullpage.js:

```<code><form method="post" action="">

  <div id="fullpage">
    <div class="section formfield">
      <div>
        FULL NAME<br/>
        <input type="text">
      </div>
    </div>
    <div class="section formfield">
      <div>
        EMAIL<br/>
        <input type="text">
      </div>
    </div>
    <div class="section formfield">
      <div>
        MESSAGE<br/>
        <input type="text">
      </div>
    </div>
  </div>

</form>
</code>```

Notice that, for ease of use and to avoid confusion, i have not used
.

You can also control the colors of each field section easily via JS:

```<code>$(document).ready(function() {
  $('#fullpage').fullpage({
    sectionsColor: ['#f0f0f0', '#cccccc', '#f0f0f0'], // section colors
    css3: true,
    scrollingSpeed: 1000
  });
});
</code>```

To center the form field vertically and horizontally:

Use Flexbox by wrapping the form field elements inside a div. Here's a sample CSS code:

```<code>.formfield > div {
   display: flex;
   align-items: center;
   justify-content: center;
}
</code>```

Let me know if this helps, and also feel free to ask if you find anything vague in my answer.

Title: Focus li which is in center of page

Body:
If i am not wrong, you want the form field to be in the center(horizontally and vertically) and to be full page, right?

Here's a working example of what you might be looking for: http://codepen.io/anon/pen/ZewEMM

In that case,

To focus on one input field per scroll:

Use this small plugin called fullPage.js. This will allow you to have focus on one input field per scroll. It's really easy to use, check it out!
Here an example of your form with fullpage.js:

<form method="post" action="">

  <div id="fullpage">
    <div class="section formfield">
      <div>
        FULL NAME<br/>
        <input type="text">
      </div>
    </div>
    <div class="section formfield">
      <div>
        EMAIL<br/>
        <input type="text">
      </div>
    </div>
    <div class="section formfield">
      <div>
        MESSAGE<br/>
        <input type="text">
      </div>
    </div>
  </div>

</form>

Notice that, for ease of use and to avoid confusion, i have not used <li>.

You can also control the colors of each field section easily via JS:

$(document).ready(function() {
  $('#fullpage').fullpage({
    sectionsColor: ['#f0f0f0', '#cccccc', '#f0f0f0'], // section colors
    css3: true,
    scrollingSpeed: 1000
  });
});

To center the form field vertically and horizontally:

Use Flexbox by wrapping the form field elements inside a div. Here's a sample CSS code:

.formfield > div {
   display: flex;
   align-items: center;
   justify-content: center;
}

Let me know if this helps, and also feel free to ask if you find anything vague in my answer.


问:
Python: js code not updating in flask
I am refreshing my browser...after running but,

changes are not affected in browser

```<code>from flask import Flask, send_file, render_template, send_file
app = Flask(__name__)

@app.route('/')
def hello_world():
    return send_file('templates/create_conf_view.html')

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True, host='0.0.0.0', port=1672,threaded=True)
</code>```

What i am doing wrong ?

答:
According to your code you need to have a directory structure as follows:

```<code>app
|_
  run.py
  templates/
     |_create_conf_view.html
</code>```

According to docs you should not pass templates when rendering a template.

Change your original file to and see if it works:

```<code>from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('create_conf_view.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=1672, thread=True)
</code>```

Also be sure to access your application at specified port!

Title: Python: js code not updating in flask

Body:
I am refreshing my browser...after running but,

changes are not affected in browser

from flask import Flask, send_file, render_template, send_file
app = Flask(__name__)

@app.route('/')
def hello_world():
    return send_file('templates/create_conf_view.html')

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True, host='0.0.0.0', port=1672,threaded=True)

What i am doing wrong ?

Body:
According to your code you need to have a directory structure as follows:

app
|_
  run.py
  templates/
     |_create_conf_view.html

According to docs you should not pass templates when rendering a template.

Change your original file to and see if it works:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('create_conf_view.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=1672, thread=True)

Also be sure to access your application at specified port!