问:
shared_ptr to an array
How can you dynamically allocate "n number of elements" to which a shared_ptr will point to?

I was able to create a static array that a shared pointer will point to, but I'd like the user to enter a number and then allocate n number of elements.

```<code>shared_ptr<int[10]> p = make_shared<int[10]>();
</code>```

答:
You should create that shared_ptr like that

```<code>std::shared_ptr<int> sp( new int[10], std::default_delete<int[]>() );
</code>```

You must give other deleter to shared_ptr

You can't use std::make_shared, because that function gives only 1 parameter, for create pointer on array you must create deleter too.

Or you can use too (like in comments , with array or with vector, which has own deleter)

```<code>std::shared_ptr<std::array<int,6>> ptr(std::make_shared<std::array<int, 6>>(std::array<int, 6>()));
</code>```

How get particular element?
Like that

```<code>std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());
sp.get()[0] = 5;
std::cout << sp.get()[0] << std::endl;
</code>```

Title: shared_ptr to an array

Body:
How can you dynamically allocate "n number of elements" to which a shared_ptr will point to?

I was able to create a static array that a shared pointer will point to, but I'd like the user to enter a number and then allocate n number of elements.

shared_ptr<int[10]> p = make_shared<int[10]>();

Body:
You should create that shared_ptr like that

std::shared_ptr<int> sp( new int[10], std::default_delete<int[]>() );

You must give other deleter to shared_ptr

You can't use std::make_shared, because that function gives only 1 parameter, for create pointer on array you must create deleter too.

Or you can use too (like in comments , with array or with vector, which has own deleter)

std::shared_ptr<std::array<int,6>> ptr(std::make_shared<std::array<int, 6>>(std::array<int, 6>()));

How get particular element?
Like that

std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());
sp.get()[0] = 5;
std::cout << sp.get()[0] << std::endl;


来源: stackexchange

问:
How to execute something after subscribe in angular
I want to return a boolean value ,but the variable in the "if" condition is undefined. </p>

```<code>function() {
    this.menuDataService.getMenu()
      .subscribe(res => {
       this.mainMenus = res.MainMenus;
       console.log(this.mainMenus);
    });

    console.log(this.mainMenus);

    if(this.mainMenus == 1){
       return true;
    }
    else {
      return false;
    }
}
</code>```

答:
You could have finally event over observable, so that subscription got called.

