问:
How to stop Google Cast excessive logging on Android?
Google Cast is logging to logcat like crazy on all my devices. The log is full of annoying garbage like:

```<code>I/CastMediaRouteProvider: Published ...
I/Publisher: Processing device ...
I/CastDeviceController: ...
</code>```

which makes development very tedious process. Is there any way to shut it off?

答: I came up with something like ^((?!CastMediaRouteProvider|Publisher|CastDeviceController).)*$ in my logcat filter but would be awesome to turn it off completely.

Body:
Google Cast is logging to logcat like crazy on all my devices. The log is full of annoying garbage like:

I/CastMediaRouteProvider: Published ...
I/Publisher: Processing device ...
I/CastDeviceController: ...

which makes development very tedious process. Is there any way to shut it off?


来源: stackexchange

问:
Wordpress Register options when plugin is activated
I want to register an option when my plugin is activated to be used in the settings page.

My code is like this:

```<code>function jpsNews_activate_plugin() {
    // REGISTER SETTINGS
    register_setting( 'jps_settings_group', 'jps_test');
    ...
}
register_activation_hook(__FILE__, 'jpsNews_activate_plugin');
</code>```

When i go to the database and search for that option, nothing is found. What am i missing? Can i do it like this?

Thanks in advance.

答:
Your option will only get stored to the database after you go to the setting pane and submit new values.

You have to remember that in Wordpress - like in any PHP application - stuff gets loaded only when a code runs to load it. And the settings API allows you to create settings pages for the current admin page being used - the register_setting() method doesn't "register your new settings in the database" or something, it just displays the settings to the admin if the admin is currently in the admin screen and looking at the settings page!

The correct way to create new settings is to register the settings under the admin_init action, which happens just before the admin pages are shown to the admin. See the register_settings() documentation for a simple example on how to do this correctly.

ContentLicense: CC BY-SA 3.0

Body:
I want to register an option when my plugin is activated to be used in the settings page.

My code is like this:

function jpsNews_activate_plugin() {
    // REGISTER SETTINGS
    register_setting( 'jps_settings_group', 'jps_test');
    ...
}
register_activation_hook(__FILE__, 'jpsNews_activate_plugin');

When i go to the database and search for that option, nothing is found. What am i missing? Can i do it like this?

Thanks in advance.


问:
saving operators in arrays, error
To give an idea of what I want elaborate with this code is the following:

Enter two numbers: 10 7

Choose Operator: e.g. (+, - , * and /)

What's 10 * 7?

Correct!

```<code>int[] arr = new int[5];

System.out.println("enter two numbers: ");
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();

System.out.println("Choose Operator: ");
arr[3] = sc.nextInt();

int operator = arr[1]+arr[3]+arr[2];

System.out.print("what's "+operator);
int svar = sc.nextInt();

if (svar == operator)
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is "+operator);
</code>```

Now I'm having a problem with running some aspects within this code. It works fine to compile but each time the program asks for to "choose operator" the compiler responses with the following error:

Exception in thread "main"

java.util.InputMismatchException   at

java.util.Scanner.throwFor(Unknown

Source)    at

java.util.Scanner.next(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)

at test1.main(test1.java:13)

I wonder how I'm going to deal with this one. But the goal would be to "save" the desired operator, and then put it together with arr[1] and arr[2] (shown in int operator) to "sort of" create this whole mathematical operation. But the error occurs when I choose one particular operator.

I would appreciate some help with this one. Thank you!

答:
All you need is two Ints, one Char and one Double, if it's not a must to use arrays so this is the code for you:

```<code>int num1, num2;
double result;
char op;

System.out.println("enter two numbers: ");
num1 = sc.nextInt();
num2 = sc.nextInt();

System.out.println("Choose Operator: ");
op = System.in.read();  // Edited

switch ( op )
{
     case '+': res = num1 + num2; break;
     case '-': res = num1 - num2; break;
     case '/': res = num1 / num2; break;
     case '*': res = num1 * num2; break;
}

System.out.print("what's " + num1 + op + num2 );

if ( sc.nextInt() == res )
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is " + res );
</code>```

Enjoy,
Rotem

ContentLicense: CC BY-SA 2.5

Title: saving operators in arrays, error

Body:
To give an idea of what I want elaborate with this code is the following:

Enter two numbers: 10 7

Choose Operator: e.g. (+, - , * and /)

What's 10 * 7?

Correct!

int[] arr = new int[5];

System.out.println("enter two numbers: ");
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();

System.out.println("Choose Operator: ");
arr[3] = sc.nextInt();

int operator = arr[1]+arr[3]+arr[2];

System.out.print("what's "+operator);
int svar = sc.nextInt();

if (svar == operator)
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is "+operator);

Now I'm having a problem with running some aspects within this code. It works fine to compile but each time the program asks for to "choose operator" the compiler responses with the following error:

Exception in thread "main"

java.util.InputMismatchException   at

java.util.Scanner.throwFor(Unknown

Source)    at

java.util.Scanner.next(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)

at test1.main(test1.java:13)

I wonder how I'm going to deal with this one. But the goal would be to "save" the desired operator, and then put it together with arr[1] and arr[2] (shown in int operator) to "sort of" create this whole mathematical operation. But the error occurs when I choose one particular operator.

I would appreciate some help with this one. Thank you!

Body:
All you need is two Ints, one Char and one Double, if it's not a must to use arrays so this is the code for you:

int num1, num2;
double result;
char op;

System.out.println("enter two numbers: ");
num1 = sc.nextInt();
num2 = sc.nextInt();

System.out.println("Choose Operator: ");
op = System.in.read();  // Edited

switch ( op )
{
     case '+': res = num1 + num2; break;
     case '-': res = num1 - num2; break;
     case '/': res = num1 / num2; break;
     case '*': res = num1 * num2; break;
}

System.out.print("what's " + num1 + op + num2 );

if ( sc.nextInt() == res )
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is " + res );

Enjoy,
Rotem


问:
To send form data using URL with POST method of REST give Error 500 Internal Server Error
This is AngularJS Controller

```<code>'use strict';

/**
 * @ngdoc function
 * @name demonApp.controller:totalTasty.becameAChefCtrl
 * @description
 * # MainCtrl
 * Controller of the demonApp
 */
angular.module('demonApp')
  .controller('becameAChefCtrl', function($scope, $http) {
      // create a blank object to handle form data.
       $http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

      // calling our submit function.
        $scope.submitForm = function() {
        // Posting data to php file
        $http({
          method  : 'POST',
          url     : 'http://something/chef',
          data : {name: "as", meaning: "ass", gender: "asss", religion: "sdad"},
          headers : {'Content-Type': 'application/x-www-form-urlencoded'}

         })
         .then(function mySuccess(response) {
      $scope.message = response.data;
    }, function myError(response) {
      $scope.errorName = response.statusText;

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

My REST Service is in php on codeigniter :

```<code><?php
header("Access-Control-Allow-Origin: *");
defined('BASEPATH') OR exit('No direct cripts are allowed here');
require(APPPATH.'libraries/REST_Controller.php');

class FirstRest extends REST_Controller {
  public function __construct(){
    parent::__construct();
    //calling model.
    $this->load->model("Babymodel","a");
    $this->load->helper('url');
    $this->output->set_header('Access-Control-Allow-Origin: *');
   }

   public function chef_post(){
   $data = array(
  'name' =>$this->input->post('name'),
  'meaning' =>$this->input->post('meaning'),
  'gender' =>$this->input->post('gender'),
  'religion' =>$this->input->post('religion')
  );

      $value = $this->a->insertbabyData('baby',$data);
      if($value)

       {
           $this->response($value, 200); // 200 being the HTTP response code
       }
       else
       {
           $this->response(NULL, 404);
       }
    }
 }
 ?>
</code>```

And Method insertbabyData() in Model is:

```<code>public function insertbabyData($table_name,$data)
{

    $this->db->insert($table_name,$data);

    return $this->db->get_where($table_name,array('id'=>$this->db-> insert_id()))->row_array();

}
</code>```

Notes:  I using same server to run AngularJS project and RESTful services.
        My GET method work properly in same project with same REST for GET url.

答:
I got the solution:

Please add this with $http({.....});

```<code>transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
</code>```

And data will be:

```<code> data: {name: "akash", meaning: "space", gender: "male", religion:"hindu"}
</code>```

Body:
This is AngularJS Controller

'use strict';

/**
 * @ngdoc function
 * @name demonApp.controller:totalTasty.becameAChefCtrl
 * @description
 * # MainCtrl
 * Controller of the demonApp
 */
angular.module('demonApp')
  .controller('becameAChefCtrl', function($scope, $http) {
      // create a blank object to handle form data.
       $http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

      // calling our submit function.
        $scope.submitForm = function() {
        // Posting data to php file
        $http({
          method  : 'POST',
          url     : 'http://something/chef',
          data : {name: "as", meaning: "ass", gender: "asss", religion: "sdad"},
          headers : {'Content-Type': 'application/x-www-form-urlencoded'}

         })
         .then(function mySuccess(response) {
      $scope.message = response.data;
    }, function myError(response) {
      $scope.errorName = response.statusText;

       });
     };
  });

My REST Service is in php on codeigniter :

<?php
header("Access-Control-Allow-Origin: *");
defined('BASEPATH') OR exit('No direct cripts are allowed here');
require(APPPATH.'libraries/REST_Controller.php');

class FirstRest extends REST_Controller {
  public function __construct(){
    parent::__construct();
    //calling model.
    $this->load->model("Babymodel","a");
    $this->load->helper('url');
    $this->output->set_header('Access-Control-Allow-Origin: *');
   }

   public function chef_post(){
   $data = array(
  'name' =>$this->input->post('name'),
  'meaning' =>$this->input->post('meaning'),
  'gender' =>$this->input->post('gender'),
  'religion' =>$this->input->post('religion')
  );

      $value = $this->a->insertbabyData('baby',$data);
      if($value)

       {
           $this->response($value, 200); // 200 being the HTTP response code
       }
       else
       {
           $this->response(NULL, 404);
       }
    }
 }
 ?>

And Method insertbabyData() in Model is:

public function insertbabyData($table_name,$data)
{

    $this->db->insert($table_name,$data);

    return $this->db->get_where($table_name,array('id'=>$this->db-> insert_id()))->row_array();

}

Notes:  I using same server to run AngularJS project and RESTful services.
        My GET method work properly in same project with same REST for GET url.

Body:
I got the solution:

Please add this with $http({.....});

transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },

And data will be:

 data: {name: "akash", meaning: "space", gender: "male", religion:"hindu"}


问:
R - Lattice - Change color of regression line
I am trying to change the regression line color to red. Right now everything is plotting blue.

```<code>library(lattice)

xyplot(ROC1.spx ~ ROC1.vix, data=newdf,
xlab = "VIX 1 Day % Change",
ylab = "S&P500 1 Day % Change",
grid = TRUE,
type = c("p","r"))
</code>```

To plot the regression line on the chart I used type = c("p","r")).

Open to other methods if need be, the code above produces this output.

Any assistance with changing regression line to red is appreciated!

答:
The answer was to:

```<code>type = c("p","r"),col.line = "red",
</code>```

col.line ="color", :)

Body:
I am trying to change the regression line color to red. Right now everything is plotting blue.

library(lattice)

xyplot(ROC1.spx ~ ROC1.vix, data=newdf,
xlab = "VIX 1 Day % Change",
ylab = "S&P500 1 Day % Change",
grid = TRUE,
type = c("p","r"))

To plot the regression line on the chart I used type = c("p","r")).

Open to other methods if need be, the code above produces this output.

Any assistance with changing regression line to red is appreciated!

Body:
The answer was to:

type = c("p","r"),col.line = "red",

col.line ="color", :)


问:
gradle no signature of a java method (hashmap.getOrDefault) applicable
This happened while I'm trying to build with Gradle. There seems to be no reason for this error to occur as Strings are Objects:

```<code>No signature of method: java.util.HashMap.getOrDefault() is applicable for argument types: (java.lang.String, java.lang.String) values: [profile, development]
Possible solutions: getOrDefault(java.lang.Object, java.lang.Object)
</code>```

Code:

```<code>apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'jacoco'

sourceCompatibility = '1.8'
targetCompatibility = '1.8'

def DEFAULT_PROFILE = 'development'
def profile = project.getProperties().getOrDefault("profile", DEFAULT_PROFILE)
def config = new ConfigSlurper(profile).parse(file("profiles.gradle").toURL())
</code>```

Note I'm using Intellij Idea rather than Eclipse as my IDE, for a project made in Eclipse. This is also my first time using Gradle, so might be some beginner's mistake.

答:
I have no idea why this should happen, other than that the Object class the String class extends comes from a different classloader than the Object class the HashMap is using in the parameters. With stuff like that you can also produce messages like could not cast java.lang.String to java.lang.String, because the same class loaded from different classloaders are not the same class, but different ones regarding instanceof checks.

Maybe if you would provide a MCVE or the actual project as a whole one could make up what's going on.

Actually you could instead use a more Groovy style:

```<code>project.findProperty("profile") ?: DEFAULT_PROFILE
</code>```

Body:
This happened while I'm trying to build with Gradle. There seems to be no reason for this error to occur as Strings are Objects:

No signature of method: java.util.HashMap.getOrDefault() is applicable for argument types: (java.lang.String, java.lang.String) values: [profile, development]
Possible solutions: getOrDefault(java.lang.Object, java.lang.Object)

Code:

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'jacoco'

sourceCompatibility = '1.8'
targetCompatibility = '1.8'

def DEFAULT_PROFILE = 'development'
def profile = project.getProperties().getOrDefault("profile", DEFAULT_PROFILE)
def config = new ConfigSlurper(profile).parse(file("profiles.gradle").toURL())

Note I'm using Intellij Idea rather than Eclipse as my IDE, for a project made in Eclipse. This is also my first time using Gradle, so might be some beginner's mistake.

Body:
I have no idea why this should happen, other than that the Object class the String class extends comes from a different classloader than the Object class the HashMap is using in the parameters. With stuff like that you can also produce messages like could not cast java.lang.String to java.lang.String, because the same class loaded from different classloaders are not the same class, but different ones regarding instanceof checks.

Maybe if you would provide a MCVE or the actual project as a whole one could make up what's going on.

Actually you could instead use a more Groovy style:

project.findProperty("profile") ?: DEFAULT_PROFILE


问:
Linear gradient width using percentage (%) instead of pixels (px)
I am using chart.js to make a graph with linear gradient :

```<code><script src="js/Chart.min.js"></script>
<script type="text/javascript">
var ctx = document.getElementById('myChart').getContext('2d');

var grd = ctx.createLinearGradient(0, 0, canvas.width, 0);
grd.addColorStop(0.2, 'red');
grd.addColorStop(0.4, 'orange');
grd.addColorStop(0.78, 'limegreen');
grd.addColorStop(0.9, 'black');

var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'horizontalBar',

    // The data for our dataset
    data: {
        labels: ["Confort"],
        datasets: [
        {
            label: ["Confort actuel"],
            borderWidth: 0,
            borderColor: 'rgba(0,0,0,1.0)',
            backgroundColor: 'rgba(0,0,0,0.2)',
            hoverBackgroundColor: 'rgba(0,0,0,0)',
            data: [64],
        },
        {
            label: ["Confort projeté"],
            borderWidth: 0,
            borderColor: 'rgba(0,0,0,1.0)',
            backgroundColor: grd,
            hoverBackgroundColor: grd,
            data: [120],
        },
        {
            label: ["Confort optimal"],
            borderWidth: 0,
            borderColor: 'rgba(0,0,0,1.0)',
            backgroundColor: 'rgba(205,205,205,1.0)',
            hoverBackgroundColor: 'rgba(205,205,205,1.0)',
            data: [100],
        },
        ]
    },

    // Configuration options go here
    options: {
        legend: {
            display: false,
        },
        scales: {
            xAxes: [{
                stacked:false,
                ticks: {
                    beginAtZero:true,
                    max: 130,
                    display: false,
                },
                gridLines : {
                    display: false,
                    drawBorder: false,
                },
            }],
            yAxes: [{
                display:false,
                stacked:true,
                barThickness: 20,
                gridLines: {
                    display: false,
                    drawBorder: false,
                }
            }],
        },
        tooltips: {
            enabled: false,
            callbacks: {
                label: function(tooltipItems, data) {
                    return " " + tooltipItems.xLabel + "%";
                }
            }
        },
    }
});
Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;

        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'right';
        ctx.textBaseline = 'center';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                if (dataset.label[i] == "Confort projeté") {
                    ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x-8, model.y + 21);
                    ctx.fillText("▲", model.x+6, model.y + 19);
                }
                else if  (dataset.label[i] == "Confort actuel") {
                    ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x-8, model.y - 14);
                    ctx.fillText("▼", model.x+6, model.y - 12);
                }
                else {
                    ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x+130, model.y - 14);
                    ctx.fillText("▼", model.x+6, model.y - 12);
                }
            }
        });
  }
});
</script>
</code>```

As you can see, I tried using canvas.width for the gradient (instead of 1024, before). But it makes my canvas crash and I have no idea why...

Anyone can help me?

Thanks!

答:
You should use the following ...

```<code>ctx.canvas.width
</code>```

var ctx = document.getElementById('myChart').getContext('2d');

var grd = ctx.createLinearGradient(0, 0, ctx.canvas.width, 0);
grd.addColorStop(0.2, 'red');
grd.addColorStop(0.4, 'orange');
grd.addColorStop(0.78, 'limegreen');
grd.addColorStop(0.9, 'black');

var chart = new Chart(ctx, {
   // The type of chart we want to create
   type: 'horizontalBar',

   // The data for our dataset
   data: {
      labels: ["Confort"],
      datasets: [{
         label: ["Confort actuel"],
         borderWidth: 0,
         borderColor: 'rgba(0,0,0,1.0)',
         backgroundColor: 'rgba(0,0,0,0.2)',
         hoverBackgroundColor: 'rgba(0,0,0,0)',
         data: [64],
      }, {
         label: ["Confort projeté"],
         borderWidth: 0,
         borderColor: 'rgba(0,0,0,1.0)',
         backgroundColor: grd,
         hoverBackgroundColor: grd,
         data: [120],
      }, {
         label: ["Confort optimal"],
         borderWidth: 0,
         borderColor: 'rgba(0,0,0,1.0)',
         backgroundColor: 'rgba(205,205,205,1.0)',
         hoverBackgroundColor: 'rgba(205,205,205,1.0)',
         data: [100],
      }, ]
   },

   // Configuration options go here
   options: {
      legend: {
         display: false,
      },
      scales: {
         xAxes: [{
            stacked: false,
            ticks: {
               beginAtZero: true,
               max: 130,
               display: false,
            },
            gridLines: {
               display: false,
               drawBorder: false,
            },
         }],
         yAxes: [{
            display: false,
            stacked: true,
            barThickness: 20,
            gridLines: {
               display: false,
               drawBorder: false,
            }
         }],
      },
      tooltips: {
         enabled: false,
         callbacks: {
            label: function(tooltipItems, data) {
               return " " + tooltipItems.xLabel + "%";
            }
         }
      },
   }
});
Chart.pluginService.register({
   afterDraw: function(chartInstance) {
      var ctx = chartInstance.chart.ctx;

      // render the value of the chart above the bar
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'right';
      ctx.textBaseline = 'center';

      chartInstance.data.datasets.forEach(function(dataset) {
         for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            if (dataset.label[i] == "Confort projeté") {
               ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x - 8, model.y + 21);
               ctx.fillText("▲", model.x + 6, model.y + 19);
            } else if (dataset.label[i] == "Confort actuel") {
               ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x - 8, model.y - 14);
               ctx.fillText("▼", model.x + 6, model.y - 12);
            } else {
               ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x + 130, model.y - 14);
               ctx.fillText("▼", model.x + 6, model.y - 12);
            }
         }
      });
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas></code>```