```<code>this.menuDataService.getMenu()
.finally( () => { console.log(this.mainMenus) });
.subscribe(res =>{
   this.mainMenus = res.MainMenus;
   console.log(this.mainMenus);
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to return a boolean value ,but the variable in the "if" condition is undefined.

function() {
    this.menuDataService.getMenu()
      .subscribe(res => {
       this.mainMenus = res.MainMenus;
       console.log(this.mainMenus);
    });

    console.log(this.mainMenus);

    if(this.mainMenus == 1){
       return true;
    }
    else {
      return false;
    }
}

Body:
You could have finally event over observable, so that subscription got called.

this.menuDataService.getMenu()
.finally( () => { console.log(this.mainMenus) });
.subscribe(res =>{
   this.mainMenus = res.MainMenus;
   console.log(this.mainMenus);
});

ContentLicense: CC BY-SA 3.0


问:
How to fetch all the data from Smartsheet using API?
I am trying to fetch all the rows that are existing in an Smartsheet using API.
I have generated the bearer authorization token and have the report details. My Python is fetching me results of the first 100 rows (source has 1200 rows). I don't use any filters within the Python. Is this due to any default (page-size value)?

I am unable to retrieve all existing data from this API.

答:
I was able to achieve this by using a curl command from SSH and calling it Talend.</p>

```<code>curl -X GET -H 'Authorization: Bearer YOURBEARERTOKENGOESHERE' https://YOURREPORTURL -k -i
</code>```

Body:
I was able to achieve this by using a curl command from SSH and calling it Talend.

curl -X GET -H 'Authorization: Bearer YOURBEARERTOKENGOESHERE' https://YOURREPORTURL -k -i


问:
search data in elastic search based on some fields
I am new to EL and want to search on this data based on "type:": "load".

Please help

```<code>    {
   "took": 14,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1109,
      "max_score": 1,
      "hits": [
         {"_index": "4",
            "_type": "aa",
            "_id": "xx",
            "_score": 1,
            "_source": {
               "useRange": false,
               "Blueprint": 4,
               "standardDeviation": 0,
               "occurrences": 0,
               "type:": "load",
               }...
               {
               }
</code>```

答:
Issue was with field name 'type' we change the name to typemetrics and below query is working
i thing type might be acting as keyword</p>

```<code>" GET /4/_search
{
  "query": {
    "term" : { "typemetrics" : "load"}
  }
} "
</code>```

Body:
I am new to EL and want to search on this data based on "type:": "load".

Please help

    {
   "took": 14,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1109,
      "max_score": 1,
      "hits": [
         {"_index": "4",
            "_type": "aa",
            "_id": "xx",
            "_score": 1,
            "_source": {
               "useRange": false,
               "Blueprint": 4,
               "standardDeviation": 0,
               "occurrences": 0,
               "type:": "load",
               }...
               {
               }

Body:
Issue was with field name 'type' we change the name to typemetrics and below query is working
i thing type might be acting as keyword

" GET /4/_search
{
  "query": {
    "term" : { "typemetrics" : "load"}
  }
} "


问:
Manipulating expressions in AngularJS
I want to be able to achieve a functionality similar to the following:

HTML

```<code><mydir> {{config = {type: 'X', options: 'y'}} </mydir>
<mydir> {{config = {type: 'a', options: 'b'}} </mydir>
</code>```

JS Directive

```<code>angular
  .module('mymod', ['dependency'])
  .controller('myCtrl', function($scope){
     this.config = config;
     this.type = config.type;
     this.options = config.options
  });
  .directive('mydir', function($compile, $window){
     return{
     ... code
     template:
         `<textarea type=this.type options=this.options> </textarea>
     }
  });
</code>```

The goal would be to be able to pass a variety of configurations through, to the controller and let the directive take care of the templating. So that way I can pass whatever combinations of configurations through and the directive should handle it.

Not sure if it's possible to achieve this in Angular since I just got into it but hopefully it isn't too complicated.

答:
If your goal is to pass a configuration parameter to your directive you can do it through the isolated scope of your directive. So that you can pass whatever configuration you like to your directive to handle it.

The following snippet implements this solution.

angular
  .module('mymod', ['dependency'])
  .controller('myCtrl', function($scope) {
    this.config = {
      type: 'a',
      options: 'b'
    };
  })
  .directive('mydir', function($compile, $window) {
    return {
      scope: {
        config: '='
      },
      template: `
        <textarea type="{{ config.type }}" options="{{ config.options }}">
        </textarea>
      `
    }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><mydir config="{type: 'X', options: 'y'}"></mydir>
<mydir config="$ctrl.config"></mydir></code>```

Title: Manipulating expressions in AngularJS

Body:
I want to be able to achieve a functionality similar to the following:

HTML

<mydir> {{config = {type: 'X', options: 'y'}} </mydir>
<mydir> {{config = {type: 'a', options: 'b'}} </mydir>

JS Directive

angular
  .module('mymod', ['dependency'])
  .controller('myCtrl', function($scope){
     this.config = config;
     this.type = config.type;
     this.options = config.options
  });
  .directive('mydir', function($compile, $window){
     return{
     ... code
     template:
         `<textarea type=this.type options=this.options> </textarea>
     }
  });

The goal would be to be able to pass a variety of configurations through, to the controller and let the directive take care of the templating. So that way I can pass whatever combinations of configurations through and the directive should handle it.

Not sure if it's possible to achieve this in Angular since I just got into it but hopefully it isn't too complicated.

Body:
If your goal is to pass a configuration parameter to your directive you can do it through the isolated scope of your directive. So that you can pass whatever configuration you like to your directive to handle it.

The following snippet implements this solution.

angular
  .module('mymod', ['dependency'])
  .controller('myCtrl', function($scope) {
    this.config = {
      type: 'a',
      options: 'b'
    };
  })
  .directive('mydir', function($compile, $window) {
    return {
      scope: {
        config: '='
      },
      template: `
        <textarea type="{{ config.type }}" options="{{ config.options }}">
        </textarea>
      `
    }
  });

<mydir config="{type: 'X', options: 'y'}"></mydir>
<mydir config="$ctrl.config"></mydir>


问:
Not able to "findViewById" in Kotlin. Getting error "Type inference failed"
I am getting the following error when I try to find a RecycleView by id.

Error:-
  Type inference failed: Not enough information to infer parameter T

Code:

```<code>class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}
</code>```

答:
You're on API level 26, where the return type of findViewById is now a generic T instead of View and can therefore be inferred. You can see the relevant changelog here.

So you should be able to do this:

```<code>val recycler_view = findViewById<RecyclerView>(R.id.recycler_view)
</code>```

Or this:

```<code>val recycler_view: RecyclerView = findViewById(R.id.recycler_view)
</code>```

Body:
I am getting the following error when I try to find a RecycleView by id.

Error:-
  Type inference failed: Not enough information to infer parameter T

Code:

class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}

Body:
You're on API level 26, where the return type of findViewById is now a generic T instead of View and can therefore be inferred. You can see the relevant changelog here.

So you should be able to do this:

val recycler_view = findViewById<RecyclerView>(R.id.recycler_view)

Or this:

val recycler_view: RecyclerView = findViewById(R.id.recycler_view)


问:
Joomla - Article not showing up
I have published some articles on Joomla and added theme to module at homepage. But when i click a link, it just show up home page, not article content.

My website here http://vmfederation.com/ and i use template JD Chicago. Example: http://vmfederation.com/23-capabilities/23-why-work-with-us.html

Can anyone help me ?

答:
You have to use the menu link: http://vmfederation.com/services/why-work-with-us.html
Capabilities does not have this item</p>

Title: Joomla - Article not showing up


问:
JavaScript/ AngularJS - perform a function when checkbox is selected
I am working on a site that has been written using AngularJS. On one of the pages, there is a button that opens up a 'Page Properties' dialog, that allows the user to change some of the properties of the page that they are currently viewing.

I want to add a checkbox to that dialog, which, when checked will set the current page as the Home page/ default page for the site (i.e. when the user clicks the site logo, or the 'Home' breadcrumb on any given page, it should then take them to the page on which they checked the 'Set as homepage' checkbox, rather than the default home page.

I have added the checkbox to the dialog, and am now just testing it, to see that I can capture whether or not it has been checked correctly, before I actually write the function to actually set the Home page to the user's choice, rather than the default.

The Angular markup for the dialog box is:

```<code><form class="modal-body" role="form" data-ng-submit="confirm($event)" novalidate>
    ...
    <div data-ng-show="layout.style === 'grid'">
        ...
        <div class="divider"></div>
        <div class="row checkbox">
            <label class="col-sm-2" data-i18n="Homepage:"></label>
            <div class="col-sm-10 checkbox">
                <label class="checkbox">
                    <input name="homepageCheckbox" type="checkbox"
                        ng-click="layout.direction='row'"
                        ng-clicked="layout.direction==='row'">
                    <span data-18n="Set this page as the home page"></span>
                </label>
            </div>
        </div>
    ...
</code>```

This markup displays the checkbox correctly- when I click the button to open the dialog box, I can see that the checkbox I've added is displayed with it's label and text alongside it, & I am able to select/ deselect it.

I am now starting to look into writing the JS required to actually change the home page to the selected page when the checkbox is selected, and thought I would start doing this by simply making sure I am correctly capturing whether or not the checkbox is selected.

To do this, I have located the JS function that is handling the dialog box, and added a few console.log() lines to it, to try and display the value of the checkbox at a given time:

```<code>.controller('PageLayoutPickerCtrl', function($scope, $route, $location, $timeout, Page, umConf, NotifyMgr, DialogMgr) {
    if($scope.homepageCheckbox == 'true'){
        console.log("homepageCheckbox is selected");
    } else {
        console.log("hompageCheckbox is not selected");
    }
    ...
    $scope.confirm = function(e) {
        ...
        if($scope.homepageCheckbox == 'true') {
            console.log("homepageCheckbox is selected inside $scope.confirm() = function()");
        } else {
            console.log("hompageCheckbox is not selected inside $scope.confirm() = function()");
        }
    };
    ...
})
</code>```

So, due to where I've placed the console.log() statements, when the button is clicked to display the dialog, a statement should be shown in the console stating whether or not the checkbox is selected as soon as the dialog opens, and another statement should be shown in the console stating whether or not the checkbox is selected as soon as the 'Confirm' button is pressed on the dialog box.

At the moment, both of these console.log() statements are showing that the checkbox is not selected, regardless of whether I have actually selected it or not.

How can I capture the value of the checkbox correctly, so that when it is selected, and the user clicks the 'Confirm' button, I can change the Home page of the website to the current page?

答:
You should use ng-model in your checkbox like this:

html

```<code>...
<label class="checkbox">
   <input name="homepageCheckbox" type="checkbox"
          ng-model="checkBoxModel"
          ng-click="layout.direction='row'"
          >
    <span data-18n="Set this page as the home page"></span>
</label>
...
</code>```

js

```<code>...
    $scope.confirm = function(e) {
        ...
        if($scope.checkBoxModel) {
            console.log("homepageCheckbox is selected inside $scope.confirm() = function()");
        } else {
            console.log("hompageCheckbox is not selected inside $scope.confirm() = function()");
        }
    };
...
</code>```

Body:
I am working on a site that has been written using AngularJS. On one of the pages, there is a button that opens up a 'Page Properties' dialog, that allows the user to change some of the properties of the page that they are currently viewing.

I want to add a checkbox to that dialog, which, when checked will set the current page as the Home page/ default page for the site (i.e. when the user clicks the site logo, or the 'Home' breadcrumb on any given page, it should then take them to the page on which they checked the 'Set as homepage' checkbox, rather than the default home page.

I have added the checkbox to the dialog, and am now just testing it, to see that I can capture whether or not it has been checked correctly, before I actually write the function to actually set the Home page to the user's choice, rather than the default.

The Angular markup for the dialog box is:

<form class="modal-body" role="form" data-ng-submit="confirm($event)" novalidate>
    ...

        ...

                    <input name="homepageCheckbox" type="checkbox"
                        ng-click="layout.direction='row'"
                        ng-clicked="layout.direction==='row'">

    ...

This markup displays the checkbox correctly- when I click the button to open the dialog box, I can see that the checkbox I've added is displayed with it's label and text alongside it, & I am able to select/ deselect it.

I am now starting to look into writing the JS required to actually change the home page to the selected page when the checkbox is selected, and thought I would start doing this by simply making sure I am correctly capturing whether or not the checkbox is selected.

To do this, I have located the JS function that is handling the dialog box, and added a few console.log() lines to it, to try and display the value of the checkbox at a given time:

.controller('PageLayoutPickerCtrl', function($scope, $route, $location, $timeout, Page, umConf, NotifyMgr, DialogMgr) {
    if($scope.homepageCheckbox == 'true'){
        console.log("homepageCheckbox is selected");
    } else {
        console.log("hompageCheckbox is not selected");
    }
    ...
    $scope.confirm = function(e) {
        ...
        if($scope.homepageCheckbox == 'true') {
            console.log("homepageCheckbox is selected inside $scope.confirm() = function()");
        } else {
            console.log("hompageCheckbox is not selected inside $scope.confirm() = function()");
        }
    };
    ...
})

So, due to where I've placed the console.log() statements, when the button is clicked to display the dialog, a statement should be shown in the console stating whether or not the checkbox is selected as soon as the dialog opens, and another statement should be shown in the console stating whether or not the checkbox is selected as soon as the 'Confirm' button is pressed on the dialog box.

At the moment, both of these console.log() statements are showing that the checkbox is not selected, regardless of whether I have actually selected it or not.

How can I capture the value of the checkbox correctly, so that when it is selected, and the user clicks the 'Confirm' button, I can change the Home page of the website to the current page?

Body:
You should use ng-model in your checkbox like this:

html

...
<label class="checkbox">
   <input name="homepageCheckbox" type="checkbox"
          ng-model="checkBoxModel"
          ng-click="layout.direction='row'"
          >
    <span data-18n="Set this page as the home page"></span>
</label>
...

js

...
    $scope.confirm = function(e) {
        ...
        if($scope.checkBoxModel) {
            console.log("homepageCheckbox is selected inside $scope.confirm() = function()");
        } else {
            console.log("hompageCheckbox is not selected inside $scope.confirm() = function()");
        }
    };
...


问:
Laravel: php artisan serve doesn't start
I've dug through a few of the other answers here and nothing seems to fit the bill. I'm probably going to leave some information out initially so just let me know what else you might need and thanks!

Currently running ubuntu 7, using composer and laravel both of which seem to be installed properly:

When I type 'php artisan serve' and 'php artisan serve --port:8000' into terminal I get this error:

PHP Warning:
  require(/home/user/Projects/thingy/bootstrap/../vendor/autoload.php):
  failed to open stream: No such file or directory in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 PHP
  Fatal error:  require(): Failed opening required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17

When I attempt to run 'php -S localhost:8000 -t public/' just as an attempt I get the following error upon refresh:

PHP 7.0.18-0ubuntu0.17.04.1 Development Server started at Thu Jul  6
  09:15:36 2017 Listening on http://localhost:8000 Document root is
  /home/user/Projects/thingy/public Press Ctrl-C to quit. [Thu Jul  6
  09:15:40 2017] PHP Warning:
  require(/home/user/Projects/thingy/bootstrap/../vendor/autoload.php):
  failed to open stream: No such file or directory in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 [Thu
  Jul  6 09:15:40 2017] PHP Fatal error:  require(): Failed opening
  required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 [Thu
  Jul  6 09:15:40 2017] 127.0.0.1:57214 [500]: / - require(): Failed
  opening required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17

I checked to see if maybe a server was already running using the 'ps -ef | grep php' command in terminal and I don't see any servers running at all.

I have run 'composer install' and I get the following error:

Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Cannot create cache
  directory /home/user/.composer/cache/files/, or directory is not
  writable. Proceeding without cache Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Loading composer
  repositories with package information Installing dependencies
  (including require-dev) from lock file Your requirements could not be
  resolved to an installable set of packages.

Problem 1
      - Installation request for laravel/framework v5.4.28 -> satisfiable by laravel/framework[v5.4.28].
      - laravel/framework v5.4.28 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.

  Problem 2
      - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
      - phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.   Problem 3
      - Installation request for phpunit/phpunit 5.7.21 -> satisfiable by phpunit/phpunit[5.7.21].
      - phpunit/phpunit 5.7.21 requires ext-dom * -> the requested PHP extension dom is missing from your system.   Problem 4
      - laravel/framework v5.4.28 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
      - laravel/tinker v1.0.1 requires illuminate/console ~5.1 -> satisfiable by laravel/framework[v5.4.28].
      - Installation request for laravel/tinker v1.0.1 -> satisfiable by laravel/tinker[v1.0.1].

To enable extensions, verify that they are enabled in your .ini
  files:
      - /etc/php/7.0/cli/php.ini
      - /etc/php/7.0/cli/conf.d/10-opcache.ini
      - /etc/php/7.0/cli/conf.d/10-pdo.ini
      - /etc/php/7.0/cli/conf.d/20-calendar.ini
      - /etc/php/7.0/cli/conf.d/20-ctype.ini
      - /etc/php/7.0/cli/conf.d/20-exif.ini
      - /etc/php/7.0/cli/conf.d/20-fileinfo.ini
      - /etc/php/7.0/cli/conf.d/20-ftp.ini
      - /etc/php/7.0/cli/conf.d/20-gettext.ini
      - /etc/php/7.0/cli/conf.d/20-iconv.ini
      - /etc/php/7.0/cli/conf.d/20-json.ini
      - /etc/php/7.0/cli/conf.d/20-pdo_pgsql.ini
      - /etc/php/7.0/cli/conf.d/20-pgsql.ini
      - /etc/php/7.0/cli/conf.d/20-phar.ini
      - /etc/php/7.0/cli/conf.d/20-posix.ini
      - /etc/php/7.0/cli/conf.d/20-readline.ini
      - /etc/php/7.0/cli/conf.d/20-shmop.ini
      - /etc/php/7.0/cli/conf.d/20-sockets.ini
      - /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
      - /etc/php/7.0/cli/conf.d/20-sysvsem.ini
      - /etc/php/7.0/cli/conf.d/20-sysvshm.ini
      - /etc/php/7.0/cli/conf.d/20-tokenizer.ini
      - /etc/php/7.0/cli/conf.d/20-zip.ini   You can also run php --ini inside terminal to see which files are used by PHP in CLI mode.

When running 'composer dump-autoload' I get the following:

Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Cannot create cache
  directory /home/user/.composer/cache/files/, or directory is not
  writable. Proceeding without cache Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Generating optimized
  autoload files

After following the advice of Nishan Karunarathna and Alex I now get the following error when I run 'php artisan serve':

PHP Fatal error:  Uncaught Error: Class
  'Illuminate\Foundation\Application' not found in
  /home/joshua/Projects/thingy/bootstrap/app.php:14 Stack trace:

0 /home/joshua/Projects/thingy/artisan(18): require_once()

1 {main}   thrown in /home/joshua/Projects/thingy/bootstrap/app.php on line 14

Thanks for any help you give!

答:
You have sort out the errors when encountered when doing composer install.

Install required PHP extensions

```<code>sudo apt-get install php7.0-mbstring

sudo apt-get install php7.0-xml
</code>```

Then restart your nginx and try to run composer install again.

Body:
You have sort out the errors when encountered when doing composer install.

Install required PHP extensions

sudo apt-get install php7.0-mbstring

sudo apt-get install php7.0-xml

Then restart your nginx and try to run composer install again.


问:
Get space between floating divs using JavaScript?
I got an layout using bootstrap with multiple floating divs.

I want to retrieve the space between the divs using JavaScript. Ive only no idea how i can do this. See below picture.

A picture says  a 1000 words ;)

Ive created a fiddle with above layout, i will paste it here so you can play with it if you want.

.page-container {
    background: #ededed;
    padding: 40px 0;
}

.column {
    padding: 15px;
    background-color: white;
    box-shadow: 1px 1px 3px #ccc;
}

[class^="col-"] {
    margin-bottom: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="page-container">
<div class="container">
    <div class="col-md-6 col-sm-6 col-xs-6">
        <div class="column">
            <h2>
        Floating element #1
        </h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
        </p>
        <p>
        Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
        </p>
        </div>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6">
        <div class="column">
            <h2>
        Floating element #2
        </h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
        </p>
        </div>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6">
       <div class="column">
        <h2>
        Floating element #3
        </h2>
        <p>
            Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
        </p>
        <p>
        Fusce a velit et justo porttitor sollicitudin a a velit. Praesent ultrices arcu a sodales ultricies. Etiam cursus mattis dapibus. Fusce vulputate commodo pretium. Suspendisse a orci vitae ipsum interdum dapibus a quis velit. Proin euismod, lectus id euismod semper, tellus nunc luctus dui, consectetur venenatis erat mi eu dolor. Nunc eleifend semper lacus, at hendrerit massa. Praesent ac magna at lacus commodo faucibus eu sit amet magna. Donec pellentesque felis et leo interdum dignissim. Sed sit amet sapien ac quam auctor semper quis ut nibh. Vivamus consectetur, ipsum luctus semper viverra, sem arcu sagittis mauris, a interdum odio sapien in augue.
        </p>
        <p>
        Nam ut bibendum urna, sed congue neque. Nunc a nunc venenatis, porttitor odio vitae, finibus est. Suspendisse quis purus a diam aliquam ullamcorper eu sed dolor. Etiam ac eros eget nisl pretium lobortis. Nulla convallis id nunc eget efficitur. Morbi vel elementum justo. Phasellus et egestas quam. Cras eu tristique urna. Cras ac justo efficitur, consectetur eros et, tincidunt nulla. Quisque et cursus ipsum. Ut tincidunt, purus et tempor fermentum, nulla diam suscipit ex, non sodales eros nunc vel ante. Duis quis justo quam. Sed imperdiet lorem et blandit pretium. Etiam elit dui, tristique et vehicula vitae, venenatis et augue.
        </p>
       </div>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6">
        <div class="column">
        <h2>
        Floating element #4
        </h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
        </p>
        <p>
        Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
        </p>
        </div>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6">
        <div class="column">
        <h2>
        Floating element #4
        </h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
        </p>
        </div>
    </div>
</div>
</div></code>```

Im trying to get those pixel, and move the underlying div up using JavaScript. I know i can use something like masonry. But i can't get those working in my application.

Does anyone have an idea how i can do this? (oh, using jQuery is no problem)

答:
Try one of:

```<code>var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;
</code>```

clientHeight includes the height and vertical padding.

offsetHeight includes the height, vertical padding, and vertical borders.

scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.

with JQuery

```<code>$('#someDiv').height();
$('#someDiv').width();
</code>```

Body:
I got an layout using bootstrap with multiple floating divs.

I want to retrieve the space between the divs using JavaScript. Ive only no idea how i can do this. See below picture.

A picture says  a 1000 words ;)

Ive created a fiddle with above layout, i will paste it here so you can play with it if you want.

.page-container {
    background: #ededed;
    padding: 40px 0;
}

.column {
    padding: 15px;
    background-color: white;
    box-shadow: 1px 1px 3px #ccc;
}

[class^="col-"] {
    margin-bottom: 30px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        Floating element #1

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.

        Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.

        Floating element #2

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.

        Floating element #3

            Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.

        Fusce a velit et justo porttitor sollicitudin a a velit. Praesent ultrices arcu a sodales ultricies. Etiam cursus mattis dapibus. Fusce vulputate commodo pretium. Suspendisse a orci vitae ipsum interdum dapibus a quis velit. Proin euismod, lectus id euismod semper, tellus nunc luctus dui, consectetur venenatis erat mi eu dolor. Nunc eleifend semper lacus, at hendrerit massa. Praesent ac magna at lacus commodo faucibus eu sit amet magna. Donec pellentesque felis et leo interdum dignissim. Sed sit amet sapien ac quam auctor semper quis ut nibh. Vivamus consectetur, ipsum luctus semper viverra, sem arcu sagittis mauris, a interdum odio sapien in augue.

        Nam ut bibendum urna, sed congue neque. Nunc a nunc venenatis, porttitor odio vitae, finibus est. Suspendisse quis purus a diam aliquam ullamcorper eu sed dolor. Etiam ac eros eget nisl pretium lobortis. Nulla convallis id nunc eget efficitur. Morbi vel elementum justo. Phasellus et egestas quam. Cras eu tristique urna. Cras ac justo efficitur, consectetur eros et, tincidunt nulla. Quisque et cursus ipsum. Ut tincidunt, purus et tempor fermentum, nulla diam suscipit ex, non sodales eros nunc vel ante. Duis quis justo quam. Sed imperdiet lorem et blandit pretium. Etiam elit dui, tristique et vehicula vitae, venenatis et augue.

        Floating element #4

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.

        Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.

        Floating element #4

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.

Im trying to get those pixel, and move the underlying div up using JavaScript. I know i can use something like masonry. But i can't get those working in my application.

Does anyone have an idea how i can do this? (oh, using jQuery is no problem)

Body:
Try one of:

var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;

clientHeight includes the height and vertical padding.

offsetHeight includes the height, vertical padding, and vertical borders.

scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.

with JQuery

$('#someDiv').height();
$('#someDiv').width();


答:
The language currently lacks the ability to use make_shared to accomplish that. It is addressed in P0674. Pretty sure it's going to make its way into the language, though it won't be C++11.

The wording will allow you to say

```<code>auto p = std::make_shared<int[10]>()
</code>```

or

```<code>auto p = std::make_shared<int[]>(10)
</code>```

Until C++20 (or whenever the proposal gets officially standardized), you're stuck with using the new syntax as linked in 21koizyd's answer.

Title: shared_ptr to an array

Body:
The language currently lacks the ability to use make_shared to accomplish that. It is addressed in P0674. Pretty sure it's going to make its way into the language, though it won't be C++11.

The wording will allow you to say

auto p = std::make_shared<int[10]>()

or

auto p = std::make_shared<int[]>(10)

Until C++20 (or whenever the proposal gets officially standardized), you're stuck with using the new syntax as linked in 21koizyd's answer.


答:
```<code><input name="homepageCheckbox" type="checkbox" ng-model="homepageCheckbox"
                    ng-click="layout.direction='row'"
                    ng-clicked="layout.direction==='row'">
</code>```

put ng-model="homepageCheckbox" and you are good to go, then in your controller,
check this:

```<code>if($scope.homepageCheckbox){
    console.log("Checkbox is selected");
}
else{
    console.log("Checkbox is not selected");
}
</code>```

Title: JavaScript/ AngularJS - perform a function when checkbox is selected

Body:
<input name="homepageCheckbox" type="checkbox" ng-model="homepageCheckbox"
                    ng-click="layout.direction='row'"
                    ng-clicked="layout.direction==='row'">

put ng-model="homepageCheckbox" and you are good to go, then in your controller,
check this:

if($scope.homepageCheckbox){
    console.log("Checkbox is selected");
}
else{
    console.log("Checkbox is not selected");
}


问:
SHGetFileInfo doesn't return correct handle to icon
I'm using SHGetFileInfo function for getting icons for folders and different file types. According to MSDN call of this function should be done from background thread and before call Component Object Model (COM) must be initialized with CoInitialize or OleInitialize.
My code looks like this:

```<code>    public void SetHlinkImage(string path)
    {
        Shell32.OleInitialize(IntPtr.Zero);
        Task task = Task.Factory.StartNew(() => { LoadIcons(path); });
    }

    private void LoadIcons(string path)
    {
        image = GetHlinkImage(path);

        if (OwnerControl.InvokeRequired)
            layout.ModuleControl.BeginInvoke((MethodInvoker)delegate ()
            {
                Shell32.OleUninitialize();
            });
    }

    public Icon GetHlinkImage(string path)
    {
        uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_ATTRIBUTES | Shell32.SHGFI_SMALLICON;

        Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();

        IntPtr result = Shell32.SHGetFileInfo(path,
                            Shell32.FILE_ATTRIBUTE_DIRECTORY,
                            ref shfi,
                            (uint)Marshal.SizeOf(shfi),
                            flags);

        Icon icon = (Icon)Icon.FromHandle(shfi.hIcon).Clone();
        WinApi.DestroyIcon(shfi.hIcon);     // cleanup

        return icon;
    }
</code>```

Mostly the problem appears after first call of the code and as result I get an exception when I tried to create Icon from icon handle:

System.ArgumentException: Win32 handle that was passed to Icon is not
  valid or is the wrong type

And further calls of the code work without problems.
Actually behaviour also somehow depends on the test system. It is hardly possible to reproduce this issue on Windows10 systems but on Windows 7 it happens quite often.

Has anyone experienced this problem?

答:
From comment of Hans Passant:

Calling OleInitialize() is pointless, the CLR already initializes COM before it starts a thread. And it failed, something you cannot see because you are not checking its return value. Not knowing that, it just spirals into undiagnosable misery from there. Yes, more of it on Win7. You must provide an STA thread, if this needs to run in the background then consider this solution.

Body:
I'm using SHGetFileInfo function for getting icons for folders and different file types. According to MSDN call of this function should be done from background thread and before call Component Object Model (COM) must be initialized with CoInitialize or OleInitialize.
My code looks like this:

    public void SetHlinkImage(string path)
    {
        Shell32.OleInitialize(IntPtr.Zero);
        Task task = Task.Factory.StartNew(() => { LoadIcons(path); });
    }

    private void LoadIcons(string path)
    {
        image = GetHlinkImage(path);

        if (OwnerControl.InvokeRequired)
            layout.ModuleControl.BeginInvoke((MethodInvoker)delegate ()
            {
                Shell32.OleUninitialize();
            });
    }

    public Icon GetHlinkImage(string path)
    {
        uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_ATTRIBUTES | Shell32.SHGFI_SMALLICON;

        Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();

        IntPtr result = Shell32.SHGetFileInfo(path,
                            Shell32.FILE_ATTRIBUTE_DIRECTORY,
                            ref shfi,
                            (uint)Marshal.SizeOf(shfi),
                            flags);

        Icon icon = (Icon)Icon.FromHandle(shfi.hIcon).Clone();
        WinApi.DestroyIcon(shfi.hIcon);     // cleanup

        return icon;
    }

Mostly the problem appears after first call of the code and as result I get an exception when I tried to create Icon from icon handle:

System.ArgumentException: Win32 handle that was passed to Icon is not
  valid or is the wrong type

And further calls of the code work without problems.
Actually behaviour also somehow depends on the test system. It is hardly possible to reproduce this issue on Windows10 systems but on Windows 7 it happens quite often.

Has anyone experienced this problem?


问:
How to revert bcache device to regular device
I have a 20 gb SSD device on my laptop that i decided to try bcache on. It seemed to work, but for some time now, I've been getting an error on boot:

```<code>error on 0f3bbb55-6839-4ed6-8127-7976a969f726: corrupted btree at bucket 17571, block 483, 61 keys, disabling caching
</code>```

I figure I could try and repair this, but I've decided I'm probably better off just disabling bcache - I don't know enough about this to risk losing data/hair if something breaks, and I think I'd be better off using the partition as swap for faster hibernating.

My question is, how do I safely stop using bcache on the device without reformatting the backing device?

I am using /dev/sda7 as my backing device, and /dev/sdb2 as the caching device (/dev/sdb1 is root).

If it matters, I'm running Ubuntu 14.04 with kernel 3.13.0-21-generic.

Update: I am essentially looking for a solution that reverts the changes made by make-bcache -B. FWIW, I ended up "solving" this by moving everything to a new partition and deleting the old (see comment below), but I'll leave this question up in case someone has an actual solution.

答:
I had a time-sensitive issue with this recently and the following text saved my bacon:

D) Recovering data without bcache:

If bcache is not available in the kernel, a filesystem on the backing
  device is still available at an 8KiB offset. So either via a loopdev
  of the backing device created with --offset 8K, or any value defined by
  --data-offset when you originally formatted bcache with make-bcache.

For example:
      losetup -o 8192 /dev/loop0 /dev/your_bcache_backing_dev

From https://www.kernel.org/doc/Documentation/bcache.txt.

This has the added benefit of not modifying the partition table on the  drive, so you can copy some data out and potentially remount it back to its original host.

Body:
I have a 20 gb SSD device on my laptop that i decided to try bcache on. It seemed to work, but for some time now, I've been getting an error on boot:

error on 0f3bbb55-6839-4ed6-8127-7976a969f726: corrupted btree at bucket 17571, block 483, 61 keys, disabling caching

I figure I could try and repair this, but I've decided I'm probably better off just disabling bcache - I don't know enough about this to risk losing data/hair if something breaks, and I think I'd be better off using the partition as swap for faster hibernating.

My question is, how do I safely stop using bcache on the device without reformatting the backing device?

I am using /dev/sda7 as my backing device, and /dev/sdb2 as the caching device (/dev/sdb1 is root).

If it matters, I'm running Ubuntu 14.04 with kernel 3.13.0-21-generic.

Update: I am essentially looking for a solution that reverts the changes made by make-bcache -B. FWIW, I ended up "solving" this by moving everything to a new partition and deleting the old (see comment below), but I'll leave this question up in case someone has an actual solution.


问:
Detect a cutout/semicircle in an image
Below is a binary image in which I would like to detect the "hills", semicircles, cutouts.. In the image below in the red circle. The detection does not have to be precise, I just need to know that something like this is in the picture. I am thinking about the algorithm which would use kind of line sweep approach and count the black pixels on the line and evaluate that with some kind of "cleveristic", but before that I would like to know if I am missing any technique that would be easier or more robust. I have tried the HoughCircles, but with no good results, because the circles have quite huge radius and there is many of them (houghCircles takes grayscale image as input).

答:
As @piglet said, this is a case of blob analysis.

If you want to further characterize and classify the defects, you have to compute some geometrical features of the shapes such as area, diameter, elungation... and feed them to a classifier/neural net.

Title: Detect a cutout/semicircle in an image


问:
CSRF verification failed. Request aborted
I try to build a very simple website where one can add data into sqlite3 database. I have a POST form with two text input.

index.html:

```<code>{% if top_list %}
    <ul>
    <b>```Name    Total steps```</b>
    {% for t in top_list %}
        ```{{t.name}} {{t.total_steps}}```
    {% endfor %}
    </ul>
    {% else %}
    <p>No data available.</p>
{% endif %}
<br>
<form action="/steps_count/" method="post">
    {% csrf_token %}
    Name: <input type="text" name="Name" /><br />
    Steps: <input type="text" name="Steps" /><br />
   <input type="submit" value="Add" />
 </form>
</code>```

forms.py:

```<code>from django import forms
from steps_count.models import Top_List

class Top_List_Form(forms.ModelForm):
    class Meta:
        model=Top_List
</code>```

views.py:

```<code># Create your views here.
from django.template import Context, loader
from django.http import HttpResponse
from steps_count.models import Top_List
from steps_count.forms import Top_List_Form
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response

def index(request):

if request.method == 'POST':
    #form = Top_List_Form(request.POST)
    print "Do something"
else:
    top_list = Top_List.objects.all().order_by('total_steps').reverse()
    t = loader.get_template('steps_count/index.html')
    c = Context({'top_list': top_list,})
    #output = ''.join([(t.name+'\t'+str(t.total_steps)+'\n') for t in top_list])
    return HttpResponse(t.render(c))
</code>```

However, when I click the "submit" button, I get the 403 error:

```<code>CSRF verification failed. Request aborted.
</code>```

I have included {% csrf_token %} in index.html. However, if it is a RequestContext problem, I really have NO idea on where and how to use it. I want everything to happen on the same page (index.html).

答:
You may have missed adding the following to your form:</p>

```<code>{% csrf_token %}
</code>```

Body:
I try to build a very simple website where one can add data into sqlite3 database. I have a POST form with two text input.

index.html:

{% if top_list %}

Name    Total steps

    {% for t in top_list %}

{{t.name}} {{t.total_steps}}

    {% endfor %}

    {% else %}

No data available.

{% endif %}

<form action="/steps_count/" method="post">
    {% csrf_token %}
    Name: <input type="text" name="Name" />

    Steps: <input type="text" name="Steps" />

   <input type="submit" value="Add" />
 </form>

forms.py:

from django import forms
from steps_count.models import Top_List

class Top_List_Form(forms.ModelForm):
    class Meta:
        model=Top_List

views.py:

# Create your views here.
from django.template import Context, loader
from django.http import HttpResponse
from steps_count.models import Top_List
from steps_count.forms import Top_List_Form
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response

def index(request):

if request.method == 'POST':
    #form = Top_List_Form(request.POST)
    print "Do something"
else:
    top_list = Top_List.objects.all().order_by('total_steps').reverse()
    t = loader.get_template('steps_count/index.html')
    c = Context({'top_list': top_list,})
    #output = ''.join([(t.name+'\t'+str(t.total_steps)+'\n') for t in top_list])
    return HttpResponse(t.render(c))

However, when I click the "submit" button, I get the 403 error:

CSRF verification failed. Request aborted.

I have included {% csrf_token %} in index.html. However, if it is a RequestContext problem, I really have NO idea on where and how to use it. I want everything to happen on the same page (index.html).

Body:
You may have missed adding the following to your form:

{% csrf_token %}


问:
Java algorithms
I am a server side Java programmer. In my recent job search, I have come across a few postings where they mention : ' Candidates with expereince in algorithm development will be preferred'. What exactly does this refer to? This is the posting for a Bank...so not a job for a research laboratory...just to clarify a bit.

I asked my headhunter ...he does not have an idea about this.

When we use Java in applications, we use the APIs that implement algorithms...so technically we are not developing algorithms. Right?

答:
"Algorithm development" sounds vague. Maybe the original technical requirement was knowledge of algorithms, and somewhere along the way, someone thought it didn't sound impressive enough, and rewrote it to "candidates with experience in algorithm development will be preferred".

I don't think it means "the ability to create new algorithms from scratch". Rather, you need to be able to recognize when a program could benefit from the use of some known algorithm or data structure, or a slight modification of one, and the ability to get that done. This is a crucial skill on many projects, and especially those where speed is important.

The generic algorithms provided by the Java class library (like Arrays.sort) make up a small fraction of what you might find in even an introductory algorithms textbook. (I'm not a Java hacker by trade, but is there even a heap sort?)

ContentLicense: CC BY-SA 2.5

Title: Java algorithms


问:
What is the best way to show a WPF window at the mouse location (to the top left of the mouse)?
I have found that this works PART of the time by inheriting the Windows Forms mouse point and subtracting out the height and width of my window to set the left and top (since my window's size is fixed):

```<code>MyWindowObjectThatInheritsWindow window = new MyWindowObjectThatInheritsWindow();
System.Windows.Point mouseLocation = GetMousePositionWindowsForms();
window.Left = mouseLocation.X - 300;
window.Top = mouseLocation.Y - 240;
window.Show();
</code>```

Edit: Here is the code for getting the mouse position...

```<code>public System.Windows.Point GetMousePositionWindowsForms()
{
    System.Drawing.Point point = System.Windows.Forms.Control.MousePosition;
    return new System.Windows.Point(point.X, point.Y);
}
</code>```

Note that this works by making the bottom right edge of the window touch the top left of your mouse cursor. But this breaks for different screen resolutions, or maybe multiple monitors with different resolutiosn? I haven't fully narrowed it down yet, but I just tried this same code on another PC, and it seems to spawn the window not to the top left of the mouse cursor, but to the bottom left of it, and a good distance past it...

I should probably add that my window sizes to content, width and height, so I can't just use the ActualWidth and ActualHeight properties since they're not available. Perhaps the issue is in getting that sizing right? Is there any way to do that? I know for sure the 300 and 240 is correct according to my main PC with two monitors running 1920x1080 resolutions, as I have calculated the widths and heights of all the objects in my window which I have explicitly sized. Edit: Just tried explicitly setting the height and width to 240/300, to ensure that the window is no longer sized to content, and I still have this issue when subtracting out the actual height and width!

Any ideas?

答:
You can also do this by slightly modifying your initial example and positioning the window before showing it.</p>

```<code>MyWindowObjectThatInheritsWindow window = new MyWindowObjectThatInheritsWindow();

var helper = new WindowInteropHelper(window);
var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle());
var transformFromDevice = hwndSource.CompositionTarget.TransformFromDevice;

System.Windows.Point wpfMouseLocation = transformFromDevice.Transform(GetMousePositionWindowsForms());
window.Left = wpfMouseLocation.X - 300;
window.Top = wpfMouseLocation.Y - 240;
window.Show();
</code>```

Body:
I have found that this works PART of the time by inheriting the Windows Forms mouse point and subtracting out the height and width of my window to set the left and top (since my window's size is fixed):

MyWindowObjectThatInheritsWindow window = new MyWindowObjectThatInheritsWindow();
System.Windows.Point mouseLocation = GetMousePositionWindowsForms();
window.Left = mouseLocation.X - 300;
window.Top = mouseLocation.Y - 240;
window.Show();

Edit: Here is the code for getting the mouse position...

public System.Windows.Point GetMousePositionWindowsForms()
{
    System.Drawing.Point point = System.Windows.Forms.Control.MousePosition;
    return new System.Windows.Point(point.X, point.Y);
}

Note that this works by making the bottom right edge of the window touch the top left of your mouse cursor. But this breaks for different screen resolutions, or maybe multiple monitors with different resolutiosn? I haven't fully narrowed it down yet, but I just tried this same code on another PC, and it seems to spawn the window not to the top left of the mouse cursor, but to the bottom left of it, and a good distance past it...

I should probably add that my window sizes to content, width and height, so I can't just use the ActualWidth and ActualHeight properties since they're not available. Perhaps the issue is in getting that sizing right? Is there any way to do that? I know for sure the 300 and 240 is correct according to my main PC with two monitors running 1920x1080 resolutions, as I have calculated the widths and heights of all the objects in my window which I have explicitly sized. Edit: Just tried explicitly setting the height and width to 240/300, to ensure that the window is no longer sized to content, and I still have this issue when subtracting out the actual height and width!

Any ideas?

Body:
You can also do this by slightly modifying your initial example and positioning the window before showing it.

MyWindowObjectThatInheritsWindow window = new MyWindowObjectThatInheritsWindow();

var helper = new WindowInteropHelper(window);
var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle());
var transformFromDevice = hwndSource.CompositionTarget.TransformFromDevice;

System.Windows.Point wpfMouseLocation = transformFromDevice.Transform(GetMousePositionWindowsForms());
window.Left = wpfMouseLocation.X - 300;
window.Top = wpfMouseLocation.Y - 240;
window.Show();


问:
How to load modifications made in native java classes?
Hi,

I'm trying to execute a jar file, overwriting some java originals interfaces to connect with the database, changing the method setBoolean to receive an object like parameter.

That's the original interface method:

```<code>void setBoolean(int parameterIndex, boolean x) throws SQLException;
</code>```

That's my change:

```<code>void setBoolean(int parameterIndex, Boolean x) throws SQLException;
</code>```

My changes were made at interface java.sql.PreparedStatement. For my changes to be called, when I start the application I'm using the command:

```<code>java -verbose:class -Xbootclasspath/p:C:/Users/user/Desktop/myproject/src/main/java -jar safepdv.jar
</code>```

With the command "-verbose:class" I can verify that the class with my changes are being loaded.

However, when the method setBoolean is called by the application, he isn't founded, and my return is:

```<code>Exception in thread "AWT-EventQueue-0" [Loaded java.lang.Throwable$WrappedPrintStream from C:\Program Files\Java\jre1.8.0_91\lib\rt.jar]
java.lang.NoSuchMethodError: java.sql.PreparedStatement.setBoolean(IZ)V
    at com.t2tierp.pafecf.controller.ConfigurationController.updateCS(ConfigurationController.java:613)
    at com.t2tierp.pafecf.view.OpenMoviment.validaCamposLogin(OpenMoviment.java:448)
    at com.t2tierp.pafecf.view.OpenMoviment.passwordTextSenhaUsuarioActionPerformed(OpenMoviment.java:403)
    at com.t2tierp.pafecf.view.OpenMoviment.access$200(OpenMoviment.java:22)
    at com.t2tierp.pafecf.view.OpenMoviment$4.actionPerformed(OpenMoviment.java:240)
    at javax.swing.JTextField.fireActionPerformed(Unknown Source)
    at javax.swing.JTextField.postActionEvent(Unknown Source)
    at javax.swing.JTextField$NotifyAction.actionPerformed(Unknown Source)
    at javax.swing.SwingUtilities.notifyAction(Unknown Source)
    at javax.swing.JComponent.processKeyBinding(Unknown Source)
    at javax.swing.JComponent.processKeyBindings(Unknown Source)
    at javax.swing.JComponent.processKeyEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.WaitDispatchSupport$2.run(Unknown Source)
    at java.awt.WaitDispatchSupport$4.run(Unknown Source)
    at java.awt.WaitDispatchSupport$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(Unknown Source)
    at java.awt.Dialog.show(Unknown Source)
    at java.awt.Component.show(Unknown Source)
    at java.awt.Component.setVisible(Unknown Source)
    at java.awt.Window.setVisible(Unknown Source)
    at java.awt.Dialog.setVisible(Unknown Source)
    at com.t2tierp.pafecf.view.Caixa.verificarMovimentoExistente(Caixa.java:3392)
    at com.t2tierp.pafecf.view.Caixa.<init>(Caixa.java:344)
    at com.t2tierp.pafecf.view.Caixa$41.run(Caixa.java:2393)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
</code>```

How can I make my method was really called instead of the original method?

答:
The calling code is still trying to pass a null value to the old method's signature (which expects a boolean, and not a Boolean). You would need to recompile the calling code so that it binds to the new method signature: the method signatures to be called are fixed at compile-time.

Also, note that PreparedStatement is an interface - changing its definition is likely to break all classes implementing said interface. Most notably, each JDBC driver will include its own implementation; you would have to recompile the drivers from source to fix this.

It is possible, but ugly and unmaintainable, to decompile the calling code and simply fix it at the point where the null is being passed, and then recompile it. You can automate this to a certain point (think bytecode-editing libraries), but the gist is that not having access to the source code making the bad calls is a severe drawback.

Body:
Hi,

I'm trying to execute a jar file, overwriting some java originals interfaces to connect with the database, changing the method setBoolean to receive an object like parameter.

That's the original interface method:

void setBoolean(int parameterIndex, boolean x) throws SQLException;

That's my change:

void setBoolean(int parameterIndex, Boolean x) throws SQLException;

My changes were made at interface java.sql.PreparedStatement. For my changes to be called, when I start the application I'm using the command:

java -verbose:class -Xbootclasspath/p:C:/Users/user/Desktop/myproject/src/main/java -jar safepdv.jar

With the command "-verbose:class" I can verify that the class with my changes are being loaded.

However, when the method setBoolean is called by the application, he isn't founded, and my return is:

Exception in thread "AWT-EventQueue-0" [Loaded java.lang.Throwable$WrappedPrintStream from C:\Program Files\Java\jre1.8.0_91\lib\rt.jar]
java.lang.NoSuchMethodError: java.sql.PreparedStatement.setBoolean(IZ)V
    at com.t2tierp.pafecf.controller.ConfigurationController.updateCS(ConfigurationController.java:613)
    at com.t2tierp.pafecf.view.OpenMoviment.validaCamposLogin(OpenMoviment.java:448)
    at com.t2tierp.pafecf.view.OpenMoviment.passwordTextSenhaUsuarioActionPerformed(OpenMoviment.java:403)
    at com.t2tierp.pafecf.view.OpenMoviment.access$200(OpenMoviment.java:22)
    at com.t2tierp.pafecf.view.OpenMoviment$4.actionPerformed(OpenMoviment.java:240)
    at javax.swing.JTextField.fireActionPerformed(Unknown Source)
    at javax.swing.JTextField.postActionEvent(Unknown Source)
    at javax.swing.JTextField$NotifyAction.actionPerformed(Unknown Source)
    at javax.swing.SwingUtilities.notifyAction(Unknown Source)
    at javax.swing.JComponent.processKeyBinding(Unknown Source)
    at javax.swing.JComponent.processKeyBindings(Unknown Source)
    at javax.swing.JComponent.processKeyEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.WaitDispatchSupport$2.run(Unknown Source)
    at java.awt.WaitDispatchSupport$4.run(Unknown Source)
    at java.awt.WaitDispatchSupport$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(Unknown Source)
    at java.awt.Dialog.show(Unknown Source)
    at java.awt.Component.show(Unknown Source)
    at java.awt.Component.setVisible(Unknown Source)
    at java.awt.Window.setVisible(Unknown Source)
    at java.awt.Dialog.setVisible(Unknown Source)
    at com.t2tierp.pafecf.view.Caixa.verificarMovimentoExistente(Caixa.java:3392)
    at com.t2tierp.pafecf.view.Caixa.<init>(Caixa.java:344)
    at com.t2tierp.pafecf.view.Caixa$41.run(Caixa.java:2393)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

How can I make my method was really called instead of the original method?


答:
Try this:

Here bind generic function use to bind view. its general function it's can use for any view.

```<code>class MyActivity : AppCompatActivity() {
    private lateinit var recycler_view : RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        recycler_view = bind(R.id.recycler_view)
    }
}

fun <T : View> Activity.bind(@IdRes res : Int) : T {
    @Suppress("UNCHECKED_CAST")
    return findViewById(res) as T
}
</code>```

Title: Not able to "findViewById" in Kotlin. Getting error "Type inference failed"

Body:
Try this:

Here bind generic function use to bind view. its general function it's can use for any view.

class MyActivity : AppCompatActivity() {
    private lateinit var recycler_view : RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        recycler_view = bind(R.id.recycler_view)
    }
}

fun <T : View> Activity.bind(@IdRes res : Int) : T {
    @Suppress("UNCHECKED_CAST")
    return findViewById(res) as T
}


问:
Adding content to wordpress page
So, i finally got my css and js scripts to load on WP

Now there is but one thing i need to get done.

i have my own theme, including header.php, footer.php, page.php

header.php and footer.php is working just fine, loading scripts and showing properly, but now i need to add all the other content.

my page.php is currently:

```<code><?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php the_content(); ?>

<?php get_footer(); ?>
</code>```

I would need to somehow add html content to pages, i have about 20 ready made .php pages which needs to be transfered to WP.

Soooo how do i go about making new page (pages -> add new) and using page template while getting the html content to show up?

I've tried to just make new page and in text mode add up all the html into page, but it only shows empty page with header and footer, so the problem is most likely the page.php and i have no idea how to get it to work.

答:
You can do look like this:</p>

```<code><?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php
    while ( have_posts() ) : the_post();
        the_content();
    endwhile;
?>
<?php get_footer(); ?>
</code>```

Title: Adding content to wordpress page

Body:
So, i finally got my css and js scripts to load on WP

Now there is but one thing i need to get done.

i have my own theme, including header.php, footer.php, page.php

header.php and footer.php is working just fine, loading scripts and showing properly, but now i need to add all the other content.

my page.php is currently:

<?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php the_content(); ?>

<?php get_footer(); ?>

I would need to somehow add html content to pages, i have about 20 ready made .php pages which needs to be transfered to WP.

Soooo how do i go about making new page (pages -> add new) and using page template while getting the html content to show up?

I've tried to just make new page and in text mode add up all the html into page, but it only shows empty page with header and footer, so the problem is most likely the page.php and i have no idea how to get it to work.

Body:
You can do look like this:

<?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php
    while ( have_posts() ) : the_post();
        the_content();
    endwhile;
?>
<?php get_footer(); ?>


问:
WP7 dynamic controls
Is it possible to generate dynamic WP7 controls in code behind (.cs)  using  .xaml template (like inflating in Android) ,
 or should I generate it all manually? For example I need dynamic tabs (PivotItems)</p>

答:
Pete Brown recently demonstrated how to dynamically generate xaml here if you'd like to look into that route.

Dynamically Generating Controls in WPF and Silverlight

Title: WP7 dynamic controls


问:
Is it possible to predefine the avaible values of a functions's parameter?
I would like to set the avaible values of a functions parameter something like this:

```<code>let valueList = [
   'val1',
   'val2',
   'val3',
];

let getSomething = (parameter: valueList) => {
    // do something
}
</code>```

And i want to get error on console if parameter value other than what are in the valueList variable.

And it would be good, if IDE showup the possible values when I call the function as follow:

```<code>getSomething(| <- cursor ) // when cursor here, the IDE show the possible values from valueList
</code>```

答:
Use enum for this:</p>

```<code>enum ValueList {
   val1,
   val2,
   val3
}
</code>```

Body:
I would like to set the avaible values of a functions parameter something like this:

let valueList = [
   'val1',
   'val2',
   'val3',
];

let getSomething = (parameter: valueList) => {
    // do something
}

And i want to get error on console if parameter value other than what are in the valueList variable.

And it would be good, if IDE showup the possible values when I call the function as follow:

getSomething(| <- cursor ) // when cursor here, the IDE show the possible values from valueList

Body:
Use enum for this:

enum ValueList {
   val1,
   val2,
   val3
}


问:
Number of children explodes after filtering on child value
I have a model (Track) with children (Rank). That can be described (simplified) as:

```<code>class Track(models.Model):
    id = models.CharField('Unique ID', max_length=100,
    primary_key=True)
    title = models.CharField('Track title', max_length=100)
    artist = models.CharField('Artist name', max_length=100)

class Rank(models.Model):
    id = models.AutoField(primary_key=True)
    trackid = models.ForeignKey(Track, related_name='rank')
    cdate = models.DateField("Date", blank=True, null=True)
</code>```

When doing this:

```<code>track_list = Track.objects.filter(Q(artist__icontains=query) |
Q(title__icontains=query)) \
.annotate(children=Count('rank'))

for track in track_list:
    print(track.children)
</code>```

The number of children per track are all close to 100 (e.g 65,78,95) and that is correct.

But when I narrow the queryset further down by applying another filter and a needed annotation:

```<code>track_list = track_list.distinct() \
.filter(rank__cdate__year=filterquery) \
.annotate(entrydate=Min('rank__cdate')) \
.annotate(children=Count('rank'))

for track in track_list:
    print(track.children)
</code>```

The number of children explodes to several thousands per track.
Any ideas?

答:
Probably by joining you get the Rank models multiple times. Try adding a distinct=True to the Count as follows:

```<code>track_list = track_list.distinct() \
    .filter(rank__cdate__year=filterquery) \
    .annotate(entrydate=Min('rank__cdate')) \
    .annotate(children=Count('rank', distinct=True))
</code>```

Body:
I have a model (Track) with children (Rank). That can be described (simplified) as:

class Track(models.Model):
    id = models.CharField('Unique ID', max_length=100,
    primary_key=True)
    title = models.CharField('Track title', max_length=100)
    artist = models.CharField('Artist name', max_length=100)

class Rank(models.Model):
    id = models.AutoField(primary_key=True)
    trackid = models.ForeignKey(Track, related_name='rank')
    cdate = models.DateField("Date", blank=True, null=True)

When doing this:

track_list = Track.objects.filter(Q(artist__icontains=query) |
Q(title__icontains=query)) \
.annotate(children=Count('rank'))

for track in track_list:
    print(track.children)

The number of children per track are all close to 100 (e.g 65,78,95) and that is correct.

But when I narrow the queryset further down by applying another filter and a needed annotation:

track_list = track_list.distinct() \
.filter(rank__cdate__year=filterquery) \
.annotate(entrydate=Min('rank__cdate')) \
.annotate(children=Count('rank'))

for track in track_list:
    print(track.children)

The number of children explodes to several thousands per track.
Any ideas?

Body:
Probably by joining you get the Rank models multiple times. Try adding a distinct=True to the Count as follows:

track_list = track_list.distinct() \
    .filter(rank__cdate__year=filterquery) \
    .annotate(entrydate=Min('rank__cdate')) \
    .annotate(children=Count('rank', distinct=True))


问:
How to properly suspend multiple threads with posix signals?
In the context of an existing multi-threaded application I want to suspend a list of threads for a specific duration then resume their normal execution. I know some of you wil say that I should not do that but I know that and I don't have a choice.

I came up with the following code that sort of work but randomly failed. For each thread I want to suspend, I send a signal and wait for an ack via a semaphore. The signal handler when invoked, post the semaphore and sleep for the specified duration.

The problem is when the system is fully loaded, the call to sem_timedwait sometimes fails with ETIMEDOUT and I am left with an inconsistent logic with semaphore used for the ack: I don't know if the signal has been dropped or is just late.

```<code>// compiled with: gcc main.c -o test -pthread

#include <pthread.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/syscall.h>

#define NUMTHREADS 40
#define SUSPEND_SIG (SIGRTMIN+1)
#define SUSPEND_DURATION  80 // in ms

static sem_t sem;

void checkResults(const char *msg, int rc) {
    if (rc == 0) {
        //printf("%s success\n", msg);
    } else if (rc == ESRCH) {
        printf("%s failed with ESRCH\n", msg);
    } else if (rc == EINVAL) {
        printf("%s failed with EINVAL\n", msg);
    } else {
        printf("%s failed with unknown error: %d\n", msg, rc);
    }
}

static void suspend_handler(int signo) {
    sem_post(&sem);
    usleep(SUSPEND_DURATION*1000);
}

void installSuspendHandler() {
    struct sigaction sa;

    memset(&sa, 0, sizeof(sa));

    sigemptyset(&sa.sa_mask);

    sa.sa_flags = 0;
    sa.sa_handler = suspend_handler;

    int rc = sigaction(SUSPEND_SIG, &sa, NULL);
    checkResults("sigaction SUSPEND", rc);
}

void *threadfunc(void *param) {
    int tid = *((int *) param);
    free(param);

    printf("Thread %d entered\n", tid);

    // this is an example workload, the real app is doing many things
    while (1) {
        int rc = sleep(30);

        if (rc != 0 && errno == EINTR) {
            //printf("Thread %d got a signal delivered to it\n", tid);
        } else {
            //printf("Thread %d did not get expected results! rc=%d, errno=%d\n", tid, rc, errno);
        }
    }

    return NULL;
}

int main(int argc, char **argv) {
    pthread_t threads[NUMTHREADS];
    int i;

    sem_init(&sem, 0, 0);

    installSuspendHandler();

    for(i=0; i<NUMTHREADS; ++i) {
        int *arg = malloc(sizeof(*arg));
        if ( arg == NULL ) {
            fprintf(stderr, "Couldn't allocate memory for thread arg.\n");
            exit(EXIT_FAILURE);
        }

        *arg = i;
        int rc = pthread_create(&threads[i], NULL, threadfunc, arg);
        checkResults("pthread_create()", rc);
    }

    sleep(3);

    printf("Will start to send signals...\n");

    while (1) {
        printf("***********************************************\n");
        for(i=0; i<NUMTHREADS; ++i) {
            int rc = pthread_kill(threads[i], SUSPEND_SIG);
            checkResults("pthread_kill()", rc);

            printf("Waiting for Semaphore for thread %d ...\n", i);

            // compute timeout abs timestamp for ack
            struct timespec ts;
            clock_gettime(CLOCK_REALTIME, &ts);
            const int TIMEOUT = SUSPEND_DURATION*1000*1000; // in nano-seconds

            ts.tv_nsec += TIMEOUT; // timeout to receive ack from signal handler

            // normalize timespec
            ts.tv_sec += ts.tv_nsec / 1000000000;
            ts.tv_nsec %= 1000000000;

            rc = sem_timedwait(&sem, &ts); // try decrement semaphore

            if (rc == -1 && errno == ETIMEDOUT) {
                // timeout
                // semaphore is out of sync
                printf("Did not received signal handler sem_post before timeout of %d ms for thread %d", TIMEOUT/1000000, i);
                abort();
            }
            checkResults("sem_timedwait", rc);
            printf("Received Semaphore for thread %d.\n", i);
        }

        sleep(1);
    }

    for(i=0; i<NUMTHREADS; ++i) {
        int rc = pthread_join(threads[i], NULL);
        checkResults("pthread_join()\n", rc);
    }
    printf("Main completed\n");
    return 0;
}
</code>```

Questions?

Is it possible for a signal to be dropped and never delivered?

What causes the timeout on the semaphore at random time when the system is loaded?

答:
usleep() is not among the async-signal-safe functions (though sleep() is, and there are other async-signal-safe functions by which you can produce a timed delay).  A program that calls usleep() from a signal handler is therefore non-conforming.  The specifications do not describe what may happen -- neither with such a call itself nor with the larger program execution in which it occurs.  Your questions can be answered only for a conforming program; I do that below.

Is it possible for a signal to be dropped and never delivered?

It depends on what exactly you mean:

If a normal (not real-time) signal is delivered to a thread that already has that signal queued then no additional instance is queued.

A thread can die with signals still queued for it; those signals will not be handled.

A thread can change a given signal's disposition (to SIG_IGN, for example), though this is a per-process attribute, not a per-thread one.

A thread can block a signal indefinitely.  A blocked signal is not dropped -- it remains queued for the thread and will eventually be received some time after it is unblocked, if that ever happens.

But no, having successfully queued a signal via the kill() or raise() function, that signal will not be randomly dropped.

What causes the timeout on the semaphore at random time when the system is loaded?

A thread can receive a signal only when it is actually running on a core.  On a system with more runnable processes than cores, some runnable processes must be suspended, without a timeslice on any core, at any given time.  On a heavily-loaded system, that's the norm.  Signals are asynchronous, so you can send one to a thread that is currently waiting for a timeslice without the sender blocking.  It is entirely possible, then, that the thread you have signaled does not get scheduled to run before the timeout expires.  If it does run, it may have the signal blocked for one reason or another, and not get around to unblocking it before it uses up its timeslice.

Ultimately, you can use your semaphore-based approach to check whether the target thread handled the signal within any timeout of your choice, but you cannot predict in advance how long it will take for the thread to handle the signal, nor even whether it will do so in any finite amount of time (for example, it could die for one reason or another before doing so).

Body:
In the context of an existing multi-threaded application I want to suspend a list of threads for a specific duration then resume their normal execution. I know some of you wil say that I should not do that but I know that and I don't have a choice.

I came up with the following code that sort of work but randomly failed. For each thread I want to suspend, I send a signal and wait for an ack via a semaphore. The signal handler when invoked, post the semaphore and sleep for the specified duration.

The problem is when the system is fully loaded, the call to sem_timedwait sometimes fails with ETIMEDOUT and I am left with an inconsistent logic with semaphore used for the ack: I don't know if the signal has been dropped or is just late.

// compiled with: gcc main.c -o test -pthread

#include <pthread.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/syscall.h>

#define NUMTHREADS 40
#define SUSPEND_SIG (SIGRTMIN+1)
#define SUSPEND_DURATION  80 // in ms

static sem_t sem;

void checkResults(const char *msg, int rc) {
    if (rc == 0) {
        //printf("%s success\n", msg);
    } else if (rc == ESRCH) {
        printf("%s failed with ESRCH\n", msg);
    } else if (rc == EINVAL) {
        printf("%s failed with EINVAL\n", msg);
    } else {
        printf("%s failed with unknown error: %d\n", msg, rc);
    }
}

static void suspend_handler(int signo) {
    sem_post(&sem);
    usleep(SUSPEND_DURATION*1000);
}

void installSuspendHandler() {
    struct sigaction sa;

    memset(&sa, 0, sizeof(sa));

    sigemptyset(&sa.sa_mask);

    sa.sa_flags = 0;
    sa.sa_handler = suspend_handler;

    int rc = sigaction(SUSPEND_SIG, &sa, NULL);
    checkResults("sigaction SUSPEND", rc);
}

void *threadfunc(void *param) {
    int tid = *((int *) param);
    free(param);

    printf("Thread %d entered\n", tid);

    // this is an example workload, the real app is doing many things
    while (1) {
        int rc = sleep(30);

        if (rc != 0 && errno == EINTR) {
            //printf("Thread %d got a signal delivered to it\n", tid);
        } else {
            //printf("Thread %d did not get expected results! rc=%d, errno=%d\n", tid, rc, errno);
        }
    }

    return NULL;
}

int main(int argc, char **argv) {
    pthread_t threads[NUMTHREADS];
    int i;

    sem_init(&sem, 0, 0);

    installSuspendHandler();

    for(i=0; i<NUMTHREADS; ++i) {
        int *arg = malloc(sizeof(*arg));
        if ( arg == NULL ) {
            fprintf(stderr, "Couldn't allocate memory for thread arg.\n");
            exit(EXIT_FAILURE);
        }

        *arg = i;
        int rc = pthread_create(&threads[i], NULL, threadfunc, arg);
        checkResults("pthread_create()", rc);
    }

    sleep(3);

    printf("Will start to send signals...\n");

    while (1) {
        printf("***********************************************\n");
        for(i=0; i<NUMTHREADS; ++i) {
            int rc = pthread_kill(threads[i], SUSPEND_SIG);
            checkResults("pthread_kill()", rc);

            printf("Waiting for Semaphore for thread %d ...\n", i);

            // compute timeout abs timestamp for ack
            struct timespec ts;
            clock_gettime(CLOCK_REALTIME, &ts);
            const int TIMEOUT = SUSPEND_DURATION*1000*1000; // in nano-seconds

            ts.tv_nsec += TIMEOUT; // timeout to receive ack from signal handler

            // normalize timespec
            ts.tv_sec += ts.tv_nsec / 1000000000;
            ts.tv_nsec %= 1000000000;

            rc = sem_timedwait(&sem, &ts); // try decrement semaphore

            if (rc == -1 && errno == ETIMEDOUT) {
                // timeout
                // semaphore is out of sync
                printf("Did not received signal handler sem_post before timeout of %d ms for thread %d", TIMEOUT/1000000, i);
                abort();
            }
            checkResults("sem_timedwait", rc);
            printf("Received Semaphore for thread %d.\n", i);
        }

        sleep(1);
    }

    for(i=0; i<NUMTHREADS; ++i) {
        int rc = pthread_join(threads[i], NULL);
        checkResults("pthread_join()\n", rc);
    }
    printf("Main completed\n");
    return 0;
}

Questions?

Is it possible for a signal to be dropped and never delivered?

What causes the timeout on the semaphore at random time when the system is loaded?