Body:
I am using chart.js to make a graph with linear gradient :

As you can see, I tried using canvas.width for the gradient (instead of 1024, before). But it makes my canvas crash and I have no idea why...

Anyone can help me?

Thanks!

Body:
You should use the following ...

ctx.canvas.width

var ctx = document.getElementById('myChart').getContext('2d');

var grd = ctx.createLinearGradient(0, 0, ctx.canvas.width, 0);
grd.addColorStop(0.2, 'red');
grd.addColorStop(0.4, 'orange');
grd.addColorStop(0.78, 'limegreen');
grd.addColorStop(0.9, 'black');

var chart = new Chart(ctx, {
   // The type of chart we want to create
   type: 'horizontalBar',

   // The data for our dataset
   data: {
      labels: ["Confort"],
      datasets: [{
         label: ["Confort actuel"],
         borderWidth: 0,
         borderColor: 'rgba(0,0,0,1.0)',
         backgroundColor: 'rgba(0,0,0,0.2)',
         hoverBackgroundColor: 'rgba(0,0,0,0)',
         data: [64],
      }, {
         label: ["Confort projeté"],
         borderWidth: 0,
         borderColor: 'rgba(0,0,0,1.0)',
         backgroundColor: grd,
         hoverBackgroundColor: grd,
         data: [120],
      }, {
         label: ["Confort optimal"],
         borderWidth: 0,
         borderColor: 'rgba(0,0,0,1.0)',
         backgroundColor: 'rgba(205,205,205,1.0)',
         hoverBackgroundColor: 'rgba(205,205,205,1.0)',
         data: [100],
      }, ]
   },

   // Configuration options go here
   options: {
      legend: {
         display: false,
      },
      scales: {
         xAxes: [{
            stacked: false,
            ticks: {
               beginAtZero: true,
               max: 130,
               display: false,
            },
            gridLines: {
               display: false,
               drawBorder: false,
            },
         }],
         yAxes: [{
            display: false,
            stacked: true,
            barThickness: 20,
            gridLines: {
               display: false,
               drawBorder: false,
            }
         }],
      },
      tooltips: {
         enabled: false,
         callbacks: {
            label: function(tooltipItems, data) {
               return " " + tooltipItems.xLabel + "%";
            }
         }
      },
   }
});
Chart.pluginService.register({
   afterDraw: function(chartInstance) {
      var ctx = chartInstance.chart.ctx;

      // render the value of the chart above the bar
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'right';
      ctx.textBaseline = 'center';

      chartInstance.data.datasets.forEach(function(dataset) {
         for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            if (dataset.label[i] == "Confort projeté") {
               ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x - 8, model.y + 21);
               ctx.fillText("▲", model.x + 6, model.y + 19);
            } else if (dataset.label[i] == "Confort actuel") {
               ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x - 8, model.y - 14);
               ctx.fillText("▼", model.x + 6, model.y - 12);
            } else {
               ctx.fillText(dataset.label[i] + " (" + dataset.data[i] + "%)", model.x + 130, model.y - 14);
               ctx.fillText("▼", model.x + 6, model.y - 12);
            }
         }
      });
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>


问:
How to create VR Video player using Google Cardboard SDK for Unity
I just downloaded Google Cardboard SDK for unity. I am fine and able to create VR project. Setup is fine and everything is working fine.

I am noob at VR Apps. Just stepped in VR Apps.

I am planing to create my own VR Enabled Video Player for android, Just like the default Google Cardboard Youtube player.

Can any one suggest me a link or can guide me in developing this app.

答:
This has become very simple for Unity 5.6 and above.

You just need a sphere with its normals inverted which you can either find online or just go to blender and make an IcoSphere and flip its normals or you can use a shader to do the same on a normal sphere. In either case use an Unlit texture for the shader.

Add a Video Player in the component which comes default with Unity to this sphere.

Add any 360 degree video to this Video Player. You can also add an online link as well. And it plays consistently well throughout the range of platforms from GoogleVR to SteamVR.

The only downside is, it only plays monoscopic images/videos by default and there requires some tweaking to run stereoscopic images/videos.


问:
Run Python codes on subdirectories
How do I run python codes (.py) on subdirectories from the main folder?

What is the easiest way to do this?

I tried:

```<code>os.chdir("path") #path = path to subdirectory
import abc #abc = module on subdirectory
</code>```

Error:

```<code>ImportError: No module named abc
</code>```

答:
Take a look at this </p>

```<code>import sys
sys.path
sys.path.append('/path/to/the/example_file.py')
import example_file
</code>```

Title: Run Python codes on subdirectories

Body:
How do I run python codes (.py) on subdirectories from the main folder?

What is the easiest way to do this?

I tried:

os.chdir("path") #path = path to subdirectory
import abc #abc = module on subdirectory

Error:

ImportError: No module named abc

Body:
Take a look at this

import sys
sys.path
sys.path.append('/path/to/the/example_file.py')
import example_file


问:
catch specific error message in Python
I need to catch when one of my dependencies throws a specific ValueError and deal with that a certain way, and otherwise re-raise the error.
I don't find any recent questions that deal with this in a way that's Python 3 compliant, and that deals with cases where the only thing distinguishing errors returned is the string message.

This post is probably the closest: Python: Catching specific exception

Something like this-- catch specific HTTP error in python --won't work because I'm not using a dependency that also supplies specific codes like an HTTP error would have.

Here's my attempt:

try:
    spect, freq_bins, time_bins = spect_maker.make(syl_audio,
                                                   self.sampFreq)
except ValueError as err:
    if str(err) == 'window is longer than input signal':
        warnings.warn('Segment {0} in {1} with label {2} '
                      'not long enough for window function'
                      ' set with current spect_params.\n'
                      'spect will be set to nan.')
        spect, freq_bins, time_bins = (np.nan,
                                       np.nan,
                                       np.nan)
    else:
        raise
```

If it matters, the dependency is scipy and I need to catch when the spectrogram fails for a specific reason (the segment I'm taking a spectrogram of is shorter than the window function).

I realize my approach is fragile because it depends on the error string not changing, but the error string is the only thing that distinguishes it from other ValueErrors returned by the same function. So I plan to have a unit test to defend myself against that.

答:
Ok, so based on other people's comments, I'm guessing it should be something like this:</p>

```<code># lower-level module
class CustomError(Exception):
    pass

# in method
Class Thing:
    def __init__(prop1):
        self.prop1 = prop1

    def method(self,element):
        try:
            dependency.function(element,self.prop1)
        except ValueError as err:
            if str(err) == 'specific ValueError':
                raise CustomError
            else:
                raise # re-raise ValueError because string not recognized

# back in higher-level module
thing = lowerlevelmodule.Thing(prop1)
for element in list_of_stuff:
    try:
        output = thing.method(element)
    except CustomError:
        output = None
        warnings.warn('set output to None for {} because CustomError'.
                       format(element))
</code>```

Title: catch specific error message in Python

Body:
I need to catch when one of my dependencies throws a specific ValueError and deal with that a certain way, and otherwise re-raise the error.
I don't find any recent questions that deal with this in a way that's Python 3 compliant, and that deals with cases where the only thing distinguishing errors returned is the string message.

This post is probably the closest: Python: Catching specific exception

Something like this-- catch specific HTTP error in python --won't work because I'm not using a dependency that also supplies specific codes like an HTTP error would have.

Here's my attempt:

try:
    spect, freq_bins, time_bins = spect_maker.make(syl_audio,
                                                   self.sampFreq)
except ValueError as err:
    if str(err) == 'window is longer than input signal':
        warnings.warn('Segment {0} in {1} with label {2} '
                      'not long enough for window function'
                      ' set with current spect_params.\n'
                      'spect will be set to nan.')
        spect, freq_bins, time_bins = (np.nan,
                                       np.nan,
                                       np.nan)
    else:
        raise

If it matters, the dependency is scipy and I need to catch when the spectrogram fails for a specific reason (the segment I'm taking a spectrogram of is shorter than the window function).

I realize my approach is fragile because it depends on the error string not changing, but the error string is the only thing that distinguishes it from other ValueErrors returned by the same function. So I plan to have a unit test to defend myself against that.

Body:
Ok, so based on other people's comments, I'm guessing it should be something like this:

# lower-level module
class CustomError(Exception):
    pass

# in method
Class Thing:
    def __init__(prop1):
        self.prop1 = prop1

    def method(self,element):
        try:
            dependency.function(element,self.prop1)
        except ValueError as err:
            if str(err) == 'specific ValueError':
                raise CustomError
            else:
                raise # re-raise ValueError because string not recognized

# back in higher-level module
thing = lowerlevelmodule.Thing(prop1)
for element in list_of_stuff:
    try:
        output = thing.method(element)
    except CustomError:
        output = None
        warnings.warn('set output to None for {} because CustomError'.
                       format(element))


问:
Place holder in C#
```<code>   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace switch_calculator
    {
        class Program
        {
            static void Main(string[] args)
            {
                double num1, num2;
                char opt;

                Console.WriteLine("Enter num1");
                num1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter num2");
                num2 = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Select the operation you would like to perform" );
       Console.WriteLine("Press \n 'A' for Add \n 'S' for subtraction
\n 'D' for Division \n 'M' for multiplicatiion \n 'R' for Remainder");

                opt = Convert.ToChar(Console.ReadLine());
                switch(opt)
                {
                    case 'A':

                        Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
                        break;
                }

                Console.ReadLine();

            }
        }
    }
</code>```

Here it's my C# code , I'm very new to programming I was just
wondering can I assign place holder value to other number like
{0},{7} or {1},{3} instead of {0},{1} in the switch case statement
case A ?? can someone pls explain the place holder concept here ?

答: No, you can't. A syntax sugar is to use $"your Add result {num1} + {num2} is {num1+num2}. And still you can't change the indexing of the placeholders. They always start from 0

Title: Place holder in C#

Body:
   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace switch_calculator
    {
        class Program
        {
            static void Main(string[] args)
            {
                double num1, num2;
                char opt;

                Console.WriteLine("Enter num1");
                num1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter num2");
                num2 = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Select the operation you would like to perform" );
       Console.WriteLine("Press \n 'A' for Add \n 'S' for subtraction
\n 'D' for Division \n 'M' for multiplicatiion \n 'R' for Remainder");

                opt = Convert.ToChar(Console.ReadLine());
                switch(opt)
                {
                    case 'A':

                        Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
                        break;
                }

                Console.ReadLine();

            }
        }
    }

Here it's my C# code , I'm very new to programming I was just
wondering can I assign place holder value to other number like
{0},{7} or {1},{3} instead of {0},{1} in the switch case statement
case A ?? can someone pls explain the place holder concept here ?


答:
I believe you want to import abc into your current module, even though they're located on different folders. Depending on your python, there are different ways to do this:

Python2.x

```<code>import imp
abc = imp.load_source('abc', '/path/to/abc.py')
</code>```

Python 3.4

```<code>from importlib.machinery import SourceFileLoader
abc = SourceFileLoader('abc', '/path/to/abc.py').load_module()
</code>```

In either case, abc will be imported for use as usual.

```<code>>>> abc
<module 'abc' from '/path/to/abc.py'>
</code>```

This is cleaner because it does not involve polluting your sys.path.

Title: Run Python codes on subdirectories

Body:
I believe you want to import abc into your current module, even though they're located on different folders. Depending on your python, there are different ways to do this:

Python2.x

import imp
abc = imp.load_source('abc', '/path/to/abc.py')

Python 3.4

from importlib.machinery import SourceFileLoader
abc = SourceFileLoader('abc', '/path/to/abc.py').load_module()

In either case, abc will be imported for use as usual.

>>> abc
<module 'abc' from '/path/to/abc.py'>

This is cleaner because it does not involve polluting your sys.path.


问:
AttributeError: 'module' object has no attribute 'createLBPHFaceRecognizer'
From this question in SO I understand the error should be solved by having opencv contrib, but the thing is that when I first built opencv using cmake using this guide by pyimagesearch , I had also built opencvcontrib. If I must rebuild it, how exactly should I do it?

This is the error:

import cv2

  cv2.createLBPHFaceRecognizer()

      Traceback (most recent call last):

    File "stdin", line 1, in module

  AttributeError: 'module' object has no attribute 'createLBPHFaceRecognizer'

Also:

import cv2

  help(cv2.face.createLBPHFaceRecognizer)

  Traceback (most recent call last):

    File "stdin", line 1, in module

  AttributeError: 'module' object has no attribute 'face'

Mac OS, Python 2.7, Opencv 3.2

答: createLBPHFaceRecognizer() is in the sub-module cv2.face in python. To access it you should use cv2.face.createLBPHFaceRecognizer().


问:
How to get data from a Swift NSURLSession?
For example, I have the following code:

```<code>let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
        var dann = NSString(data: data, encoding: NSUTF8StringEncoding)!
        self.str = dann
})
task.resume()
</code>```

I want to transfer the data to a variable in the class (the str variable in the class). The string self.str = dann does not convey anything. How can I do this?

答:
// Swift 3 based for Quick ref.</p>

```<code>let task = URLSession.shared.dataTask(with: NSURL(string: "http://httpbin.org/get")! as URL, completionHandler: { (data, response, error) -> Void in
    do{
       let str = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject]
       print(str)
    } catch {
        fatalError("json error: \(error)")
    }
})
task.resume()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For example, I have the following code:

let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
        var dann = NSString(data: data, encoding: NSUTF8StringEncoding)!
        self.str = dann
})
task.resume()

I want to transfer the data to a variable in the class (the str variable in the class). The string self.str = dann does not convey anything. How can I do this?

Body:
// Swift 3 based for Quick ref.

let task = URLSession.shared.dataTask(with: NSURL(string: "http://httpbin.org/get")! as URL, completionHandler: { (data, response, error) -> Void in
    do{
       let str = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject]
       print(str)
    } catch {
        fatalError("json error: \(error)")
    }
})
task.resume()


问:
HTML not rendering on php page
I'm making an app with complete php. I'm using a bootstrap admin template to make the code. However, when I run the application, some pages aren't rendered. Instead, when I navigate to the page, it displays a localhost error that just says "check errors". An example of this is when I navigate from the index page to the user profile page. I receive an error from the application when I try to use a link to navigate to the app's profile page. How do I fix this? </p>

答: I found my problem. The error log was saying that I wasn't including a file properly. Once I fixed it, the application worked. Thank you. </p>

Title: HTML not rendering on php page


问:
PHP Execute Shell Command And Retrieve The Output
I'm trying to retrieve the contents of a file on a remote server via SSH and display the results in a browser.  The remote server's name and address is configured on my local server with the name "router", such that from the command line I can execute the following to successfully retrieve the results:

```<code>ssh router "cat /var/log/messages"
</code>```

I'm having trouble getting this to execute in PHP - I can't get the quotes escaped properly.  Here's my PHP script

```<code>```
$command = 'ssh router \"cat /var/log/messages\"';
<?php system($command); ?>
```
</code>```

But this outputs the command string to the webpage instead of executing the command and returning the results.

答:
Use escapeshellarg() to escape command argument. Please try like this

```<code>$host       =  escapeshellarg("user@router");
$commandArg =  escapeshellarg("/var/log/messages");
$result     = shell_exec('ssh ' . $host . ' cat ' . $commandArg);
echo $result, PHP_EOL;
</code>```

Body:
I'm trying to retrieve the contents of a file on a remote server via SSH and display the results in a browser.  The remote server's name and address is configured on my local server with the name "router", such that from the command line I can execute the following to successfully retrieve the results:

ssh router "cat /var/log/messages"

I'm having trouble getting this to execute in PHP - I can't get the quotes escaped properly.  Here's my PHP script

$command = 'ssh router \"cat /var/log/messages\"';
<?php system($command); ?>

But this outputs the command string to the webpage instead of executing the command and returning the results.

Body:
Use escapeshellarg() to escape command argument. Please try like this

$host       =  escapeshellarg("user@router");
$commandArg =  escapeshellarg("/var/log/messages");
$result     = shell_exec('ssh ' . $host . ' cat ' . $commandArg);
echo $result, PHP_EOL;


问:
[R]:Can the time below in opening a 7GB csv be further reduced from 17 min to less than a minute
My code snippet and time taken data is as below.

any suggestions and alternate options  on how to reduce the below to less than a minute maximum.

```<code>##########RUN FROM r 64bit windows 10###########################

> #automation to import large clog data into R
> gc()
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  363072 19.4     592000 31.7   460000 24.6
Vcells 6672707 51.0   10309224 78.7  7293876 55.7
> memory.limit(size=20000)
[1] 20000
> library(data.table)
data.table 1.10.4
  The fastest way to learn (by data.table authors): https://www.datacamp.com/courses/data-analysis-the-data-table-way
  Documentation: ?data.table, example(data.table) and browseVignettes("data.table")
  Release notes, videos and slides: http://r-datatable.com
> DT <- fread("C:/CLOG-BIG-DATA-PROJECT/WestBengal_0000.txt",sep=",",header=FALSE,
              showProgress = TRUE,verbose=TRUE )

###############################################################

#output#########################################################

**17502188 rows and 64 (of 64) columns from 7.143 GB file in 00:17:38**
Read 17502188 rows. Exactly what was estimated and allocated up front
   0.000s (  0%) Memory map (rerun may be quicker)
   0.000s (  0%) sep and header detection
  18.283s (  2%) Count rows (wc -l)
   0.000s (  0%) Column type detection (100 rows at 10 points)
  19.296s (  2%) Allocation of 17502188x64 result (xMB) in RAM
**1019.676s ( 93%) Reading data**
   0.107s (  0%) Allocation for type bumps (if any), including gc time if triggered
   0.048s (  0%) Coercing data already read in type bumps (if any)
  39.639s (  4%) Changing na.strings to NA
**1097.049s        Total**
</code>```

答:
Yes, there is a very simple solution: switch to the latest dev version of data.table. There were literally dozens of speed improvements in fread since version 1.10.4 that you have, most important one is switch to parallel file reading.

For example, on my laptop I have a 2.7Gb CSV file with 13M rows x 35 columns (roughly 2.5 times smaller than yours). It takes only 15.7s to read it with the current latest version of R data.table. Assuming your file has a similar structure, it should take approximately 40s for fread to ingest it.

Body:
My code snippet and time taken data is as below.

any suggestions and alternate options  on how to reduce the below to less than a minute maximum.

##########RUN FROM r 64bit windows 10###########################

> #automation to import large clog data into R
> gc()
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  363072 19.4     592000 31.7   460000 24.6
Vcells 6672707 51.0   10309224 78.7  7293876 55.7
> memory.limit(size=20000)
[1] 20000
> library(data.table)
data.table 1.10.4
  The fastest way to learn (by data.table authors): https://www.datacamp.com/courses/data-analysis-the-data-table-way
  Documentation: ?data.table, example(data.table) and browseVignettes("data.table")
  Release notes, videos and slides: http://r-datatable.com
> DT <- fread("C:/CLOG-BIG-DATA-PROJECT/WestBengal_0000.txt",sep=",",header=FALSE,
              showProgress = TRUE,verbose=TRUE )

###############################################################

#output#########################################################

**17502188 rows and 64 (of 64) columns from 7.143 GB file in 00:17:38**
Read 17502188 rows. Exactly what was estimated and allocated up front
   0.000s (  0%) Memory map (rerun may be quicker)
   0.000s (  0%) sep and header detection
  18.283s (  2%) Count rows (wc -l)
   0.000s (  0%) Column type detection (100 rows at 10 points)
  19.296s (  2%) Allocation of 17502188x64 result (xMB) in RAM
**1019.676s ( 93%) Reading data**
   0.107s (  0%) Allocation for type bumps (if any), including gc time if triggered
   0.048s (  0%) Coercing data already read in type bumps (if any)
  39.639s (  4%) Changing na.strings to NA
**1097.049s        Total**


问:
Save UIImage array to disk
I have a UIImage array that I'm trying to save to disk (documents directory). I've converted it to Data so it can be saved but I can't figure out the correct/best way to save that [Data] to disk.

(arrayData as NSArray).write(to: filename, atomically: false) doesn't seem right or there seems like there is some better way.

Code so far:

```<code>    // Get the new UIImage
    let image4 = chartView.snapShot()

    // Make UIImage into Data to save
    let data = UIImagePNGRepresentation(image4!)

    // Add Data image to Data Array
    arrayData.append(data!)

    // Get Disk/Folder
    let filename = getDocumentsDirectory().appendingPathComponent("images")

    // This is how I'd Write Data image to Disk
    // try? data?.write(to: filename)

    // TODO: Write array Data images to Disk
    (arrayData as NSArray).write(to: filename, atomically: false)
</code>```

答:
You can below code to stored image into local.</p>

```<code>   let fileManager = NSFileManager.defaultManager()
    let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("ImageName.png")
    let image = YOUR_IMAGE_TO_STORE.
    let imageData = UIImageJPEGRepresentation(image!, 0.5)
    fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
</code>```

Title: Save UIImage array to disk

Body:
I have a UIImage array that I'm trying to save to disk (documents directory). I've converted it to Data so it can be saved but I can't figure out the correct/best way to save that [Data] to disk.

(arrayData as NSArray).write(to: filename, atomically: false) doesn't seem right or there seems like there is some better way.

Code so far:

    // Get the new UIImage
    let image4 = chartView.snapShot()

    // Make UIImage into Data to save
    let data = UIImagePNGRepresentation(image4!)

    // Add Data image to Data Array
    arrayData.append(data!)

    // Get Disk/Folder
    let filename = getDocumentsDirectory().appendingPathComponent("images")

    // This is how I'd Write Data image to Disk
    // try? data?.write(to: filename)

    // TODO: Write array Data images to Disk
    (arrayData as NSArray).write(to: filename, atomically: false)

Body:
You can below code to stored image into local.

   let fileManager = NSFileManager.defaultManager()
    let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("ImageName.png")
    let image = YOUR_IMAGE_TO_STORE.
    let imageData = UIImageJPEGRepresentation(image!, 0.5)
    fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)


问:
convert all xlsx files in directory to text
I am trying to create a button in a .xlsm that will convert each of the ~100 .xlsx files in the myFolder directory to .txt. The below VBA code returns an Expected End Suberror. The data is always in `Sheet 1" even though there may be other sheets present.

The Dos command executes and converts the files but they are unreadable (something to do with excels formatting?). I am not sure what to do?  Thank you :)

Dos

```<code>cd C:\Users\Desktop\folder
Copy *.xlsx *.txt
</code>```

VBA

```<code>Option Explicit

Private Sub CommandButton1_Click()

Dim oFSO, myFolder
Dim xlText

myFolder = "C:\Users\Desktop\folder"

Set oFSO = CreateObject("Scripting.FileSystemObject")
xlText = -4158 'Excel txt format enum
Call ConvertAllExcelFiles(myFolder)
Set oFSO = Nothing

Call MsgBox("Done!")

Sub ConvertAllExcelFiles(ByVal oFolder)
Dim targetF, oFileList, oFile
Dim oExcel, oWB, oWSH

Set oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
Set targetF = oFSO.GetFolder(oFolder)
Set oFileList = targetF.Files
For Each oFile In oFileList
If (Right(oFile.Name, 4) = "xlsx") Then
    Set oWB = oExcel.Workbooks.Open(oFile.Path)
    For Each oWSH In oWB.Sheets
        Call oWSH.SaveAs(oFile.Path & ".txt", FileFormat:=xlTextWindows)
    Next
    Set oWSH = Nothing
    Call oWB.Close
    Set oWB = Nothing
End If
Next
Call oExcel.Quit
Set oExcel = Nothing
End Sub
</code>```

答:
The first lines of your code belong in Private Sub CommandButton1_Click()

(it has to be closed by End Sub)

Option Explicit and proper code indentation can help in this situation

Try this version:

```<code>Option Explicit

Private Sub CommandButton1_Click()
    Dim myFolder As String

    myFolder = "C:\Users\Desktop\folder"
    ConvertAllExcelFiles myFolder
    MsgBox "Done!"
End Sub

Public Sub ConvertAllExcelFiles(ByVal folderPath As String)
    Dim xlApp As Object, wb As Workbook, ws As Variant, fso As Object
    Dim fileList As Object, itm As Object, fileName As String

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fileList = fso.GetFolder(folderPath).Files
    Set xlApp = CreateObject("Excel.Application")
    xlApp.DisplayAlerts = False

    For Each itm In fileList
        If Right(itm.Name, 4) = "xlsx" Then
            Set wb = xlApp.Workbooks.Open(itm.Path)
            fileName = fso.GetParentFolderName(itm.Path) & "\" & fso.GetBaseName(itm.Path)
            If True Then    'if converting all sheets use For loop (Change True to False)
                wb.Sheets(1).SaveAs fileName & ".txt", FileFormat:=xlTextWindows
            Else
                For Each ws In wb.Sheets
                  ws.SaveAs fileName & " - " & ws.Name & ".txt", FileFormat:=xlTextWindows
                Next
                Set ws = Nothing
            End If
            wb.Close:   Set wb = Nothing
        End If
    Next
    xlApp.Quit
End Sub
</code>```

Body:
I am trying to create a button in a .xlsm that will convert each of the ~100 .xlsx files in the myFolder directory to .txt. The below VBA code returns an Expected End Suberror. The data is always in `Sheet 1" even though there may be other sheets present.

The Dos command executes and converts the files but they are unreadable (something to do with excels formatting?). I am not sure what to do?  Thank you :)

Dos

cd C:\Users\Desktop\folder
Copy *.xlsx *.txt

VBA

Option Explicit

Private Sub CommandButton1_Click()

Dim oFSO, myFolder
Dim xlText

myFolder = "C:\Users\Desktop\folder"

Set oFSO = CreateObject("Scripting.FileSystemObject")
xlText = -4158 'Excel txt format enum
Call ConvertAllExcelFiles(myFolder)
Set oFSO = Nothing

Call MsgBox("Done!")

Sub ConvertAllExcelFiles(ByVal oFolder)
Dim targetF, oFileList, oFile
Dim oExcel, oWB, oWSH

Set oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
Set targetF = oFSO.GetFolder(oFolder)
Set oFileList = targetF.Files
For Each oFile In oFileList
If (Right(oFile.Name, 4) = "xlsx") Then
    Set oWB = oExcel.Workbooks.Open(oFile.Path)
    For Each oWSH In oWB.Sheets
        Call oWSH.SaveAs(oFile.Path & ".txt", FileFormat:=xlTextWindows)
    Next
    Set oWSH = Nothing
    Call oWB.Close
    Set oWB = Nothing
End If
Next
Call oExcel.Quit
Set oExcel = Nothing
End Sub

Body:
The first lines of your code belong in Private Sub CommandButton1_Click()

(it has to be closed by End Sub)

Option Explicit and proper code indentation can help in this situation

Try this version:

Option Explicit

Private Sub CommandButton1_Click()
    Dim myFolder As String

    myFolder = "C:\Users\Desktop\folder"
    ConvertAllExcelFiles myFolder
    MsgBox "Done!"
End Sub

Public Sub ConvertAllExcelFiles(ByVal folderPath As String)
    Dim xlApp As Object, wb As Workbook, ws As Variant, fso As Object
    Dim fileList As Object, itm As Object, fileName As String

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fileList = fso.GetFolder(folderPath).Files
    Set xlApp = CreateObject("Excel.Application")
    xlApp.DisplayAlerts = False

    For Each itm In fileList
        If Right(itm.Name, 4) = "xlsx" Then
            Set wb = xlApp.Workbooks.Open(itm.Path)
            fileName = fso.GetParentFolderName(itm.Path) & "\" & fso.GetBaseName(itm.Path)
            If True Then    'if converting all sheets use For loop (Change True to False)
                wb.Sheets(1).SaveAs fileName & ".txt", FileFormat:=xlTextWindows
            Else
                For Each ws In wb.Sheets
                  ws.SaveAs fileName & " - " & ws.Name & ".txt", FileFormat:=xlTextWindows
                Next
                Set ws = Nothing
            End If
            wb.Close:   Set wb = Nothing
        End If
    Next
    xlApp.Quit
End Sub


问:
Is it considered accepted using var's as "shortcuts" in c#?
One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

```<code>using MyApp.Properties;
</code>```

-- or --

```<code>using appsettings = MyAppp.Properties.Settings;
</code>```

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

```<code>var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;
</code>```

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)

答:
Seems fine to me, it can enhance readability especially if you're using that long .notated syntax many times.

As a side, if you're using an indexed property or an autogenerated property (which does work on the fly for the GETTER) multiple times, then there can be a performance hit for each access of this property. That's microoptimisation though, so probably shouldn't worry too much about that.

Body:
One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

using MyApp.Properties;

-- or --

using appsettings = MyAppp.Properties.Settings;

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)


问:
SpongyCastle private key extraction very slow
I am using following method to extract private key from secret key using Spongy Castle:

```<code>public static PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecKey, char[] pass)
        throws PGPException {
    if (pgpSecKey == null) return null;

    PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(
            new BcPGPDigestCalculatorProvider()).build(pass);
    return pgpSecKey.extractPrivateKey(decryptor);
}
</code>```

However the last line of code runs very slow (aproximately 90 secs) on Android. Is there any better way on how to extract PGPPrivateKey from encrypted secret keys? Maybe I am doing some mistake when exporting secret key from linux but I dont think that this is the problem since I use simple command gpg --export-secret-keys > key.skr. Any ideas on what could be causing this problem?

答:
I noticed a similar slow performance at the PKCS8 private key decryption after upgrading the Android Gradle plugin from 2.2.1 to 3.3.0.

The slow performance is caused by Instant Run. When Instant Run is deactivated, the decryption needs ~1 second.

Body:
I am using following method to extract private key from secret key using Spongy Castle:

public static PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecKey, char[] pass)
        throws PGPException {
    if (pgpSecKey == null) return null;

    PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(
            new BcPGPDigestCalculatorProvider()).build(pass);
    return pgpSecKey.extractPrivateKey(decryptor);
}

However the last line of code runs very slow (aproximately 90 secs) on Android. Is there any better way on how to extract PGPPrivateKey from encrypted secret keys? Maybe I am doing some mistake when exporting secret key from linux but I dont think that this is the problem since I use simple command gpg --export-secret-keys > key.skr. Any ideas on what could be causing this problem?


问:
Output paragraph to web page depending on whether a user input answer is true or false
I want to make an application with 3 questions, each with 2 buttons: yes and no. I want to output a different paragraph in response, depending on whether the answer was true or false (not an alert message!). How do I proceed??</p>

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Tegne med Javascript</title>
    <script>

    function oppstart () {
           function hs(){
         document.getElementById('utskrift').onclick = "riktig";
       }
       function hu(){
       document.getElementById('utskrift').onclick = "feil";
     }
       function ss(){
         document.getElementById('utskrift1').onclick = "riktig";
       }
       function su(){
         document.getElementById('utskrift1').onclick = "feil";
       }
       function ts(){
         document.getElementById('utskrift2').onclick = "riktig";
       }
       function tu(){
         document.getElementById('utskrift2').onclick = "feil";
     }
    }

    </script>
    </head>

    <body>
    jeg har hode
    <p id="utskrift"></p>
    <button type="submit" id="hs">Sann</button>  <button type="submit"
    id="hu">USann</button>
    <br>
    <br>

    <p id="utskrift1"></p>
    jeg liker Skyrim   <button type="submit" id="ss">Sann</button>  <button
    type="submit" id="su">USann</button>
      <br>
        <br>

        <p id="utskrift2"></p>
    jeg heter Tarzan   <button type="submit" id="ts">Sann</button>  <button
    type="submit" id="tu">USann</button>

   </body>
</code>```

答:
Each question's Yes/No buttons will have a click event callback function that will check the answer given and deliver the correct output.

Don't use submit buttons for this since you aren't actually submitting form data anywhere, regular button types will do.

This can be optimized a bit by combining the 3 functions I'm showing below into a single one, but that will complicate the code beyond beginner level, so you may want to stick with this approach for now.

// Get references to all of the buttons
var q1P = document.getElementById("utskrift1");
var q1Sann = document.getElementById("hs");
var q1Usann = document.getElementById("hu");

var q2P = document.getElementById("utskrift2");
var q2Sann = document.getElementById("ss");
var q2Usann = document.getElementById("su");

var q3P = document.getElementById("utskrift3");
var q3Sann = document.getElementById("ts");
var q3Usann = document.getElementById("tu");

// Set up each set of buttons to invoke a validation function when they are clicked
q1Sann.addEventListener("click", q1Validate);
q1Usann.addEventListener("click", q1Validate);

q2Sann.addEventListener("click", q2Validate);
q2Usann.addEventListener("click", q2Validate);

q3Sann.addEventListener("click", q3Validate);
q3Usann.addEventListener("click", q3Validate);

// Validation functions
function q1Validate (evt) {
  var message = "";

  // Test which button was clicked and populate the appropriate paragraph accordingly
  if(evt.target === q1Sann){
    message = "Correct!";
  } else {
    message = "Incorrect!";
  }

  // Update the paragraph with the message
  q1P.textContent = message;
}

function q2Validate (evt) {
  var message = "";

  // Test which button was clicked and populate the appropriate paragraph accordingly
  if(evt.target === q2Sann){
    message = "Correct!";
  } else {
    message = "Incorrect!";
  }
  q2P.textContent = message;
}

function q3Validate (evt) {
  var message = "";

  // Test which button was clicked and populate the appropriate paragraph accordingly
  if(evt.target === q3Sann){
    message = "Correct!";
  } else {
    message = "Incorrect!";
  }
  q3P.textContent = message;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p { color: blue; }</code>```

    jeg har hode
    <button type="button" id="hs">Sann</button>
    <button type="button" id="hu">USann</button>

    jeg liker Skyrim
    <button type="button" id="ss">Sann</button>
    <button type="button" id="su">USann</button>

    jeg heter Tarzan
    <button type="button" id="ts">Sann</button>
    <button type="button" id="tu">USann</button>

    ```

Body:
I want to make an application with 3 questions, each with 2 buttons: yes and no. I want to output a different paragraph in response, depending on whether the answer was true or false (not an alert message!). How do I proceed??

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Tegne med Javascript</title>

    jeg har hode

    <button type="submit" id="hs">Sann</button>  <button type="submit"
    id="hu">USann</button>

    jeg liker Skyrim   <button type="submit" id="ss">Sann</button>  <button
    type="submit" id="su">USann</button>

    jeg heter Tarzan   <button type="submit" id="ts">Sann</button>  <button
    type="submit" id="tu">USann</button>

Body:
Each question's Yes/No buttons will have a click event callback function that will check the answer given and deliver the correct output.

Don't use submit buttons for this since you aren't actually submitting form data anywhere, regular button types will do.

This can be optimized a bit by combining the 3 functions I'm showing below into a single one, but that will complicate the code beyond beginner level, so you may want to stick with this approach for now.

// Get references to all of the buttons
var q1P = document.getElementById("utskrift1");
var q1Sann = document.getElementById("hs");
var q1Usann = document.getElementById("hu");

var q2P = document.getElementById("utskrift2");
var q2Sann = document.getElementById("ss");
var q2Usann = document.getElementById("su");

var q3P = document.getElementById("utskrift3");
var q3Sann = document.getElementById("ts");
var q3Usann = document.getElementById("tu");

// Set up each set of buttons to invoke a validation function when they are clicked
q1Sann.addEventListener("click", q1Validate);
q1Usann.addEventListener("click", q1Validate);

q2Sann.addEventListener("click", q2Validate);
q2Usann.addEventListener("click", q2Validate);

q3Sann.addEventListener("click", q3Validate);
q3Usann.addEventListener("click", q3Validate);

// Validation functions
function q1Validate (evt) {
  var message = "";

  // Test which button was clicked and populate the appropriate paragraph accordingly
  if(evt.target === q1Sann){
    message = "Correct!";
  } else {
    message = "Incorrect!";
  }

  // Update the paragraph with the message
  q1P.textContent = message;
}

function q2Validate (evt) {
  var message = "";

  // Test which button was clicked and populate the appropriate paragraph accordingly
  if(evt.target === q2Sann){
    message = "Correct!";
  } else {
    message = "Incorrect!";
  }
  q2P.textContent = message;
}

function q3Validate (evt) {
  var message = "";

  // Test which button was clicked and populate the appropriate paragraph accordingly
  if(evt.target === q3Sann){
    message = "Correct!";
  } else {
    message = "Incorrect!";
  }
  q3P.textContent = message;
}

p { color: blue; }

<div>
    jeg har hode
    <button type="button" id="hs">Sann</button>
    <button type="button" id="hu">USann</button>
    <p id="utskrift1"></p>
</div>

<div>
    jeg liker Skyrim
    <button type="button" id="ss">Sann</button>
    <button type="button" id="su">USann</button>
    <p id="utskrift2"></p>
</div>

<div>
    jeg heter Tarzan
    <button type="button" id="ts">Sann</button>
    <button type="button" id="tu">USann</button>
    <p id="utskrift3"></p>
</div>


问:
Shifting around the image in bootstrap
Hi i know this is an amateur question, but i have some trouble.

This is my CSS`:

body{
 background-image: url(street-photography1.jpg);
 background-size: cover;
 color: white;
 background-repeat: no-repeat;
 background-position:center;
 background-attachment: fixed;
}
form{
 background-color: rgba(19, 18, 18, 0.66);
 color: white;
 padding: 40px;
 margin-top: 200px;
 padding-bottom: 60px;

}
.form-control{
 background-color: rgba(14, 14, 14, 0.35);
 border-radius: 0px;
 color: white;
}
.logo1{
 padding: 40px;
 margin-top: 200px;

}
h1{
 text-align: center;
}

.btn{
 width: 100%;
 margin-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>
 <!-- Latest compiled and minified CSS -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 <!-- Optional theme -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

 <!-- Latest compiled and minified JavaScript -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <!-- Bootstrap -->

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
 <link rel="stylesheet" type="text/css" href="style2.css" />
  </head>
  <body>

 <div class="container">
 <div class="column">
 <div class=" col-sm-5">
 <img class="logo1" src="images/capture.png" alt=" logo">
 </div>
 </div>

 <div class="row">

   <div class="col-sm-offset-6 col-sm-7">

    <form>

     <h1>Hello, world!</h1>
      <div class="form-group">
     <label for="exampleInputEmail1">Email address</label>
     <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
      </div>
      <div class="form-group">
     <label for="exampleInputPassword1">Password</label>
     <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
      </div>

      <div class="checkbox">
     <label>
       <input type="checkbox"> Remember Password
     </label>
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>

   </div>
  </div>
  <footer class="container">
    <div class="row">
      <p class="col-sm-5">
      Copyright © 2016 , Singapore. All rights reserved.</p>

    </div>
  </footer>

  </body>
</html></code>```

So currently my webpage looks like this.

How can i shift my message logo so that the logo and my validation form are in the same line with each other?

答:
You can next the two col divs inside of a row. i.e.</p>

```<code><div class="row">
  <div class="col-sm-12>
   <div class="row">
     <div class="col-sm-6>...Logo...
     <div class="col-sm-6>...Form...
     </div>
     </div>
  </div>
</div>
</code>```

Title: Shifting around the image in bootstrap

Body:
Hi i know this is an amateur question, but i have some trouble.

This is my CSS`:

body{
 background-image: url(street-photography1.jpg);
 background-size: cover;
 color: white;
 background-repeat: no-repeat;
 background-position:center;
 background-attachment: fixed;
}
form{
 background-color: rgba(19, 18, 18, 0.66);
 color: white;
 padding: 40px;
 margin-top: 200px;
 padding-bottom: 60px;

}
.form-control{
 background-color: rgba(14, 14, 14, 0.35);
 border-radius: 0px;
 color: white;
}
.logo1{
 padding: 40px;
 margin-top: 200px;

}
h1{
 text-align: center;
}

.btn{
 width: 100%;
 margin-top: 20px;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap 101 Template</title>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

 <link rel="stylesheet" type="text/css" href="style2.css" />

    <form>

Hello, world!

     Email address
     <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">

     Password
     <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">

       <input type="checkbox"> Remember Password

      <button type="submit" class="btn btn-default">Submit</button>
    </form>

      Copyright © 2016 , Singapore. All rights reserved.

So currently my webpage looks like this.

How can i shift my message logo so that the logo and my validation form are in the same line with each other?

Body:
You can next the two col divs inside of a row. i.e.

<div class="row">
  <div class="col-sm-12>
   <div class="row">
     <div class="col-sm-6>...Logo...
     <div class="col-sm-6>...Form...
     </div>
     </div>
  </div>
</div>


问:
Hough Circle in c# , dynamic memory
I have problem in dynamic memory allocation getting data from matrix

```<code>Image image_gray = new Image("im1.jpg");
Matrix circles = new Matrix(100, 1, 3);
</code>```

Question 1: How can I locate dynamic memory because I don't know the number of circles?

```<code>Emgu.CV.CvInvoke.cvHoughCircles(image_gray, circles, HOUGH_TYPE.CV_HOUGH_GRADIENT,
    2, 100, 200, 100, 10, 500);
</code>```

Question 2: Now circle is matrix with [100 ,3], How can I get

```<code>point center= Round (circle[i][1], circle[i][1])
</code>```

How can I get

```<code>int radius= circle[i][2];
</code>```

what should my for loop look like to get data from matrix and casting should be point and int.

I tried already (NOT WORKING / ERROR)

```<code>for (int i=0; i < circles.Rows; i++)
{ Matrix entry = circles.GetRow(i);

 float x = entry[0];
 float y = entry[1];
float r = entry[2];} // NOT WORKING
</code>```

because instead of copying (required) only (i) row it copies whole matrix( circles) and float x=......gives errors

```<code>No overload for method 'this' takes '1' arguments
</code>```

please help me in this regard

regards

sorry to answer my question. please give some hint to dynamic memory allocation and matrix data

答:
The documentation suggests that it will grow the matrix to fit, but it also contradicts that, so honestly, I would try a 1 row 1 col matrix on an image with more circles and see what it gives you.  I see that you're using Matrix type - I don't know how you convert to the IntPtr needed by cvHoughCircles, but it should be straight forward to iterate over each row and pull out the results, which are 3 floats: (x, y, r) -</p>

```<code>for (int i=0; i < circles.Cols; i++) {
    Matrix<float> entry = circles.GetRow(i);
    float x = entry[0]; // guessing here - the doc'n is truly awful
    float y = entry[1];
    float r = entry[2];
}
</code>```

Title: Hough Circle in c# , dynamic memory

Body:
I have problem in dynamic memory allocation getting data from matrix

Image image_gray = new Image("im1.jpg");
Matrix circles = new Matrix(100, 1, 3);

Question 1: How can I locate dynamic memory because I don't know the number of circles?

Emgu.CV.CvInvoke.cvHoughCircles(image_gray, circles, HOUGH_TYPE.CV_HOUGH_GRADIENT,
    2, 100, 200, 100, 10, 500);

Question 2: Now circle is matrix with [100 ,3], How can I get

point center= Round (circle[i][1], circle[i][1])

How can I get

int radius= circle[i][2];

what should my for loop look like to get data from matrix and casting should be point and int.

I tried already (NOT WORKING / ERROR)

for (int i=0; i < circles.Rows; i++)
{ Matrix entry = circles.GetRow(i);

 float x = entry[0];
 float y = entry[1];
float r = entry[2];} // NOT WORKING

because instead of copying (required) only (i) row it copies whole matrix( circles) and float x=......gives errors

No overload for method 'this' takes '1' arguments

please help me in this regard

regards

sorry to answer my question. please give some hint to dynamic memory allocation and matrix data

Body:
The documentation suggests that it will grow the matrix to fit, but it also contradicts that, so honestly, I would try a 1 row 1 col matrix on an image with more circles and see what it gives you.  I see that you're using Matrix type - I don't know how you convert to the IntPtr needed by cvHoughCircles, but it should be straight forward to iterate over each row and pull out the results, which are 3 floats: (x, y, r) -

for (int i=0; i < circles.Cols; i++) {
    Matrix<float> entry = circles.GetRow(i);
    float x = entry[0]; // guessing here - the doc'n is truly awful
    float y = entry[1];
    float r = entry[2];
}


答:
To save your images to the document directory, you could start by creating a function to save your image as follows. The function handles creating the image name for you and returns it.

```<code>    func saveImage(image: UIImage) -> String {

    let imageData = NSData(data: UIImagePNGRepresentation(image)!)
    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true)
   let docs = paths[0] as NSString
   let uuid = NSUUID().uuidString + ".png"
   let fullPath = docs.appendingPathComponent(uuid)
   _ = imageData.write(toFile: fullPath, atomically: true)
  return uuid

   }
</code>```

Now since you want to save an array of images, you can simply loop and call the saveImage function:

```<code>   for image in images {
       saveImage(image: image)
   }
</code>```

If you prefer to name those images yourself, you can amend the first function to the following:

```<code>    func saveImage(image: UIImage, withName name: String) {

 let imageData = NSData(data: UIImagePNGRepresentation(image)!)
 let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true)
 let docs = paths[0] as NSString
 let name = name
 let fullPath = docs.appendingPathComponent(name)
 _ = imageData.write(toFile: fullPath, atomically: true)
 }
</code>```

When you save an image as a UIImagePNGRepresentation as you are trying to do, please note that is does not save orientation for you. This means that when you attempt to retrieve the image, it might be titled to the left. You will need to redraw your image to make sure it has the right orientation as this post will explain how to save png correctly. However, if you save your image with UIImageJPEGRepresentation you will not have to worry about all that and you can simply save your image without any extra effort.

EDITED TO GIVE ARRAY OF IMAGES

To retrieve the images you have saved, you can use the following function where you pass an array of the image names and you get an array back:

```<code>   func getImage(imageNames: [String]) -> [UIImage] {

    var savedImages: [UIImage] = [UIImage]()

    for imageName in imageNames {

    if let imagePath = getFilePath(fileName: imageName) {
        savedImage.append(UIImage(contentsOfFile: imagePath))
    }

   }

   return savedImages

   }
</code>```

Which relies on this function to work:

```<code>    func getFilePath(fileName: String) -> String? {

    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    var filePath: String?
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
   if paths.count > 0 {
   let dirPath = paths[0] as NSString
   filePath = dirPath.appendingPathComponent(fileName)
   }
  else {
  filePath = nil
  }

  return filePath
  }
</code>```

Title: Save UIImage array to disk

Body:
To save your images to the document directory, you could start by creating a function to save your image as follows. The function handles creating the image name for you and returns it.

    func saveImage(image: UIImage) -> String {

    let imageData = NSData(data: UIImagePNGRepresentation(image)!)
    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true)
   let docs = paths[0] as NSString
   let uuid = NSUUID().uuidString + ".png"
   let fullPath = docs.appendingPathComponent(uuid)
   _ = imageData.write(toFile: fullPath, atomically: true)
  return uuid

   }

Now since you want to save an array of images, you can simply loop and call the saveImage function:

   for image in images {
       saveImage(image: image)
   }

If you prefer to name those images yourself, you can amend the first function to the following:

    func saveImage(image: UIImage, withName name: String) {

 let imageData = NSData(data: UIImagePNGRepresentation(image)!)
 let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true)
 let docs = paths[0] as NSString
 let name = name
 let fullPath = docs.appendingPathComponent(name)
 _ = imageData.write(toFile: fullPath, atomically: true)
 }

When you save an image as a UIImagePNGRepresentation as you are trying to do, please note that is does not save orientation for you. This means that when you attempt to retrieve the image, it might be titled to the left. You will need to redraw your image to make sure it has the right orientation as this post will explain how to save png correctly. However, if you save your image with UIImageJPEGRepresentation you will not have to worry about all that and you can simply save your image without any extra effort.

EDITED TO GIVE ARRAY OF IMAGES

To retrieve the images you have saved, you can use the following function where you pass an array of the image names and you get an array back:

   func getImage(imageNames: [String]) -> [UIImage] {

    var savedImages: [UIImage] = [UIImage]()

    for imageName in imageNames {

    if let imagePath = getFilePath(fileName: imageName) {
        savedImage.append(UIImage(contentsOfFile: imagePath))
    }

   }

   return savedImages

   }

Which relies on this function to work:

    func getFilePath(fileName: String) -> String? {

    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    var filePath: String?
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
   if paths.count > 0 {
   let dirPath = paths[0] as NSString
   filePath = dirPath.appendingPathComponent(fileName)
   }
  else {
  filePath = nil
  }

  return filePath
  }


问:
How convert a table format or it structure with Google Refine
I have a table with the following format:

```<code>ID  Estation    Y   M   D   H   N   Nh     h   Cl
1   78357     2017  5   1   1   0   0   -9001   0
2   78357     2017  5   1   2   0   0   -9001   0
3   78357     2017  5   1   3   1   1    750    5
</code>```

I want to convert the data in this table to the following format:

```<code>ID  Estation    Y   M   D   H   Var Value
1   78357     2017  5   1   1   N    0
2   78357     2017  5   1   2   N    0
3   78357     2017  5   1   3   N    1
4   78357     2017  5   1   1   Nh   0
5   78357     2017  5   1   2   Nh   0
6   78357     2017  5   1   3   Nh   1
7   78357     2017  5   1   1   h   -9001
8   78357     2017  5   1   2   h   -9001
9   78357     2017  5   1   3   h    750
10  78357     2017  5   1   1   Cl   0
11  78357     2017  5   1   2   Cl   0
12  78357     2017  5   1   3   Cl   5
</code>```

Due to the amount of registration I must take from one format to another I want to do it using Google Refine. Someone has any idea how to do it?.

答:
You can do this in Google Refine (now called OpenRefine) using the Transpose option.

In the 'N' column click the drop down menu and choose "Transpose -> Transpose cells across columns into rows"

In the screen shown choose "N" as the "From Column" and "(last column)" as the "To Column"

Choose to Transpose into Two New Columns.  Call the Key column "Var" and the Value column "Value"

Check the box that says "Fill down in other columns"

Click Transpose

This should give you the various variables & values in a single column with multiple rows

To sort in the order you give in your example maybe challenging. If you Sort the Var col in reverse alphabetical order it is close although not quite - not sure how important this is to you.

Remember in OpenRefine you have to choose to Reorder Rows Permanently to commit the new sort order.

You may have to transform the ID column to renumber with unique IDs. You can do this with the GREL rowIndex+1 once you have got the sort order correct

Body:
I have a table with the following format:

ID  Estation    Y   M   D   H   N   Nh     h   Cl
1   78357     2017  5   1   1   0   0   -9001   0
2   78357     2017  5   1   2   0   0   -9001   0
3   78357     2017  5   1   3   1   1    750    5

I want to convert the data in this table to the following format:

ID  Estation    Y   M   D   H   Var Value
1   78357     2017  5   1   1   N    0
2   78357     2017  5   1   2   N    0
3   78357     2017  5   1   3   N    1
4   78357     2017  5   1   1   Nh   0
5   78357     2017  5   1   2   Nh   0
6   78357     2017  5   1   3   Nh   1
7   78357     2017  5   1   1   h   -9001
8   78357     2017  5   1   2   h   -9001
9   78357     2017  5   1   3   h    750
10  78357     2017  5   1   1   Cl   0
11  78357     2017  5   1   2   Cl   0
12  78357     2017  5   1   3   Cl   5

Due to the amount of registration I must take from one format to another I want to do it using Google Refine. Someone has any idea how to do it?.


问:
Python and Variable Scope
So I am recently new to Python, but I seem to be able to program some stuff and get it working.  However I've been trying to expand my knowledge of how things work in the language, and putting this simple file together confuses me.

```<code>class TestA:
    def __init__(self):
        self.varNum = 3

    def printNum(self):
        print(self.varNum)

class TestB:
    varNum = 0

    def __init__(self):
        varNum = 3

    def printNum(self):
        global varNum
        print(varNum)

a = TestA()
a.printNum()

b = TestB()
b.printNum()
</code>```

The code to TestA prints 3 to the screen properly.  However the code for TestB instead gives me a NameError stating that: 'varNum' is not defined.  And I get that error whether i have the global varNum line there or not.

I suppose what confuses me, is I see the __init__ function as a class constructor.  And when I have programmed with languages such as Java or C# I've declared global variables outside of the constructor so that their scope is the whole class.  Is that not a thing in Python?  The code I've written I just kind of tagged self. onto everything because I was just trying to get some stuff put together quickly, but I am trying to figure more out about the language now.  Is self. the only way in Python to make class scope variables?  Or are there other ways?

Thanks for your time :)

答:
In Python, variables declared inside the class definition, but not inside a method are class or static variables:

```<code>class TestB:
    varNum = 0
</code>```

This creates a class-level varNum variable, but this is distinct from any instance-level varNum variable, so you could have:

```<code>class TestB:
    varNum = 0

    def __init__(self):
        self.varNum = 3

b = TestB()
print(b.varNum)  # print 3
print(TestB.varNum)  # print 0
</code>```

Thus, class TestB should work in this way:

```<code>class TestB:
    varNum = 0

    def __init__(self):
        self.varNum = 3

    def printInstanceNum(self):
        print(self.varNum)

    def printClassNum():
        print(TestB.varNum)

b = TestB()
b.printInstanceNum()  # print 3
TestB.printClassNum()  # print 0
</code>```

Note that since there's no any reference to instance object in method printClassNum(), we don't have to put self as an argument. The method could actually become a staticmethod:

```<code>class TestB:
    varNum = 0

    @staticmethod
    def printClassNum():
        print(TestB.varNum)
</code>```

Ref

class objects

static method

Title: Python and Variable Scope

Body:
So I am recently new to Python, but I seem to be able to program some stuff and get it working.  However I've been trying to expand my knowledge of how things work in the language, and putting this simple file together confuses me.

class TestA:
    def __init__(self):
        self.varNum = 3

    def printNum(self):
        print(self.varNum)

class TestB:
    varNum = 0

    def __init__(self):
        varNum = 3

    def printNum(self):
        global varNum
        print(varNum)

a = TestA()
a.printNum()

b = TestB()
b.printNum()

The code to TestA prints 3 to the screen properly.  However the code for TestB instead gives me a NameError stating that: 'varNum' is not defined.  And I get that error whether i have the global varNum line there or not.

I suppose what confuses me, is I see the __init__ function as a class constructor.  And when I have programmed with languages such as Java or C# I've declared global variables outside of the constructor so that their scope is the whole class.  Is that not a thing in Python?  The code I've written I just kind of tagged self. onto everything because I was just trying to get some stuff put together quickly, but I am trying to figure more out about the language now.  Is self. the only way in Python to make class scope variables?  Or are there other ways?

Thanks for your time :)

Body:
In Python, variables declared inside the class definition, but not inside a method are class or static variables:

class TestB:
    varNum = 0

This creates a class-level varNum variable, but this is distinct from any instance-level varNum variable, so you could have:

class TestB:
    varNum = 0

    def __init__(self):
        self.varNum = 3

b = TestB()
print(b.varNum)  # print 3
print(TestB.varNum)  # print 0

Thus, class TestB should work in this way:

class TestB:
    varNum = 0

    def __init__(self):
        self.varNum = 3

    def printInstanceNum(self):
        print(self.varNum)

    def printClassNum():
        print(TestB.varNum)

b = TestB()
b.printInstanceNum()  # print 3
TestB.printClassNum()  # print 0

Note that since there's no any reference to instance object in method printClassNum(), we don't have to put self as an argument. The method could actually become a staticmethod:

class TestB:
    varNum = 0

    @staticmethod
    def printClassNum():
        print(TestB.varNum)

Ref

class objects

static method


问:
Turbo C++ : while(fin) vs while(!fin.eof())
I was told that I should be using while(fin) instead of while(!fin.eof()) when reading a file.

What exactly is the difference?

Edit: I do know that while(fin) actually checks the stream object and that when it becomes NULL, the loop breaks and it covers eof and fail flags.
But my course teacher says that fin.eof() is better so I need to understand the fundamental operation that's going on here.

Which one is the right practice?

Note: This is not a duplicate, I need assistance in Turbo C++ and with binary files.
I'm basically trying to read a file using a class object.

答:
One good method is to do something like this:

```<code>while ( instream.read(...) && !instream.eof() ) {  //Reading a binary file
      Statement1;
      Statement2;
}
</code>```

or in case of a text file:

```<code>while ( (ch = instream.get()) && !instream.eof() ) {  //To read a single character
      Statement1;
      Statement2;
}
</code>```

Here, the object is being read within the while loop's condition statement and then the value of eof flag is being tested.
This wouldn't result in undesired outputs.

Here we are checking the status of the actual I/O operation and the eof together. You may also check for the fail flag.

I would like to point out that according to @RetiredNinja, we may only check for the I/O operation.
That is:

```<code>while ( instream.read(...) ) {  //Reading a binary file
      Statement1;
      Statement2;
}
</code>```

Body:
One good method is to do something like this:

while ( instream.read(...) && !instream.eof() ) {  //Reading a binary file
      Statement1;
      Statement2;
}

or in case of a text file:

while ( (ch = instream.get()) && !instream.eof() ) {  //To read a single character
      Statement1;
      Statement2;
}

Here, the object is being read within the while loop's condition statement and then the value of eof flag is being tested.
This wouldn't result in undesired outputs.

Here we are checking the status of the actual I/O operation and the eof together. You may also check for the fail flag.

I would like to point out that according to @RetiredNinja, we may only check for the I/O operation.
That is:

while ( instream.read(...) ) {  //Reading a binary file
      Statement1;
      Statement2;
}