问:
Changing a linked list of Ellipses to images in c#
I've made a simple snake game in c# wpf forms.The problem is that Iv'e made the food as Ellipses and I want to change that to an image of an apple.
This is the food class where I specified the type/shape of the food :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Controls;

namespace WpfApp1
{
class Food
{
    public double x, y;
    public Ellipse e = new Ellipse();
    public Food(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    public void setFoodPosition()
    {
        Random r = new Random();
        if (Settings.size != 0)
            e.Width = e.Height = Settings.g.Size;
        else
            e.Width = e.Height = 10;
        e.Stroke = Brushes.Black;
        e.Fill = new SolidColorBrush(Color.FromRgb((byte)r.Next(255), (byte)r.Next(255), (byte)r.Next(255))); ;
        Canvas.SetLeft(e, x);
        Canvas.SetTop(e, y);
    }
  }
 }
</code>```

does anyone have any idea how I do that?

Body:
I've made a simple snake game in c# wpf forms.The problem is that Iv'e made the food as Ellipses and I want to change that to an image of an apple.
This is the food class where I specified the type/shape of the food :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Controls;

namespace WpfApp1
{
class Food
{
    public double x, y;
    public Ellipse e = new Ellipse();
    public Food(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    public void setFoodPosition()
    {
        Random r = new Random();
        if (Settings.size != 0)
            e.Width = e.Height = Settings.g.Size;
        else
            e.Width = e.Height = 10;
        e.Stroke = Brushes.Black;
        e.Fill = new SolidColorBrush(Color.FromRgb((byte)r.Next(255), (byte)r.Next(255), (byte)r.Next(255))); ;
        Canvas.SetLeft(e, x);
        Canvas.SetTop(e, y);
    }
  }
 }

does anyone have any idea how I do that?

Body:
Change the ellipse to a rectangle with no stroke and fill it with a drawing brush that represents an apple.

Apple graphic taken from xamalot

class Food
    {
        public double x, y;
        public Rectangle e = new Rectangle();

        private SolidColorBrush brush1 = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFB5121B"));
        private SolidColorBrush brush2 = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF4F6E18"));

        private DrawingBrush apple;

        private double size = 20.0;

        public Food(double x, double y)
        {
            this.x = x;
            this.y = y;
            GeometryDrawing a1 = new GeometryDrawing(brush1, null, Geometry.Parse("F1M513.300,368.290C513.300,368.290 530.719,179.903 449.429,135.387 368.139,90.871 273.945,91.516 273.945,91.516 273.945,91.516 228.783,79.903 216.526,80.548 204.269,81.193 125.559,84.419 68.784,142.484 12.009,200.549 4.268,237.322 6.849,285.064 9.430,332.806 34.590,438.613 34.590,438.613 34.590,438.613 70.074,516.677 76.526,521.839 82.978,527.001 122.333,570.871 149.429,576.678 176.525,582.485 234.590,580.549 248.138,578.614 261.686,576.679 339.106,581.194 366.848,576.033 394.590,570.872 475.881,490.870 490.720,461.193 505.559,431.516 513.300,368.290 513.300,368.290z"));
            GeometryDrawing a2 = new GeometryDrawing(brush2, null, Geometry.Parse("F1M435.881,122.484L437.171,113.452 462.332,105.710 463.623,92.807C463.623,92.807 495.881,67.000 497.171,55.388 498.461,43.776 505.559,20.549 505.559,20.549L479.107,16.033C479.107,16.033 424.269,12.807 421.688,12.807 419.107,12.807 395.881,14.742 395.881,14.742L337.171,28.936 290.720,72.807 285.559,78.613 272.656,125.710 253.946,143.129 251.365,121.839C251.365,121.839 242.978,94.097 238.462,94.097 233.946,94.097 232.655,90.871 232.655,90.871L229.429,90.871 216.526,99.258 201.687,111.516 208.139,123.129C208.139,123.129 222.977,134.097 226.203,140.548 229.429,146.999 237.171,163.774 233.945,170.225 230.719,176.676 222.332,192.161 222.332,192.161L241.041,200.548C241.041,200.548 247.492,207.645 260.395,196.677 273.298,185.709 257.169,175.387 257.169,175.387 257.169,175.387 251.362,165.710 261.040,159.903 270.718,154.096 304.267,143.774 314.589,144.419 324.911,145.064 350.718,148.290 361.040,149.580 371.362,150.870 435.881,122.484 435.881,122.484z"));
            GeometryDrawing a3 = new GeometryDrawing(Brushes.Black, null, Geometry.Parse("F1M128.784,96.677C148.139,88.935 174.369,81.601 174.369,81.601 192.987,77.160 211.565,75.052 230.540,78.296 243.012,80.428 260.740,87.167 273.042,86.000 279.480,78.644 278.052,68.304 283.253,60.448 289.458,51.076 294.940,59.933 294.042,67.000 298.067,54.331 338.001,6.529 351.082,18.709 355.593,22.908 420.671,2.572 431.042,0.000 431.254,3.071 430.920,6.071 430.042,9.000 447.617,12.292 466.476,8.608 484.313,10.769 491.850,11.682 502.369,18.105 509.042,12.000 510.861,24.711 509.113,25.330 507.578,37.200 505.575,52.679 495.643,69.019 484.589,79.747 481.237,83.199 477.389,85.950 473.042,88.000 476.148,95.075 479.028,93.481 472.860,101.040 465.707,109.805 455.381,113.436 445.042,117.000 443.998,125.386 466.546,138.834 471.035,145.778 474.307,150.839 498.550,187.608 495.042,187.000 507.285,204.943 506.970,226.532 513.235,245.733 522.462,274.010 518.921,309.492 517.366,338.795 516.019,364.167 516.886,390.178 509.973,413.289 507.449,421.729 494.598,479.776 483.041,479.000 465.660,528.203 414.718,579.661 361.111,583.683 329.023,586.090 297.163,578.453 265.041,583.000 228.602,589.404 195.545,594.889 159.306,584.585 109.315,570.372 66.443,528.234 48.386,479.739 36.691,448.332 21.452,420.930 14.912,387.631 10.008,362.661 8.375,340.614 3.621,315.216 -4.386,272.435 0.070,221.175 25.211,187.212 35.862,172.824 41.077,151.323 58.022,142.155 67.303,137.134 76.285,126.810 85.433,120.915 85.434,120.915 109.429,104.419 128.784,96.677z M414.042,64.000C426.498,46.435 406.256,32.395 410.042,15.000 397.805,14.493 376.430,18.708 370.022,30.011 365.638,37.745 365.836,46.995 363.872,55.425 361.380,66.117 354.186,75.110 352.042,86.000 372.512,78.557 395.099,75.228 414.042,64.000 M424.042,44.000C426.543,35.314 430.940,27.446 434.042,19.000 426.020,18.754 420.768,21.745 414.042,16.000 411.001,25.542 419.895,36.289 424.042,44.000 M486.042,19.000C472.684,19.179 444.659,13.770 437.010,24.751 430.706,33.800 422.828,52.810 422.042,64.000 422.318,61.028 457.493,47.482 462.096,44.739 472.277,38.671 481.678,31.404 490.042,23.000 490.150,23.019 486.233,18.620 486.042,19.000 M440.042,61.000C452.222,62.766 467.215,65.806 479.105,61.050 494.224,55.002 490.026,34.660 497.042,23.000 480.410,39.150 461.330,51.814 440.042,61.000 M346.042,85.000C360.129,68.533 348.792,47.819 340.042,32.000 326.577,39.407 310.909,52.613 309.903,68.758 309.348,77.656 310.249,86.590 309.428,95.476 308.989,100.234 302.330,109.552 304.041,114.000 312.835,99.033 334.394,96.711 346.042,85.000 M350.042,44.000C354.103,48.646 353.819,55.803 357.042,61.000 359.240,51.294 361.521,41.627 364.042,32.000 357.967,34.124 352.835,38.096 350.042,44.000 M450.042,66.000C455.537,84.095 470.575,77.818 478.042,66.000 471.350,60.585 458.358,70.389 450.042,66.000 M454.042,87.000C455.526,85.148 457.193,83.482 459.042,82.000 445.923,68.860 442.985,62.996 423.392,67.247 405.870,71.048 390.012,79.535 373.042,85.000 393.934,85.236 445.185,125.197 461.042,94.000 458.086,92.294 455.752,89.961 454.042,87.000 M298.042,84.000C301.484,86.409 303.150,89.742 303.042,94.000 309.970,90.194 305.458,75.576 304.042,70.000 300.866,74.154 298.866,78.820 298.042,84.000 M253.042,167.000C255.620,156.719 277.769,140.995 285.505,133.386 289.170,129.709 292.900,126.098 296.694,122.554 305.692,114.337 297.166,117.338 300.555,108.030 304.820,96.323 297.702,85.367 288.041,77.999 283.160,91.979 279.528,106.245 277.362,120.899 275.648,132.500 271.666,134.028 266.362,143.800 266.022,144.426 255.032,154.911 255.041,154.999 242.339,144.154 252.806,121.622 241.041,108.999 239.498,119.949 235.243,128.783 223.041,129.999 230.159,139.753 239.442,156.768 237.195,169.056 236.041,175.365 232.919,181.129 231.137,187.251 228.116,197.635 243.199,198.698 251.041,201.000 255.475,189.287 250.187,178.388 253.042,167.000 M265.042,118.000C269.094,104.222 280.259,94.104 259.664,90.569 244.997,88.051 225.689,88.648 211.924,83.869 203.397,80.909 180.969,88.489 172.042,91.000 151.675,96.730 132.840,106.511 114.042,116.000 59.130,143.718 15.553,199.202 11.810,265.090 10.780,283.229 37.230,442.912 46.748,450.542 46.493,450.617 75.058,505.521 78.999,511.549 98.081,540.728 124.864,561.761 154.786,573.244 185.512,585.036 222.415,572.249 254.209,572.179 287.252,572.107 323.348,579.623 356.163,572.754 409.424,561.606 459.076,499.925 483.924,454.159 499.973,424.601 504.615,389.266 506.601,355.349 508.976,314.777 510.741,268.100 499.309,229.172 491.641,203.060 484.325,173.871 465.068,153.539 457.862,145.930 445.945,137.601 436.101,134.470 422.571,130.166 410.572,144.028 396.597,144.031 392.777,144.031 382.531,152.867 374.192,153.647 361.430,154.841 348.647,152.575 336.316,149.477 312.818,143.572 284.786,153.807 265.044,167.000 265.087,170.391 260.293,187.917 269.044,185.000 277.091,182.317 285.950,184.333 294.044,182.000 305.589,178.673 322.379,168.044 330.044,177.000 312.169,181.677 292.999,183.728 276.811,193.246 257.709,204.477 252.581,208.797 233.053,198.284 224.684,193.779 215.928,191.070 205.814,188.840 194.013,186.238 162.420,187.285 154.045,179.000 166.925,178.886 189.962,181.909 199.045,184.000 234.266,192.062 241.788,151.281 216.045,133.000 209.051,128.034 205.179,127.053 200.594,118.534 192.155,102.850 209.268,103.866 218.033,96.492 245.519,73.367 251.513,109.054 258.045,130.001 267.876,129.306 263.289,123.961 265.042,118.000 M404.042,131.000C417.720,127.298 408.380,124.138 401.849,117.237 391.482,106.280 391.701,92.772 373.814,89.802 361.629,87.780 348.714,90.862 337.491,95.545 332.421,97.660 308.279,109.915 310.043,117.001 320.520,113.944 337.908,121.959 347.446,126.279 362.393,133.047 385.319,136.065 404.042,131.000 M231.042,91.000C225.165,95.639 189.601,111.553 209.254,117.255 227.381,122.514 245.094,103.026 231.042,91.000 M424.042,121.000C420.158,119.020 416.825,116.353 414.042,113.000 419.381,110.729 427.969,113.629 431.042,107.000 418.474,105.041 407.407,98.614 395.042,96.000 398.688,106.570 409.105,129.552 424.042,121.000 M216.042,124.000C221.159,124.441 233.190,128.531 232.042,118.000 229.843,121.464 215.554,118.883 216.042,124.000z M289.042,140.000C309.452,138.049 328.829,142.222 349.042,141.000 339.229,118.123 296.925,112.520 289.042,140.000 M364.042,142.000C366.373,146.741 373.152,140.349 375.042,139.000 365.356,138.139 356.896,132.194 347.042,132.000 348.719,138.333 357.071,149.190 364.042,142.000"));
            DrawingGroup innerGroup = new DrawingGroup();
            innerGroup.Children.Add(a3);
            DrawingGroup outerGroup = new DrawingGroup();
            outerGroup.Children.Add(a1);
            outerGroup.Children.Add(a2);
            outerGroup.Children.Add(innerGroup);
            apple = new DrawingBrush();
            apple.Drawing = outerGroup;
        }

        public void SetFoodPosition()
        {
            Random r = new Random();
            if (size != 0)
                e.Width = e.Height = size;
            else
                e.Width = e.Height = 10;
            //e.Stroke = Brushes.Black;
            e.Fill = apple;// new SolidColorBrush(Color.FromRgb((byte)r.Next(255), (byte)r.Next(255), (byte)r.Next(255))); ;
            Canvas.SetLeft(e, x);
            Canvas.SetTop(e, y);
        }
    }


来源: stackexchange

问:
PHP url recognition
How can you check if text typed in from a user is an url?

Lets say I want to check if the text is a url and then check if the string has "youtube.com" in it.  Afterwards, I want to get the portion of the link which is of interest for me between the substrings "watch?v=" and any "&" parameters if they do exist.

答:
```<code>preg_match('#watch\?v=([^&]+)#', $url, $matches);
echo $matches[1];
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP url recognition


问:
Can an echo program in Clojure be built with lazy infinite sequences?
Take the following program as an example:

```<code>(defn echo-ints []
  (doseq [i (->> (BufferedReader. *in*)
                 (line-seq)
                 (map read-string)
                 (take-while integer?))]
    (println i)))
</code>```

The idea is to prompt the user for input and then echo it back if it's an integer. However, in this particular program almost every second input won't be echoed immediately. Instead the program will wait for additional input before processing two inputs at once.

Presumably this a consequence of some performance tweaks happening behind the scenes. However in this instance I'd really like to have an immediate feedback loop. Is there an easy way to accomplish this, or does the logic of the program have to be significantly altered?

(The main motivation here is to pass the infinite sequence of user inputs to another function f that transforms lazy sequences to other lazy sequences. If I wrote some kind of while-loop, I wouldn't be able to use f.)

答:
It is generally not good to mix lazyness with side-effect (printing in this case), since most sequence functions have built-in optimizations that cause unintended effects while still being functionally correct.

Here's a good write up: https://stuartsierra.com/2015/08/25/clojure-donts-lazy-effects

What you are trying to do seems like a good fit for core.async channels. I would think as the problem as 'a stream of user input' instead of 'infinite sequence of user inputs', and 'f transforms lazy sequences to lazy sequences' becomes 'f transform a stream into another stream'. This will allow you to write f as transducers which you can arbitrarily compose.

ContentLicense: CC BY-SA 3.0

Body:
Take the following program as an example:

(defn echo-ints []
  (doseq [i (->> (BufferedReader. *in*)
                 (line-seq)
                 (map read-string)
                 (take-while integer?))]
    (println i)))

The idea is to prompt the user for input and then echo it back if it's an integer. However, in this particular program almost every second input won't be echoed immediately. Instead the program will wait for additional input before processing two inputs at once.

Presumably this a consequence of some performance tweaks happening behind the scenes. However in this instance I'd really like to have an immediate feedback loop. Is there an easy way to accomplish this, or does the logic of the program have to be significantly altered?

(The main motivation here is to pass the infinite sequence of user inputs to another function f that transforms lazy sequences to other lazy sequences. If I wrote some kind of while-loop, I wouldn't be able to use f.)


问:
Redirect www to non-www, http to https and only one Host
I'm looking for a special redirect system (htaccess) for improving SEO and the indexed structure of a website in google.

There are some Domains, who pointing to Website root directory. Therefore the Websites gets delivered by multiple Domains.

Specification for the Redirect System:

http -> https

www -> non-www

redirect to one host

only one 301 redirect (no several redirect behind each others)

Example:

Main Domain: domain-a.com

Goal: https://domain-a.com/XXX

Please look as this example Set

>>> Redirect Examples

答:
Did you try just google same answers like this or this?

Try this:

```<code>RewriteEngine On
  RewriteBase /

  RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</code>```

Body:
Did you try just google same answers like this or this?

Try this:

RewriteEngine On
  RewriteBase /

  RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  RewriteRule ^(.*)$ https://%1/$1 [R=301,L]


问:
Removing Duplicate Rows in a google Spreadsheet from the end row
i find this code for remove duplicate row in google spraedsheet:
from this url:
https://developers.google.com/apps-script/articles/removing_duplicates

```<code>function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();
  var last=sheet.getLastRow();
  var newData = new Array();
  for(i in data){
    //Logger.log(i);
    var row = data[i];
    //Logger.log(row[5]);
    var duplicate = false;
    for(j in newData){
      //Logger.log(newData[j][5]);
      if(row[5] == newData[j][5]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
</code>```

but this function start removing duplicate row from the first row, i want to start removing from the end row of sheet.
How can i do this?

答:
This code is going from Top to bottom i.e., from Row 1 to Row 2 and I guess, you want reverse of this i.e., Bottom to Top , last row to 1st row.

For this result, you can try this code snippet :

```<code>function removeDuplicates() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
    var data = sheet.getRange(1, 1, sheet.getLastRow(), 6).getValues();
    var last=sheet.getLastRow();
    var newData = new Array();
    for(i = data.length - 1; i--; i >= 0){
        //Logger.log(i);
        var row = data[i];
        //Logger.log(row[5]);
        var duplicate = false;
        for(j = newData.length - 1; j--; j >= 0){
            //Logger.log(newData[j][5]);
            if(row[5] == newData[j][5]){
                duplicate = true;
            }
        }
        if(!duplicate){
            newData.unshift(row); //I am trying to insert element in start of array instead of end
        }
    }
    sheet.clearContents();
    sheet.getRange(1, 1, newData.length,newData[0].length).setValues(newData);
}
</code>```

This code is untested. Let me know if this doesn't works or if you have any feedbacks/questions.

Thanks.

Body:
i find this code for remove duplicate row in google spraedsheet:
from this url:
https://developers.google.com/apps-script/articles/removing_duplicates

function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();
  var last=sheet.getLastRow();
  var newData = new Array();
  for(i in data){
    //Logger.log(i);
    var row = data[i];
    //Logger.log(row[5]);
    var duplicate = false;
    for(j in newData){
      //Logger.log(newData[j][5]);
      if(row[5] == newData[j][5]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

but this function start removing duplicate row from the first row, i want to start removing from the end row of sheet.
How can i do this?

Body:
This code is going from Top to bottom i.e., from Row 1 to Row 2 and I guess, you want reverse of this i.e., Bottom to Top , last row to 1st row.

For this result, you can try this code snippet :

function removeDuplicates() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
    var data = sheet.getRange(1, 1, sheet.getLastRow(), 6).getValues();
    var last=sheet.getLastRow();
    var newData = new Array();
    for(i = data.length - 1; i--; i >= 0){
        //Logger.log(i);
        var row = data[i];
        //Logger.log(row[5]);
        var duplicate = false;
        for(j = newData.length - 1; j--; j >= 0){
            //Logger.log(newData[j][5]);
            if(row[5] == newData[j][5]){
                duplicate = true;
            }
        }
        if(!duplicate){
            newData.unshift(row); //I am trying to insert element in start of array instead of end
        }
    }
    sheet.clearContents();
    sheet.getRange(1, 1, newData.length,newData[0].length).setValues(newData);
}

This code is untested. Let me know if this doesn't works or if you have any feedbacks/questions.

Thanks.


问:
How to pause Jssor in another class
I have a slide show program called Jssor which also uses jQuery.  I have links inside the slide show which invoke Fancybox3 to display a text box describing that slide.  I need the slide show to pause while the focus is on Fancybox.  Jssor has a method called $Pause and $Play and I can get it to work (outside of the jQuery class) by using buttons (manually clicking.)  The main issue is that I need it to work without user interaction.  My plan is to put the code into Fancybox.js so it will pause/play the slide show automatically.  I know almost nothing about JavaScript so please keep it simple.

I left out (below) a bunch of code thinking I would make this simple and hoping it’s not needed for this question.  This code does work, I just need to know how to make/invoke the last line (using JS not HTML) without user input.

```<code><script type="text/javascript">
jQuery(document).ready(function ($) {
    // A bunch of code
    //...........................
    var jssor_1_slider = new $JssorSlider$("jssor_1", jssor_1_options);
    function Play() {
        jssor_1_slider.$Play();
    };
    function Pause() {
        jssor_1_slider.$Pause();
    };

    $("#playButton").click(Play);
    $("#pauseButton").click(Pause);
};
</script>
// HTML
<input id="playButton" type="button" value="Play" />
<input id="pauseButton" type="button" value="Pause" />
</code>```

答:
Callbacks are designed for purposes like this. Example:

```<code>$('[data-fancybox="images"]').fancybox({
  onInit : function() {
    jssor_1_slider.$Pause();
  },
  afterClose : function() {
    jssor_1_slider.$Play();
  }
});
</code>```

Obviously, this code should go after you have created jssor_1_slider variable.

Title: How to pause Jssor in another class

Body:
I have a slide show program called Jssor which also uses jQuery.  I have links inside the slide show which invoke Fancybox3 to display a text box describing that slide.  I need the slide show to pause while the focus is on Fancybox.  Jssor has a method called $Pause and $Play and I can get it to work (outside of the jQuery class) by using buttons (manually clicking.)  The main issue is that I need it to work without user interaction.  My plan is to put the code into Fancybox.js so it will pause/play the slide show automatically.  I know almost nothing about JavaScript so please keep it simple.

I left out (below) a bunch of code thinking I would make this simple and hoping it’s not needed for this question.  This code does work, I just need to know how to make/invoke the last line (using JS not HTML) without user input.

// HTML
<input id="playButton" type="button" value="Play" />
<input id="pauseButton" type="button" value="Pause" />

Body:
Callbacks are designed for purposes like this. Example:

$('[data-fancybox="images"]').fancybox({
  onInit : function() {
    jssor_1_slider.$Pause();
  },
  afterClose : function() {
    jssor_1_slider.$Play();
  }
});

Obviously, this code should go after you have created jssor_1_slider variable.


问:
Function is looping infinitely - do/while functions
Goal:

Implement a program that prints out a double half-pyramid of a specified height, per the below.

```<code>$ ./mario
Height: 4
   #  #
  ##  ##
 ###  ###
####  ####
</code>```

Problem:

Have been messing with the code for the past 3 hours or so. I got the first line to work, but everything beyond that was just 2 parallel pillars consisting of a singular hash mark. At present, the program is indefinitely printing a hash mark.

Code:

```<code>int main (void) {
    // user gives height value for pyramid
    // h = height
    int h;
    do {
        printf (
            "How tall do you want your pyramid to be? Please type a number "
            "between 0 and 23.\n");
        h = get_int ();

    } while (h < 0 || h > 23);

    // Left side of pyramid says spaces first, followed by hashes. Two spaces
    // inbetween sides of the pyramid. Right side renders hashes first, then
    // inputs newline character.
    // r = row
    // s = space
    // p = hash
    // q = hash right
    int q;
    int p;
    int s;
    int r;
    for (r = 0; r < h; r++) {
        do {
            do {
                printf (" ");
                s++;
            } while (s < h - r);

            // says spaces

            do {
                printf ("#");
                p++;
            } while (p < r++);

            // says left hashes

            // always print 2 spaces inbetween
            printf ("  "); // two spaces

            do {
                printf ("#");
                q++;
            } while (q < r++);
            // says right hashes

            printf ("\n");
            q = 0;
            p = 0;
            s = 0;
            // reset q,p,s values

        } // end bracket of encompassing 'do' function
        while (r < h);
        //'for' function should execute once, increment 'r' by 1, and repeat
        //until row height becomes height provided by user.

    } // end bracket of for loop

} // end bracket of int main
</code>```

Expected Result:

Program creates pyramid formed by hash symbols and spaces.

Actual Result:

Infinitely looping print function.

答:
A shorter implementation, for your study

```<code>int i,j;
for (i=0 ; i<h ; i++) {            // h lines
    for(j=0 ; j < h+2+i+1 ; j++) { // cover all characters on 1 line
        printf("%s", j<h-i-1 || j<h+2 && j>=h ? " " : "#");
    }
    printf("\n");                  // end of line
}
</code>```

Regarding j<h-i-1 || j<h+2 && j>=h ? " " : "#"

j<h-i-1 spaces before the first #

j<h+2 && j>=h spaces between the #s

?: operator: C ? A : B translates to if C is true give A otherwise give B

Body:
Goal:

Implement a program that prints out a double half-pyramid of a specified height, per the below.

$ ./mario
Height: 4
   #  #
  ##  ##
 ###  ###
####  ####

Problem:

Have been messing with the code for the past 3 hours or so. I got the first line to work, but everything beyond that was just 2 parallel pillars consisting of a singular hash mark. At present, the program is indefinitely printing a hash mark.

Code:

int main (void) {
    // user gives height value for pyramid
    // h = height
    int h;
    do {
        printf (
            "How tall do you want your pyramid to be? Please type a number "
            "between 0 and 23.\n");
        h = get_int ();

    } while (h < 0 || h > 23);

    // Left side of pyramid says spaces first, followed by hashes. Two spaces
    // inbetween sides of the pyramid. Right side renders hashes first, then
    // inputs newline character.
    // r = row
    // s = space
    // p = hash
    // q = hash right
    int q;
    int p;
    int s;
    int r;
    for (r = 0; r < h; r++) {
        do {
            do {
                printf (" ");
                s++;
            } while (s < h - r);

            // says spaces

            do {
                printf ("#");
                p++;
            } while (p < r++);

            // says left hashes

            // always print 2 spaces inbetween
            printf ("  "); // two spaces

            do {
                printf ("#");
                q++;
            } while (q < r++);
            // says right hashes

            printf ("\n");
            q = 0;
            p = 0;
            s = 0;
            // reset q,p,s values

        } // end bracket of encompassing 'do' function
        while (r < h);
        //'for' function should execute once, increment 'r' by 1, and repeat
        //until row height becomes height provided by user.

    } // end bracket of for loop

} // end bracket of int main

Expected Result:

Program creates pyramid formed by hash symbols and spaces.

Actual Result:

Infinitely looping print function.

Body:
A shorter implementation, for your study

int i,j;
for (i=0 ; i<h ; i++) {            // h lines
    for(j=0 ; j < h+2+i+1 ; j++) { // cover all characters on 1 line
        printf("%s", j<h-i-1 || j<h+2 && j>=h ? " " : "#");
    }
    printf("\n");                  // end of line
}

Regarding j<h-i-1 || j<h+2 && j>=h ? " " : "#"

j<h-i-1 spaces before the first #

j<h+2 && j>=h spaces between the #s

?: operator: C ? A : B translates to if C is true give A otherwise give B


问:
I can't build android-27 , tool-27.0.2 with travis.CI
Can any one help me?

Stuck from my side.

https://travis-ci.org/XinyueZ/mvvm-template/jobs/313586340

I can 't build (./gradlew test) it.

my yml is:

```<code>language: android
android:
  components:
    - tools
    - platform-tools
    - build-tools-27.0.2
    - android-27
    - add-on
    - extra
licenses:
    - 'android-sdk-license-.+'
jdk:
    - oraclejdk8
script:
    - ./gradlew :repository:testMockDebugUnitTest :repository:testProdDebugUnitTest :repository:testProdReleaseUnitTest
before_cache:
    - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
cache:
  directories:
    - $HOME/.m2
    - $HOME/.gradle/caches/
    - $HOME/.gradle/wrapper/

    buildToolsVersion = '27.0.2'
</code>```

I have tried 27.0.1  as well, same failed.

I had one or three times successed, just 2 hours later, something went wrong.

same yml,  no change.

See here

答:
It seems Google uploaded a new version of the android-27 package and the checksum is now different and the download fails. For the moment, you need to install it yourself using the sdkmanager CLI instead. Here's what you would need to add to your .travis.yml file:

```<code>before_install:
- yes | sdkmanager "platforms;android-27"
</code>```

Body:
Can any one help me?

Stuck from my side.

https://travis-ci.org/XinyueZ/mvvm-template/jobs/313586340

I can 't build (./gradlew test) it.

my yml is:

language: android
android:
  components:
    - tools
    - platform-tools
    - build-tools-27.0.2
    - android-27
    - add-on
    - extra
licenses:
    - 'android-sdk-license-.+'
jdk:
    - oraclejdk8
script:
    - ./gradlew :repository:testMockDebugUnitTest :repository:testProdDebugUnitTest :repository:testProdReleaseUnitTest
before_cache:
    - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
cache:
  directories:
    - $HOME/.m2
    - $HOME/.gradle/caches/
    - $HOME/.gradle/wrapper/

    buildToolsVersion = '27.0.2'

I have tried 27.0.1  as well, same failed.

I had one or three times successed, just 2 hours later, something went wrong.

same yml,  no change.

See here

Body:
It seems Google uploaded a new version of the android-27 package and the checksum is now different and the download fails. For the moment, you need to install it yourself using the sdkmanager CLI instead. Here's what you would need to add to your .travis.yml file:

before_install:
- yes | sdkmanager "platforms;android-27"


问:
Django autoescape is not working in render_to_string(template)?
I am drafting an email template to users when they successfully updated their passwords.

I used {{ autoescape off }} in the template, which is rendered by using render_to_string().

However, the email content shows the HTML angle brackets directly like this:

Hi user!

Your password is updated successfully!

I am using Django2.0 and my code looks like this:

views.py

```<code>from django.core.mail import send_mail
from django.template.loader import render_to_string

def sendmail(request, title)
    email_title = title
    email_content = render_to_string('template.html',{'username':request.user.username})
    recipient = request.user.email
    send_mail(
            email_title,
            email_content,
            'myemail@email.com',
            [recipient,],
            )
</code>```

template.html

```<code>{{ autoescape off}}
Hi <span style='color:blue'>user! </span>
Your password is updated successfully!
{{ endautoescape }}
</code>```

Is there anything wrong with my code?

Otherwise, is autoescape always on while using render_to_string()?

答:
This has nothing to do with autoescape, which is for rendering variables (it is also a template tag, so you use it with {% autoescape off %}, not {{ autoescape off }}). It is doing nothing at all in your current template.

Your issue is that you're trying to put HTML into the plain text body of an email.

send_mail expects a plain text message body. If you want to have a HTML body then you need to supply a html_message argument:

```<code>send_mail(
    email_title,
    '',  # Empty plain text body - not recommended and you should supply a plain text alternative
    'myemail@email.com',
    [recipient,],
    html_message=email_content,  # This will render as HTML
)
</code>```

Body:
I am drafting an email template to users when they successfully updated their passwords.

I used {{ autoescape off }} in the template, which is rendered by using render_to_string().

However, the email content shows the HTML angle brackets directly like this:

Hi user!

Your password is updated successfully!

I am using Django2.0 and my code looks like this:

views.py

from django.core.mail import send_mail
from django.template.loader import render_to_string

def sendmail(request, title)
    email_title = title
    email_content = render_to_string('template.html',{'username':request.user.username})
    recipient = request.user.email
    send_mail(
            email_title,
            email_content,
            'myemail@email.com',
            [recipient,],
            )

template.html

{{ autoescape off}}
Hi user!
Your password is updated successfully!
{{ endautoescape }}

Is there anything wrong with my code?

Otherwise, is autoescape always on while using render_to_string()?

Body:
This has nothing to do with autoescape, which is for rendering variables (it is also a template tag, so you use it with {% autoescape off %}, not {{ autoescape off }}). It is doing nothing at all in your current template.

Your issue is that you're trying to put HTML into the plain text body of an email.

send_mail expects a plain text message body. If you want to have a HTML body then you need to supply a html_message argument:

send_mail(
    email_title,
    '',  # Empty plain text body - not recommended and you should supply a plain text alternative
    'myemail@email.com',
    [recipient,],
    html_message=email_content,  # This will render as HTML
)


问:
Empty string not equal to empty string in PHP ternary operator expression
Could someone explain me the following?</p>

```<code>$a="";

$a="" ? "" : "muh";

echo $a;
// returns muh
</code>```

答:
It looks you are trying to use Comparison operator ==, but instead you are using an Assignment operator =

Your code is trying to assign $a the result of the expression "" ? "" : "muh". An empty string is evaluated as false and $a is assgined the value of muh.

Let's put some parentheses to make it more obvious:

```<code>//$a equals (if empty string then "" else "muh")
$a = ("" ? "" : "muh");

echo $a; // muh

//$a equals (if $a is equal to empty string then "" else muh)
$a = ($a == "" ? "" : "muh");

echo $a; //
</code>```

Body:
Could someone explain me the following?

$a="";

$a="" ? "" : "muh";

echo $a;
// returns muh

Body:
It looks you are trying to use Comparison operator ==, but instead you are using an Assignment operator =

Your code is trying to assign $a the result of the expression "" ? "" : "muh". An empty string is evaluated as false and $a is assgined the value of muh.

Let's put some parentheses to make it more obvious:

//$a equals (if empty string then "" else "muh")
$a = ("" ? "" : "muh");

echo $a; // muh

//$a equals (if $a is equal to empty string then "" else muh)
$a = ($a == "" ? "" : "muh");

echo $a; //


问:
rollapply in datatable to calculate sums returns NAs
I would like to calculate rolling sums in R. I am using this code to create a data table TT:

```<code>TT <- data.table(ID=c(rep(100,9),rep(200,6)),date=seq(as.Date("1958-04-25"),as.Date("1958-05-9"),by="days"),
             output=c(5,8,NA,6,7,8,NA,12,13,2,14,12,14,14,NA))
</code>```

Here I try to calculate the rolling sums, but the result is only NAs, even though in the first case (ID), the length should be > 7.

```<code>TT[,XX :=
 ifelse(length(output) >= 7,
        rollapply(output, 7, sum, na.rm = TRUE,align = "right",fill = NA_real_),
        rep(NA_real_,length(output))),by=ID]

TT[,length(output),by=ID]
</code>```

What I want to do is calculate rolling sums with a window of 7, if possible, per ID. If not possible (i.e. not enough rows) per ID, I just want to have NAs. I am also open to other solutions.

Body:
I would like to calculate rolling sums in R. I am using this code to create a data table TT:

TT <- data.table(ID=c(rep(100,9),rep(200,6)),date=seq(as.Date("1958-04-25"),as.Date("1958-05-9"),by="days"),
             output=c(5,8,NA,6,7,8,NA,12,13,2,14,12,14,14,NA))

Here I try to calculate the rolling sums, but the result is only NAs, even though in the first case (ID), the length should be > 7.

TT[,XX :=
 ifelse(length(output) >= 7,
        rollapply(output, 7, sum, na.rm = TRUE,align = "right",fill = NA_real_),
        rep(NA_real_,length(output))),by=ID]

TT[,length(output),by=ID]

What I want to do is calculate rolling sums with a window of 7, if possible, per ID. If not possible (i.e. not enough rows) per ID, I just want to have NAs. I am also open to other solutions.

Body:
you can use if and else instead of ifelse. ifelse(test, yes, no) returns a value with the same shape as test, the mode of the result may depend on the value of test.

TT[, XX := if(length(output) >= 7) rollapply(output, 7, sum, na.rm = TRUE, align = "right", fill = NA_real_) else rep(NA_real_, length(output)), by = ID]

     ID       date output XX
 1: 100 1958-04-25      5 NA
 2: 100 1958-04-26      8 NA
 3: 100 1958-04-27     NA NA
 4: 100 1958-04-28      6 NA
 5: 100 1958-04-29      7 NA
 6: 100 1958-04-30      8 NA
 7: 100 1958-05-01     NA 34
 8: 100 1958-05-02     12 41
 9: 100 1958-05-03     13 46
10: 200 1958-05-04      2 NA
11: 200 1958-05-05     14 NA
12: 200 1958-05-06     12 NA
13: 200 1958-05-07     14 NA
14: 200 1958-05-08     14 NA
15: 200 1958-05-09     NA NA


问:
Checkbox issue oncheck function
Please see the following code at first.
I want the particular checkbox (with id cfc1) to not be shown ticked whenever clicking on it.
I have used the onCheck function there. I'm not finding any way to the particular element be shown unchecked whenever clicked on it. I'm trying using the code -

```<code>if(e.currentTarget.id === 'cfc1') {
    document.getElementById(e.currentTarget.id).checked = false;
}
</code>```

but it's not working.

How to do it using the onCheck function?

```<code>import React, {Component} from 'react';
import Checkbox from 'material-ui/Checkbox';

class Checkboxes extends Component {
  constructor() {
     super();
     this.state = {
        checkids:['cfc0', 'cfc1', 'cfc2', 'cfc3']
     };
     this.handleCheck = this.handleCheck.bind(this);
     this.getElements = this.getElements.bind(this);
  }
  getElements() {
     let arr = [];
     this.state.checkids.forEach(function(element) {
        arr.push(
          <Checkbox
             id={element}
             onCheck={this.handleCheck}
          />
        );
     }, this)
     return arr;
  }
  handleCheck(e) {
     console.log(e.currentTarget.id);
     console.log(e.currentTarget.checked);
  }
  render() {
     return(
       <div>
          {this.getElements()}
       </div>
     );
  }
}
export default Checkboxes
</code>```

答:
To get it working for your use case, try having a state variable that maintains the checked information of each element id.

And in the onCheck handler toggle the checkbox for all the boxes except the one desired by setting the state.

WORKING DEMO

```<code>class App extends Component {
  constructor() {
    super();
     this.state = {
        checkids:{
          'cfc0': false,
          'cfc1': false,
          'cfc2': false,
          'cfc3': false
        }
     };
  }

  handleCheck(e) {
     const checkids = {...this.state.checkids};
     checkids[e.target.id] = e.target.id === "cfc1" ? false : !checkids[e.target.id];

     this.setState({checkids});
  }

  getElements() {
     let arr = [];
     Object.keys(this.state.checkids).forEach(function(element, index) {
        arr.push(
          <Checkbox
             key={index}
             id={element}
             checked={this.state.checkids[element]}
             onCheck={this.handleCheck.bind(this)}
          />
        );
     }, this)
     return arr;
  }

  render() {
    return (
      <MuiThemeProvider>
        <div>
          {this.getElements()}
       </div>
      </MuiThemeProvider>
    );
  }
}
</code>```

Title: Checkbox issue oncheck function

Body:
Please see the following code at first.
I want the particular checkbox (with id cfc1) to not be shown ticked whenever clicking on it.
I have used the onCheck function there. I'm not finding any way to the particular element be shown unchecked whenever clicked on it. I'm trying using the code -

if(e.currentTarget.id === 'cfc1') {
    document.getElementById(e.currentTarget.id).checked = false;
}

but it's not working.

How to do it using the onCheck function?

import React, {Component} from 'react';
import Checkbox from 'material-ui/Checkbox';

class Checkboxes extends Component {
  constructor() {
     super();
     this.state = {
        checkids:['cfc0', 'cfc1', 'cfc2', 'cfc3']
     };
     this.handleCheck = this.handleCheck.bind(this);
     this.getElements = this.getElements.bind(this);
  }
  getElements() {
     let arr = [];
     this.state.checkids.forEach(function(element) {
        arr.push(
          <Checkbox
             id={element}
             onCheck={this.handleCheck}
          />
        );
     }, this)
     return arr;
  }
  handleCheck(e) {
     console.log(e.currentTarget.id);
     console.log(e.currentTarget.checked);
  }
  render() {
     return(

          {this.getElements()}

     );
  }
}
export default Checkboxes

Body:
To get it working for your use case, try having a state variable that maintains the checked information of each element id.

And in the onCheck handler toggle the checkbox for all the boxes except the one desired by setting the state.

WORKING DEMO

class App extends Component {
  constructor() {
    super();
     this.state = {
        checkids:{
          'cfc0': false,
          'cfc1': false,
          'cfc2': false,
          'cfc3': false
        }
     };
  }

  handleCheck(e) {
     const checkids = {...this.state.checkids};
     checkids[e.target.id] = e.target.id === "cfc1" ? false : !checkids[e.target.id];

     this.setState({checkids});
  }

  getElements() {
     let arr = [];
     Object.keys(this.state.checkids).forEach(function(element, index) {
        arr.push(
          <Checkbox
             key={index}
             id={element}
             checked={this.state.checkids[element]}
             onCheck={this.handleCheck.bind(this)}
          />
        );
     }, this)
     return arr;
  }

  render() {
    return (
      <MuiThemeProvider>
        <div>
          {this.getElements()}
       </div>
      </MuiThemeProvider>
    );
  }
}


问:
Newbie - cant compile objective c with GNUStep
I have a question relating to this question Unable to Compile Objective C using Gnustep on windows

I am trying to compile my first objective c app on Windows.
The file is hello.m (all files below created in Visual Studio)

```<code>#import <../Program Files/GNUstep/System/Library/Headers/Foundation/Foundation.h>

int main(int argc, const char* argv[])
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSLog(@"Hello from Hello.m!");

    [pool release];
    return 0;
}
</code>```

In order to compile it I have a GNUmakefile in the same directory:

```<code>include $(GNUSTEP_MAKEFILES)/common.make
TOOL_NAME = hello
YourProg_OBJC_FILES = hello.m
include $(GNUSTEP_MAKEFILES)/tool.make
</code>```

As I understand it, when I run make the command "make" the GNUmakefile will execute.

When I do this in the GNUStep shell I get an error

```<code>GNUmakefile:1 *** missing separator. Stop.
</code>```

I tried adding a tab to the first line. This did nothing. Yes, I am sure it was a tab, not a space.

答:
make is complaining about your makefile, so you probably have a syntax error somewhere.

See: http://www.gnu.org/software/automake/manual/make/Error-Messages.html:

This means that make could not understand much of anything about the makefile line it just read. GNU make looks for various separators (:, =, recipe prefix characters, etc.) to indicate what kind of line it's parsing. This message means it couldn't find a valid one.

Try you might try compiling directly:

```<code>gcc -o hello hello.m -I/c/GNUstep/GNUstep/System/Library/Headers \
    -L /c/GNUstep/GNUstep/System/Library/Libraries -lobjc -lgnustep-base \
    -fconstant-string-class=NSConstantString
</code>```

Body:
I have a question relating to this question Unable to Compile Objective C using Gnustep on windows

I am trying to compile my first objective c app on Windows.
The file is hello.m (all files below created in Visual Studio)

#import <../Program Files/GNUstep/System/Library/Headers/Foundation/Foundation.h>

int main(int argc, const char* argv[])
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSLog(@"Hello from Hello.m!");

    [pool release];
    return 0;
}

In order to compile it I have a GNUmakefile in the same directory:

include $(GNUSTEP_MAKEFILES)/common.make
TOOL_NAME = hello
YourProg_OBJC_FILES = hello.m
include $(GNUSTEP_MAKEFILES)/tool.make

As I understand it, when I run make the command "make" the GNUmakefile will execute.

When I do this in the GNUStep shell I get an error

GNUmakefile:1 *** missing separator. Stop.

I tried adding a tab to the first line. This did nothing. Yes, I am sure it was a tab, not a space.

Body:
make is complaining about your makefile, so you probably have a syntax error somewhere.

See: http://www.gnu.org/software/automake/manual/make/Error-Messages.html:

This means that make could not understand much of anything about the makefile line it just read. GNU make looks for various separators (:, =, recipe prefix characters, etc.) to indicate what kind of line it's parsing. This message means it couldn't find a valid one.

Try you might try compiling directly:

gcc -o hello hello.m -I/c/GNUstep/GNUstep/System/Library/Headers \
    -L /c/GNUstep/GNUstep/System/Library/Libraries -lobjc -lgnustep-base \
    -fconstant-string-class=NSConstantString


问:
How to convert XElement object into a dataset or datatable?
I'm accessing a SharePoint(2007) list through a service reference of lists.asmx created in my console application. Console application is created in VS2012 and .Net 4.5 framework.

```<code>ListsSoapClient proxy1 = new ListsSoapClient();
proxy1.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
proxy1.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
string listName = "List_For_Test";
DataSet ds1 = new DataSet();
XElement ndQuery = new XElement("Query", "");
XElement ndViewFields = new XElement("ViewFields", "");
XElement ndQueryOptions = new XElement("QueryOptions", "");
XElement items = proxy1.GetListItems(listName, null, ndQuery, ndViewFields, null, ndQueryOptions, null);
ds1 = XElementToDataSet(items);
</code>```

I need to convert the XML returned in items XElement to dataset/datatable and pass it to a stored procedure written in SQL Server 2008 R2.

I tried using following code but it gave me error

```<code>    XElement setup = (from p in x.Descendants() select p).First();
    foreach (XElement xe in setup.Descendants()) // build your DataTable
    dt.Columns.Add(new DataColumn(xe.Name.ToString(), typeof(string)));
    // on second iteration gave error that "'{#RowsetSchema}row'" column already existing.
</code>```

This is the XML stream returned from GetListItems() webservice method call

<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
  xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
  xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema"
  xmlns="http://schemas.microsoft.com/sharepoint/soap/"> <rs:data
  ItemCount="2"> <z:row
  ows_ContentTypeId="0x01006B57C3DFF39626458A729755ABF3A370"
  ows_Title="Item#1" ows_ListID="1.00000000000000"
  ows_Loan_x0020_Number="1234.00000000000" ows_ID="2"
  ows_ContentType="Item" ows_Modified="2014-04-01 10:06:38"
  ows_Created="2014-04-01 10:06:38" ows_Author="7017;#, Khushi"
  ows_Editor="7017;#, Khushi" ows_owshiddenversion="1"
  ows_WorkflowVersion="1" ows__UIVersion="512"
  ows__UIVersionString="1.0" ows_Attachments="0"
  ows__ModerationStatus="0" ows_LinkTitleNoMenu="Item#1"
  ows_LinkTitle="Item#1" ows_SelectTitle="2"
  ows_Order="200.000000000000"
  ows_GUID="{2832ED2B-A45D-4950-8E0E-EEB3E31199AF}" ows_FileRef="2;#
  List_For_Test/2_.000" ows_FileDirRef="2;#/List_For_Test"
  ows_Last_x0020_Modified="2;#2014-04-01 10:06:38"
  ows_Created_x0020_Date="2;#2014-04-01 10:06:38" ows_FSObjType="2;#0"
  ows_PermMask="0x7fffffffffffffff" ows_FileLeafRef="2;#2_.000"
  ows_UniqueId="2;#{F3336392-74F7-45C2-A175-EF36DA219812}"
  ows_ProgId="2;#"
  ows_ScopeId="2;#{E9E1B331-7993-4586-93DC-3690EBEBAD9E}"
  ows__EditMenuTableStart="2_.000" ows__EditMenuTableEnd="2"
  ows_LinkFilenameNoMenu="2_.000" ows_LinkFilename="2_.000"
  ows_ServerUrl="/ List_For_Test/2_.000"
  ows_EncodedAbsUrl="Lists/List_For_Test/2_.000" ows_BaseName="2_"
  ows_MetaInfo="2;#" ows__Level="1" ows__IsCurrentVersion="1" />

  <z:row ows_ContentTypeId="0x01006B57C3DFF39626458A729755ABF3A370"
  ows_Title="Item#2" ows_ListID="2.00000000000000"
  ows_Loan_x0020_Number="5678.00000000000" ows_ID="3"
  ows_ContentType="Item" ows_Modified="2014-04-01 10:06:53"
  ows_Created="2014-04-01 10:06:53" ows_Author="7017;#Khushi"
  ows_Editor="7017;#, Khushi" ows_owshiddenversion="1"
  ows_WorkflowVersion="1" ows__UIVersion="512"
  ows__UIVersionString="1.0" ows_Attachments="0"
  ows__ModerationStatus="0" ows_LinkTitleNoMenu="Item#2"
  ows_LinkTitle="Item#2" ows_SelectTitle="3"
  ows_Order="300.000000000000"
  ows_GUID="{8A6C6A66-A795-4054-B793-789B739EA881}" ows_FileRef="3;#
  /List_For_Test/3_.000" ows_FileDirRef="3;# /List_For_Test"
  ows_Last_x0020_Modified="3;#2014-04-01 10:06:53"
  ows_Created_x0020_Date="3;#2014-04-01 10:06:53" ows_FSObjType="3;#0"
  ows_PermMask="0x7fffffffffffffff" ows_FileLeafRef="3;#3_.000"
  ows_UniqueId="3;#{434E5737-5591-4A02-91E5-B2C7A2EFF2B3}"
  ows_ProgId="3;#"
  ows_ScopeId="3;#{E9E1B331-7993-4586-93DC-3690EBEBAD9E}"
  ows__EditMenuTableStart="3_.000" ows__EditMenuTableEnd="3"
  ows_LinkFilenameNoMenu="3_.000" ows_LinkFilename="3_.000"
  ows_ServerUrl="/List_For_Test/3_.000"
  ows_EncodedAbsUrl="Lists/List_For_Test/3_.000" ows_BaseName="3_"
  ows_MetaInfo="3;#" ows__Level="1" ows__IsCurrentVersion="1" />

  </rs:data>   </listitems>

答:
Please check it here...

```<code>public static class XElementExtensions {
public static DataTable ToDataTable(this XElement element) {
    DataSet ds = new DataSet();
    string rawXml = element.ToString();
    ds.ReadXml(new StringReader(rawXml));
    return ds.Tables[0];
}

public static DataTable ToDataTable(this IEnumerable<XElement> elements) {
    return ToDataTable(new XElement("Root", elements));
}
}
</code>```

Use it like this:

```<code>protected void Page_Load(object sender, EventArgs e) {
string xmlFile = Server.MapPath("~/Data.xml");
XDocument document = XDocument.Load(xmlFile);
var booksQuery = from b in document.Elements("NewDataSet").Elements("Table")
                  select b;

DataTable table = booksQuery.ToDataTable();
GridView1.DataSource = table;
GridView1.DataBind();
</code>```

}

Body:
I'm accessing a SharePoint(2007) list through a service reference of lists.asmx created in my console application. Console application is created in VS2012 and .Net 4.5 framework.

ListsSoapClient proxy1 = new ListsSoapClient();
proxy1.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
proxy1.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
string listName = "List_For_Test";
DataSet ds1 = new DataSet();
XElement ndQuery = new XElement("Query", "");
XElement ndViewFields = new XElement("ViewFields", "");
XElement ndQueryOptions = new XElement("QueryOptions", "");
XElement items = proxy1.GetListItems(listName, null, ndQuery, ndViewFields, null, ndQueryOptions, null);
ds1 = XElementToDataSet(items);

I need to convert the XML returned in items XElement to dataset/datatable and pass it to a stored procedure written in SQL Server 2008 R2.

I tried using following code but it gave me error

    XElement setup = (from p in x.Descendants() select p).First();
    foreach (XElement xe in setup.Descendants()) // build your DataTable
    dt.Columns.Add(new DataColumn(xe.Name.ToString(), typeof(string)));
    // on second iteration gave error that "'{#RowsetSchema}row'" column already existing.

This is the XML stream returned from GetListItems() webservice method call

<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
  xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
  xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema"
  xmlns="http://schemas.microsoft.com/sharepoint/soap/"> <rs:data
  ItemCount="2"> <z:row
  ows_ContentTypeId="0x01006B57C3DFF39626458A729755ABF3A370"
  ows_Title="Item#1" ows_ListID="1.00000000000000"
  ows_Loan_x0020_Number="1234.00000000000" ows_ID="2"
  ows_ContentType="Item" ows_Modified="2014-04-01 10:06:38"
  ows_Created="2014-04-01 10:06:38" ows_Author="7017;#, Khushi"
  ows_Editor="7017;#, Khushi" ows_owshiddenversion="1"
  ows_WorkflowVersion="1" ows__UIVersion="512"
  ows__UIVersionString="1.0" ows_Attachments="0"
  ows__ModerationStatus="0" ows_LinkTitleNoMenu="Item#1"
  ows_LinkTitle="Item#1" ows_SelectTitle="2"
  ows_Order="200.000000000000"
  ows_GUID="{2832ED2B-A45D-4950-8E0E-EEB3E31199AF}" ows_FileRef="2;#
  List_For_Test/2_.000" ows_FileDirRef="2;#/List_For_Test"
  ows_Last_x0020_Modified="2;#2014-04-01 10:06:38"
  ows_Created_x0020_Date="2;#2014-04-01 10:06:38" ows_FSObjType="2;#0"
  ows_PermMask="0x7fffffffffffffff" ows_FileLeafRef="2;#2_.000"
  ows_UniqueId="2;#{F3336392-74F7-45C2-A175-EF36DA219812}"
  ows_ProgId="2;#"
  ows_ScopeId="2;#{E9E1B331-7993-4586-93DC-3690EBEBAD9E}"
  ows__EditMenuTableStart="2_.000" ows__EditMenuTableEnd="2"
  ows_LinkFilenameNoMenu="2_.000" ows_LinkFilename="2_.000"
  ows_ServerUrl="/ List_For_Test/2_.000"
  ows_EncodedAbsUrl="Lists/List_For_Test/2_.000" ows_BaseName="2_"
  ows_MetaInfo="2;#" ows__Level="1" ows__IsCurrentVersion="1" />

  <z:row ows_ContentTypeId="0x01006B57C3DFF39626458A729755ABF3A370"
  ows_Title="Item#2" ows_ListID="2.00000000000000"
  ows_Loan_x0020_Number="5678.00000000000" ows_ID="3"
  ows_ContentType="Item" ows_Modified="2014-04-01 10:06:53"
  ows_Created="2014-04-01 10:06:53" ows_Author="7017;#Khushi"
  ows_Editor="7017;#, Khushi" ows_owshiddenversion="1"
  ows_WorkflowVersion="1" ows__UIVersion="512"
  ows__UIVersionString="1.0" ows_Attachments="0"
  ows__ModerationStatus="0" ows_LinkTitleNoMenu="Item#2"
  ows_LinkTitle="Item#2" ows_SelectTitle="3"
  ows_Order="300.000000000000"
  ows_GUID="{8A6C6A66-A795-4054-B793-789B739EA881}" ows_FileRef="3;#
  /List_For_Test/3_.000" ows_FileDirRef="3;# /List_For_Test"
  ows_Last_x0020_Modified="3;#2014-04-01 10:06:53"
  ows_Created_x0020_Date="3;#2014-04-01 10:06:53" ows_FSObjType="3;#0"
  ows_PermMask="0x7fffffffffffffff" ows_FileLeafRef="3;#3_.000"
  ows_UniqueId="3;#{434E5737-5591-4A02-91E5-B2C7A2EFF2B3}"
  ows_ProgId="3;#"
  ows_ScopeId="3;#{E9E1B331-7993-4586-93DC-3690EBEBAD9E}"
  ows__EditMenuTableStart="3_.000" ows__EditMenuTableEnd="3"
  ows_LinkFilenameNoMenu="3_.000" ows_LinkFilename="3_.000"
  ows_ServerUrl="/List_For_Test/3_.000"
  ows_EncodedAbsUrl="Lists/List_For_Test/3_.000" ows_BaseName="3_"
  ows_MetaInfo="3;#" ows__Level="1" ows__IsCurrentVersion="1" />

  </rs:data>   </listitems>

Body:
Please check it here...

public static class XElementExtensions {
public static DataTable ToDataTable(this XElement element) {
    DataSet ds = new DataSet();
    string rawXml = element.ToString();
    ds.ReadXml(new StringReader(rawXml));
    return ds.Tables[0];
}

public static DataTable ToDataTable(this IEnumerable<XElement> elements) {
    return ToDataTable(new XElement("Root", elements));
}
}

Use it like this:

protected void Page_Load(object sender, EventArgs e) {
string xmlFile = Server.MapPath("~/Data.xml");
XDocument document = XDocument.Load(xmlFile);
var booksQuery = from b in document.Elements("NewDataSet").Elements("Table")
                  select b;

DataTable table = booksQuery.ToDataTable();
GridView1.DataSource = table;
GridView1.DataBind();

}


问:
Getting 'DatabaseError' object has no attribute 'message' in DJango
I am trying to run the following code here to save information to the database. I have seen other messages - but - it appears that the solutions are for older versions of Python/DJango (as they do not seem to be working on the versions I am using now: Python 3.6.3 and DJango 1.11.7

```<code>if form.is_valid():
    try:
        item = form.save(commit=False)
        item.tenantid = tenantid
        item.save()
        message = 'saving data was successful'
    except DatabaseError as e:
        message = 'Database Error: ' + str(e.message)
</code>```

When doing so, I get an error message the error message listed below. How can I fix this so I can get the message found at the DB level printed out?

```<code>'DatabaseError' object has no attribute 'message'
Request Method:
POST
Request URL:
http://127.0.0.1:8000/storeowner/edit/
Django Version:
1.11.7
Exception Type:
AttributeError
Exception Value:
'DatabaseError' object has no attribute 'message'
Exception Location:
C:\WORK\AppPython\ContractorsClubSubModuleDEVELOP\libmstr\storeowner\views.py in edit_basic_info, line 40
Python Executable:
C:\WORK\Software\Python64bitv3.6\python.exe
Python Version:
3.6.3
Python Path:
['C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP',
 'C:\\WORK\\Software\\OracleInstantClient64Bit\\instantclient_12_2',
 'C:\\WORK\\Software\\Python64bitv3.6\\python36.zip',
 'C:\\WORK\\Software\\Python64bitv3.6\\DLLs',
 'C:\\WORK\\Software\\Python64bitv3.6\\lib',
 'C:\\WORK\\Software\\Python64bitv3.6',
 'C:\\Users\\dgmufasa\\AppData\\Roaming\\Python\\Python36\\site-packages',
 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libintgr',
 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libmstr',
 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libtrans',
 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libintgr',
 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libmstr',
 'C:\\WORK\\TRASH\\tempforcustomer\\tempforcustomer\\libtempmstr',
 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libtrans',
 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages',
 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages\\django-1.11.7-py3.6.egg',
 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages\\pytz-2017.3-py3.6.egg']
Server time:
Sat, 9 Dec 2017 08:42:49 +0000
</code>```

答:
Just change

```<code>str(e.message)
</code>```

to

```<code>str(e)
</code>```

Body:
I am trying to run the following code here to save information to the database. I have seen other messages - but - it appears that the solutions are for older versions of Python/DJango (as they do not seem to be working on the versions I am using now: Python 3.6.3 and DJango 1.11.7

if form.is_valid():
    try:
        item = form.save(commit=False)
        item.tenantid = tenantid
        item.save()
        message = 'saving data was successful'
    except DatabaseError as e:
        message = 'Database Error: ' + str(e.message)

When doing so, I get an error message the error message listed below. How can I fix this so I can get the message found at the DB level printed out?

'DatabaseError' object has no attribute 'message'
Request Method:
POST
Request URL:
http://127.0.0.1:8000/storeowner/edit/
Django Version:
1.11.7
Exception Type:
AttributeError
Exception Value:
'DatabaseError' object has no attribute 'message'
Exception Location:
C:\WORK\AppPython\ContractorsClubSubModuleDEVELOP\libmstr\storeowner\views.py in edit_basic_info, line 40
Python Executable:
C:\WORK\Software\Python64bitv3.6\python.exe
Python Version:
3.6.3
Python Path:
['C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP',
 'C:\\WORK\\Software\\OracleInstantClient64Bit\\instantclient_12_2',
 'C:\\WORK\\Software\\Python64bitv3.6\\python36.zip',
 'C:\\WORK\\Software\\Python64bitv3.6\\DLLs',
 'C:\\WORK\\Software\\Python64bitv3.6\\lib',
 'C:\\WORK\\Software\\Python64bitv3.6',
 'C:\\Users\\dgmufasa\\AppData\\Roaming\\Python\\Python36\\site-packages',
 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libintgr',
 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libmstr',
 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libtrans',
 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libintgr',
 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libmstr',
 'C:\\WORK\\TRASH\\tempforcustomer\\tempforcustomer\\libtempmstr',
 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libtrans',
 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages',
 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages\\django-1.11.7-py3.6.egg',
 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages\\pytz-2017.3-py3.6.egg']
Server time:
Sat, 9 Dec 2017 08:42:49 +0000

Body:
Just change

str(e.message)

to

str(e)


问:
How to find elements in webview in android using appium
I am new in automation testing . I am trying to find elements in webview in Android app using appium .
Below is code i am using but I am not able to find say div using its id

```<code>private AppiumDriver<WebElement> driver;

@Before
public void setUp() throws Exception {
    // set up appium

}
@After
public void tearDown() throws Exception {
    driver.quit();
}

@Test
public void webView() throws InterruptedException {

     DesiredCapabilities capabilities = new DesiredCapabilities();
     capabilities.setCapability("deviceName","Android Emulator");

     capabilities.setCapability("appPackage", "com.hokucampusaffairs");
     capabilities.setCapability("appActivity", "com.mybeeps.DashboardActivity");
     try {
        driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Thread.sleep(6000);
   Set<String> contextNames = driver.getContextHandles();
    for (String contextName : contextNames) {
      System.out.println(contextName);
      if (contextName.contains("WEBVIEW")){
        driver.context(contextName);
      }
    }
 String pagesource=   driver.getPageSource();
 String  url=   driver.getCurrentUrl();
 try {
    WebElement inputField = **driver.findElement(By.id("top-container"));**
    inputField.click();
 }
 catch(Exception e)
 {
     e.printStackTrace();
 }

}
</code>```

Code in bold is not finding div using its id . Also findelementbyTag is only finding parent elements .

I am using latest version of appium /Android sdk/java 1.8

答:
Exception gives you the answer - no element found with id='top-container'

Make sure you switch driver to webview

Try other locator strategies, e.g. Xpath

For webview inspection you can use chrome dev tools: https://developers.google.com/web/tools/chrome-devtools/remote-debugging/webviews

Body:
I am new in automation testing . I am trying to find elements in webview in Android app using appium .
Below is code i am using but I am not able to find say div using its id

private AppiumDriver<WebElement> driver;

@Before
public void setUp() throws Exception {
    // set up appium

}
@After
public void tearDown() throws Exception {
    driver.quit();
}

@Test
public void webView() throws InterruptedException {

     DesiredCapabilities capabilities = new DesiredCapabilities();
     capabilities.setCapability("deviceName","Android Emulator");

     capabilities.setCapability("appPackage", "com.hokucampusaffairs");
     capabilities.setCapability("appActivity", "com.mybeeps.DashboardActivity");
     try {
        driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Thread.sleep(6000);
   Set<String> contextNames = driver.getContextHandles();
    for (String contextName : contextNames) {
      System.out.println(contextName);
      if (contextName.contains("WEBVIEW")){
        driver.context(contextName);
      }
    }
 String pagesource=   driver.getPageSource();
 String  url=   driver.getCurrentUrl();
 try {
    WebElement inputField = **driver.findElement(By.id("top-container"));**
    inputField.click();
 }
 catch(Exception e)
 {
     e.printStackTrace();
 }

}

Code in bold is not finding div using its id . Also findelementbyTag is only finding parent elements .

I am using latest version of appium /Android sdk/java 1.8


问:
multiprocessing for keras model predict with single GPU
Background

I want to predict pathology images using keras with Inception-Resnet_v2. I have trained the model already and got a .hdf5 file. Because the pathology image is very large (for example: 20,000 x 20,000 pixels), so I have to scan the image to get small patches for prediction.

I want to speed up the prediction procedure using multiprocessing lib with python2.7. The main idea is using different subprocesses to scan different lines and then sending patches to model.

I saw somebody suggests importing keras and loading model in subprocesses. But I don't think it is suitable for my task. Loading model usingkeras.models.load_model() one time will take about 47s, which is very time-consuming. So I can't reload the model every time when I start a new subprocess.

Question

My question is can I load the model in my main process and pass it as a parameter to subprocesses?

I have tried two methods but both of them didn't work.

Method 1. Using multiprocessing.Pool

The code is :

```<code>import keras
from keras.models import load_model
import multiprocessing

def predict(num,model):
    print dir(model)
    print num
    model.predict("image data, type:list")

if __name__ == '__main__':
    model = load_model("path of hdf5 file")
    list = [(1,model),(2,model),(3,model),(4,model),(5,model),(6,model)]
    pool = multiprocessing.Pool(4)
    pool.map(predict,list)
    pool.close()
    pool.join()
</code>```

The output is

```<code>cPickle.PicklingError: Can't pickle <type 'module'>: attribute lookup __builtin__.module failed
</code>```

I searched the error and found Pool can't map unpickelable parameters, so I try method 2.

Method 2. Using multiprocessing.Process

The code is

```<code>import keras
from keras.models import load_model
import multiprocessing

def predict(num,model):
    print num
    print dir(model)
    model.predict("image data, type:list")

if __name__ == '__main__':
    model = load_model("path of hdf5 file")
    list = [(1,model),(2,model),(3,model),(4,model),(5,model),(6,model)]
    proc = []
    for i in range(4):
        proc.append(multiprocessing.Process(predict, list[i]))
        proc[i].start()
    for i in range(4):
        proc[i].join()
</code>```

In Method 2, I can print dir(model). I think it means the model is passed to subprocesses successfully. But I got this error

```<code>E tensorflow/stream_executor/cuda/cuda_driver.cc:1296] failed to enqueue async memcpy from host to device: CUDA_ERROR_NOT_INITIALIZED; GPU dst: 0x13350b2200; host src: 0x2049e2400; size: 4=0x4
</code>```

The environment which I use:

Ubuntu 16.04, python 2.7

keras 2.0.8 (tensorflow backend)

one Titan X, Driver version 384.98, CUDA 8.0

Looking forward to reply! Thanks!

答:
Maybe you can use apply_async() instead of Pool()

and you can find more details here:

Python multiprocessing pickling error

Body:
Background

I want to predict pathology images using keras with Inception-Resnet_v2. I have trained the model already and got a .hdf5 file. Because the pathology image is very large (for example: 20,000 x 20,000 pixels), so I have to scan the image to get small patches for prediction.

I want to speed up the prediction procedure using multiprocessing lib with python2.7. The main idea is using different subprocesses to scan different lines and then sending patches to model.

I saw somebody suggests importing keras and loading model in subprocesses. But I don't think it is suitable for my task. Loading model usingkeras.models.load_model() one time will take about 47s, which is very time-consuming. So I can't reload the model every time when I start a new subprocess.

Question

My question is can I load the model in my main process and pass it as a parameter to subprocesses?

I have tried two methods but both of them didn't work.

Method 1. Using multiprocessing.Pool

The code is :

import keras
from keras.models import load_model
import multiprocessing

def predict(num,model):
    print dir(model)
    print num
    model.predict("image data, type:list")

if __name__ == '__main__':
    model = load_model("path of hdf5 file")
    list = [(1,model),(2,model),(3,model),(4,model),(5,model),(6,model)]
    pool = multiprocessing.Pool(4)
    pool.map(predict,list)
    pool.close()
    pool.join()

The output is

cPickle.PicklingError: Can't pickle <type 'module'>: attribute lookup __builtin__.module failed

I searched the error and found Pool can't map unpickelable parameters, so I try method 2.

Method 2. Using multiprocessing.Process

The code is

import keras
from keras.models import load_model
import multiprocessing

def predict(num,model):
    print num
    print dir(model)
    model.predict("image data, type:list")

if __name__ == '__main__':
    model = load_model("path of hdf5 file")
    list = [(1,model),(2,model),(3,model),(4,model),(5,model),(6,model)]
    proc = []
    for i in range(4):
        proc.append(multiprocessing.Process(predict, list[i]))
        proc[i].start()
    for i in range(4):
        proc[i].join()

In Method 2, I can print dir(model). I think it means the model is passed to subprocesses successfully. But I got this error

E tensorflow/stream_executor/cuda/cuda_driver.cc:1296] failed to enqueue async memcpy from host to device: CUDA_ERROR_NOT_INITIALIZED; GPU dst: 0x13350b2200; host src: 0x2049e2400; size: 4=0x4

The environment which I use:

Ubuntu 16.04, python 2.7

keras 2.0.8 (tensorflow backend)

one Titan X, Driver version 384.98, CUDA 8.0

Looking forward to reply! Thanks!


问:
How can I create expression or vector function handle, then plot it?
How can I create vector function handle (anonymous function) with product a scalar value, then plot result. Clearly, I want to plot this formula

```<code>Let f(x,ym)= (1-exp(x-ym)/h); and
iX(x)=1/6.f(x,ym(1))+
      7/6.f(x,ym(2))+
     25/6.f(x,ym(3))+
     43/6.f(x,ym(4));

iY(x)=1/5.f(x,ym(1))+
      2/5.f(x,ym(2))+
     14/5.f(x,ym(3))+
      4/5.f(x,ym(4));
</code>```

This code without loop but give  me :'' Error using plot Conversion to double from sym is not possible''.

```<code>clear all;clc;a=0;b=2;n=3;h=(b-a)/n;ym=a:h:b;
X=[ 1/6, 7/6, 25/6,43/6];  % Data
Y=[ 1/5, 2/5, 14/5,14/5];
f=@(x,ym) (1-exp(x-ym)/h);
% with syms
syms x;
iX=f(x,ym(1:length(ym))).*X; % result iX= [f.1/6 , f.7/6 , f.25/6 , f.43/6]
iY=f(x,ym(1:length(ym))).*Y;
iFx= sum(iX);iFy=sum(iY);   % result  iFx= f.1/6 + f.7/6 + f.25/6 + f.43/6
x=ym;
plot(x,iFx,'r+');hold on;plot(x,iFy,'og');
</code>```

Moreover, I tired to use a alternate codes with loop condition but the error persists as conversion to logical from sym is not possible.

```<code>% clear all;clc
% a=0;b=2;n=3;h=(b-a)/n;ym=a:h:b;
% %
% X=[ 1/6, 7/6, 25/6,43/6]; % Data
% Y=[ 1/5, 2/5, 14/5,4/5];
% %
% f=@(x,ym) (1-exp(x-ym)/h);
% %
% syms x  %double(subs(x))
% iX=cell(1,length(ym));iY=cell(1,length(ym)); %  cell, iX{k} and iY{k}
% % iX=zeros(1,length(ym));iY=zeros(1,length(ym));
% for k=1:length(ym)
% %          iX(k) =   f(x,ym(k)).*X(k);
% %          iY(k) =   f(x,ym(k)).*Y(k);
%            iX{k} = @(x,k)  f(x,ym(k)).*X(k);
%            iY{k} = @(x,k)  f(x,ym(k)).*Y(k);
%            iX(x,k);
% end
% whos
% x=ym;
% plot(x,iX{:},'r:');hold on;plot(x,iY{:},'b--');
</code>```

please, how can I fix it?

答:
You can't directly call plot(x,iFx) because iFx (and iFy) are symbolic variables depending on x and not the output from actually puting some real values into them. The easiest way is to fix this is to a) convert the symbolic variables to symbolic functions using symfun(formula,variables) and b) to then call said function with the values you want to plot them against:

```<code>clear all;clc;a=0;b=2;n=3;h=(b-a)/n;ym=a:h:b;
X=[ 1/6, 7/6, 25/6,43/6];  % Data
Y=[ 1/5, 2/5, 14/5,14/5];
f=@(x,ym) (1-exp(x-ym)/h);
% with syms
syms x;
iX=f(x,ym(1:length(ym))).*X; % result iX= [f.1/6 , f.7/6 , f.25/6 , f.43/6]
iY=f(x,ym(1:length(ym))).*Y;
iFx= sum(iX);iFy=sum(iY);   % result  iFx= f.1/6 + f.7/6 + f.25/6 + f.43/6

% same code until here

% step a) turn to symbolic function
iFx = symfun(iFx,x); iFy = symfun(iFy,x);

% step b) call the function with the "x" value of the plot.
plot(ym,iFx(ym),'r+');
hold on;
plot(ym,iFy(ym),'og');
</code>```

Edit:

Sure, you can do the same thing with matlabFunction:

```<code>iFx = matlabFunction(iFx); iFy = matlabFunction(iFy);
</code>```

For a discussion about symfun vs matlabFunction I refer to: matlab symfun vs anonymous function

TL;DR : matlabFunction returns an anonymous function which is usually faster, but symbolic functions are more flexible. But in this case it won't matter either way because the function is quite simple and the number of evaluated data points very little; therefore it will compute almost instantly anyways. But it's probably good practice to use matlabFunction.

Body:
How can I create vector function handle (anonymous function) with product a scalar value, then plot result. Clearly, I want to plot this formula

Let f(x,ym)= (1-exp(x-ym)/h); and
iX(x)=1/6.f(x,ym(1))+
      7/6.f(x,ym(2))+
     25/6.f(x,ym(3))+
     43/6.f(x,ym(4));

iY(x)=1/5.f(x,ym(1))+
      2/5.f(x,ym(2))+
     14/5.f(x,ym(3))+
      4/5.f(x,ym(4));

This code without loop but give  me :'' Error using plot Conversion to double from sym is not possible''.

clear all;clc;a=0;b=2;n=3;h=(b-a)/n;ym=a:h:b;
X=[ 1/6, 7/6, 25/6,43/6];  % Data
Y=[ 1/5, 2/5, 14/5,14/5];
f=@(x,ym) (1-exp(x-ym)/h);
% with syms
syms x;
iX=f(x,ym(1:length(ym))).*X; % result iX= [f.1/6 , f.7/6 , f.25/6 , f.43/6]
iY=f(x,ym(1:length(ym))).*Y;
iFx= sum(iX);iFy=sum(iY);   % result  iFx= f.1/6 + f.7/6 + f.25/6 + f.43/6
x=ym;
plot(x,iFx,'r+');hold on;plot(x,iFy,'og');

Moreover, I tired to use a alternate codes with loop condition but the error persists as conversion to logical from sym is not possible.

% clear all;clc
% a=0;b=2;n=3;h=(b-a)/n;ym=a:h:b;
% %
% X=[ 1/6, 7/6, 25/6,43/6]; % Data
% Y=[ 1/5, 2/5, 14/5,4/5];
% %
% f=@(x,ym) (1-exp(x-ym)/h);
% %
% syms x  %double(subs(x))
% iX=cell(1,length(ym));iY=cell(1,length(ym)); %  cell, iX{k} and iY{k}
% % iX=zeros(1,length(ym));iY=zeros(1,length(ym));
% for k=1:length(ym)
% %          iX(k) =   f(x,ym(k)).*X(k);
% %          iY(k) =   f(x,ym(k)).*Y(k);
%            iX{k} = @(x,k)  f(x,ym(k)).*X(k);
%            iY{k} = @(x,k)  f(x,ym(k)).*Y(k);
%            iX(x,k);
% end
% whos
% x=ym;
% plot(x,iX{:},'r:');hold on;plot(x,iY{:},'b--');

please, how can I fix it?

Body:
You can't directly call plot(x,iFx) because iFx (and iFy) are symbolic variables depending on x and not the output from actually puting some real values into them. The easiest way is to fix this is to a) convert the symbolic variables to symbolic functions using symfun(formula,variables) and b) to then call said function with the values you want to plot them against:

clear all;clc;a=0;b=2;n=3;h=(b-a)/n;ym=a:h:b;
X=[ 1/6, 7/6, 25/6,43/6];  % Data
Y=[ 1/5, 2/5, 14/5,14/5];
f=@(x,ym) (1-exp(x-ym)/h);
% with syms
syms x;
iX=f(x,ym(1:length(ym))).*X; % result iX= [f.1/6 , f.7/6 , f.25/6 , f.43/6]
iY=f(x,ym(1:length(ym))).*Y;
iFx= sum(iX);iFy=sum(iY);   % result  iFx= f.1/6 + f.7/6 + f.25/6 + f.43/6

% same code until here

% step a) turn to symbolic function
iFx = symfun(iFx,x); iFy = symfun(iFy,x);

% step b) call the function with the "x" value of the plot.
plot(ym,iFx(ym),'r+');
hold on;
plot(ym,iFy(ym),'og');

Edit:

Sure, you can do the same thing with matlabFunction:

iFx = matlabFunction(iFx); iFy = matlabFunction(iFy);

For a discussion about symfun vs matlabFunction I refer to: matlab symfun vs anonymous function

TL;DR : matlabFunction returns an anonymous function which is usually faster, but symbolic functions are more flexible. But in this case it won't matter either way because the function is quite simple and the number of evaluated data points very little; therefore it will compute almost instantly anyways. But it's probably good practice to use matlabFunction.


问:
Unable to receive all MQTT messages in Python

I am trying to send messages from one python script to another using MQTT. One script is a publisher. The second script is a subscriber. I send messages every 0.1 second.

Publisher:

```<code>client = mqtt.Client('DataReaderPub')
client.connect('127.0.0.1', 1883, 60)
print("MQTT parameters set.")

# Read from all files
count = 0
for i in range(1,51):
    payload = "Hello world" + str(count)
    client.publish(testtopic, payload, int(publisherqos))
    client.loop()
    count = count+1
    print(count, ' msg sent: ', payload)
    sleep(0.1)
</code>```

Subscriber:

```<code>subclient = mqtt.Client("DynamicDetectorSub")
subclient.on_message = on_message
subclient.connect('127.0.0.1')

subclient.subscribe(testtopic, int(subscriberqos))

subclient.loop_forever()
</code>```

mosquitto broker version - 3.1

mosquitto.conf has max inflight messages set to 0, persistence true.

publisher QOS = 2

subscriber QOS = 2

topic = 'test' in both scripts

When I run subscriber and publisher in the same script, the messages are sent and received as expected. But when they are in separate scripts, I do not receive all the messages and sometimes no messages. I run subscriber first and then publisher. I have tried subscriber with loop.start() and loop.stop() with waiting for few minutes.

I am unable to debug this problem. Any pointers would be great!

EDIT:

I included client.loop() after publish. -> Same output as before

When I printed out statements in 'on_connect' and 'on_disconnect', I noticed that client mqtt connection gets established and disconnects almost immediately. This happens every second. I even got this message once -

[WinError 10053] An established connection was aborted by the software in your host machine

Keep Alive = 60

Is there any other parameter I should look at?

答:
You need to call the network loop function in the publisher as well so the client actually gets some time to do the IO (And the dual handshake for the QOS2).

Add client.loop() after the call to client.publish() in the client:

```<code>import paho.mqtt.client as mqtt
import time

client = mqtt.Client('DataReaderPub')
client.connect('127.0.0.1', 1883, 60)
print("MQTT parameters set.")

# Read from all files
count = 0
for i in range(1,51):
    payload = "Hello world" + str(count)
    client.publish("test", payload, 2)
    client.loop()
    count = count+1
    print(count, ' msg sent: ', payload)
    time.sleep(0.1)
</code>```

Subscriber code:

```<code>import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
  print(msg.topic + " " + str(msg.payload))

subclient = mqtt.Client("DynamicDetectorSub")
subclient.on_message = on_message
subclient.connect('127.0.0.1')

subclient.subscribe("test", 2)

subclient.loop_forever()
</code>```

Body:
I am trying to send messages from one python script to another using MQTT. One script is a publisher. The second script is a subscriber. I send messages every 0.1 second.

Publisher:

client = mqtt.Client('DataReaderPub')
client.connect('127.0.0.1', 1883, 60)
print("MQTT parameters set.")

# Read from all files
count = 0
for i in range(1,51):
    payload = "Hello world" + str(count)
    client.publish(testtopic, payload, int(publisherqos))
    client.loop()
    count = count+1
    print(count, ' msg sent: ', payload)
    sleep(0.1)

Subscriber:

subclient = mqtt.Client("DynamicDetectorSub")
subclient.on_message = on_message
subclient.connect('127.0.0.1')

subclient.subscribe(testtopic, int(subscriberqos))

subclient.loop_forever()

mosquitto broker version - 3.1

mosquitto.conf has max inflight messages set to 0, persistence true.

publisher QOS = 2

subscriber QOS = 2

topic = 'test' in both scripts

When I run subscriber and publisher in the same script, the messages are sent and received as expected. But when they are in separate scripts, I do not receive all the messages and sometimes no messages. I run subscriber first and then publisher. I have tried subscriber with loop.start() and loop.stop() with waiting for few minutes.

I am unable to debug this problem. Any pointers would be great!

EDIT:

I included client.loop() after publish. -> Same output as before

When I printed out statements in 'on_connect' and 'on_disconnect', I noticed that client mqtt connection gets established and disconnects almost immediately. This happens every second. I even got this message once -

[WinError 10053] An established connection was aborted by the software in your host machine

Keep Alive = 60

Is there any other parameter I should look at?

Body:
You need to call the network loop function in the publisher as well so the client actually gets some time to do the IO (And the dual handshake for the QOS2).

Add client.loop() after the call to client.publish() in the client:

import paho.mqtt.client as mqtt
import time

client = mqtt.Client('DataReaderPub')
client.connect('127.0.0.1', 1883, 60)
print("MQTT parameters set.")

# Read from all files
count = 0
for i in range(1,51):
    payload = "Hello world" + str(count)
    client.publish("test", payload, 2)
    client.loop()
    count = count+1
    print(count, ' msg sent: ', payload)
    time.sleep(0.1)

Subscriber code:

import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
  print(msg.topic + " " + str(msg.payload))

subclient = mqtt.Client("DynamicDetectorSub")
subclient.on_message = on_message
subclient.connect('127.0.0.1')

subclient.subscribe("test", 2)

subclient.loop_forever()


问:
When to use JoranConfigurator?
Can someone explain to me when should we use JoranConfigurtor?
I have logback.xml existing in a directory. I wonder what's happening in this piece of code?

Doesn't LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); initializes the context? So what is Joran is doing?

```<code> private static void configureLoggerContext(String logbackConfigFileUrl) {
    File file = new File(logbackConfigFileUrl);
    LoggerListener loggerListener = new LoggerListener();
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    loggerContext.reset();
    loggerContext.addListener(loggerListener);
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(loggerContext);
    try {
        configurator.doConfigure(file);
    } catch (JoranException je) {
        throw new RuntimeException(je.getMessage());
    }
}
</code>```

答:
Jorana is just a configuration library that Logback relies on.
https://logback.qos.ch/manual/configuration.html#joranDirectly

Title: When to use JoranConfigurator?

Body:
Can someone explain to me when should we use JoranConfigurtor?
I have logback.xml existing in a directory. I wonder what's happening in this piece of code?

Doesn't LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); initializes the context? So what is Joran is doing?

 private static void configureLoggerContext(String logbackConfigFileUrl) {
    File file = new File(logbackConfigFileUrl);
    LoggerListener loggerListener = new LoggerListener();
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    loggerContext.reset();
    loggerContext.addListener(loggerListener);
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(loggerContext);
    try {
        configurator.doConfigure(file);
    } catch (JoranException je) {
        throw new RuntimeException(je.getMessage());
    }
}


问:
Redirect www to non-www, http to https and only one Host
I'm looking for a special redirect system (htaccess) for improving SEO and the indexed structure of a website in google.

There are some Domains, who pointing to Website root directory. Therefore the Websites gets delivered by multiple Domains.

Specification for the Redirect System:

http -> https

www -> non-www

redirect to one host

only one 301 redirect (no several redirect behind each others)

Example:

Main Domain: domain-a.com

Goal: https://domain-a.com/XXX

Please look as this example Set

>>> Redirect Examples

答:
```<code>RewriteEngine on

# other domains
RewriteCond %{HTTP_HOST} !^domain-a.com [NC]
RewriteRule .* https://domain-a.com%{REQUEST_URI} [R=301,L]

# Redirect to domain with HTTPS.
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Same for www:
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule .* https://domain-a.com%{REQUEST_URI} [R=301,L]
</code>```


问:
Ansible EC2 Snapshots
I'm trying to automate the EC2 snapshots using the Ansible. I wrote the following play to gather the facts:

```<code>- hosts: localhost
  connection: local
  tasks:
    - name: Gathering the facts...
        ec2_remote_facts:
        aws_secret_key: bcv.jdbvdjbvdfjbv
        aws_access_key: dfnvdfnbvdfjbvndfj
        region: us-west-2
      register: ec2_facts

- name: printing the results
  debug: var=ec2_facts
</code>```

Above play works fine and returns the following output:

```<code>ok: [localhost] => {
    "ec2_facts": {
    "changed": false,
    "instances": [
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-12-08T08:52:21.000Z",
                    "delete_on_termination": true,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-0f0026ee65c5452e4"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-e5d10780",
                    "name": "default"
                }
            ],
            "hypervisor": "xen",
            "id": "i-0409acd413bb9db0f",
            "image_id": "ami-03445933",
            "instance_profile": null,
            "interfaces": [
                {
                    "id": "eni-1ea57b3d",
                    "mac_address": "02:04:f4:3a:92:34"
                }
            ],
            "kernel": null,
            "key_name": "ansible-test",
            "launch_time": "2017-12-08T08:52:20.000Z",
            "monitoring_state": "disabled",
            "persistent": false,
            "placement": {
                "tenancy": "default",
                "zone": "us-west-2b"
            },
            "private_dns_name": "ip-172-31-41-48.us-west-2.compute.internal",
            "private_ip_address": "172.31.41.48",
            "public_dns_name": "ec2-x-x-x-x.us-west-2.compute.amazonaws.com",
            "public_ip_address": "x.x.x.x",
            "ramdisk": null,
            "region": "us-west-2",
            "requester_id": null,
            "root_device_type": "ebs",
            "source_destination_check": "true",
            "spot_instance_request_id": null,
            "state": "running",
            "tags": {},
            "virtualization_type": "hvm",
            "vpc_id": "vpc-4a77992f"
        },
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-12-08T11:43:45.000Z",
                    "delete_on_termination": false,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-036a851b5b96ac359"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-c63677a3",
                    "name": "test"
                }
            ],
            "hypervisor": "xen",
            "id": "i-05b9ecfe5fa30be49",
            "image_id": "ami-02c71d7a",
            "instance_profile": null,
            "interfaces": [
                {
                    "id": "eni-e2d40dc1",
                    "mac_address": "02:7c:b1:08:45:e8"
                }
            ],
            "kernel": null,
            "key_name": "ansible-test",
            "launch_time": "2017-12-08T11:43:44.000Z",
            "monitoring_state": "disabled",
            "persistent": false,
            "placement": {
                "tenancy": "default",
                "zone": "us-west-2b"
            },
            "private_dns_name": "ip-172-31-35-159.us-west-2.compute.internal",
            "private_ip_address": "172.31.35.159",
            "public_dns_name": "ec2-x-x-x-x.us-west-2.compute.amazonaws.com",
            "public_ip_address": "x.x.x.x",
            "ramdisk": null,
            "region": "us-west-2",
            "requester_id": null,
            "root_device_type": "ebs",
            "source_destination_check": "true",
            "spot_instance_request_id": null,
            "state": "running",
            "tags": {},
            "virtualization_type": "hvm",
            "vpc_id": "vpc-4a77992f"
        }
    ]
}
}
</code>```

I have two running test instances in my AWS account and above output shows the correct information. Now using the above facts, I want to snapshot the EBS volumes attached to the respective instances. But theami_launch_index value always returns 0 even if there are multiple instances. So i believe I cannot dynamically select the instances and attached EBS volumes to snapshot it. Following is the play I've wrote to snapshot the instances based on the above facts:

```<code>- name: Snapshoting the instance...
  ec2_snapshot:
    aws_secret_key: bcv.jdbvdjbvdfjbv
    aws_access_key: dfnvdfnbvdfjbvndfj
    region: us-west-2
    instance_id: "{{ item.id }}"
    device_name: "{{ item['device_name'] }}"
    description: "Snapshot test by"
  with_items: "{{ ec2_facts.instances }}"
</code>```

So can anyone please help me to solve the issue?

答:
I'm able to snapshot all the running AWS instances using the following play:

```<code>- hosts: localhost
  connection: local
  tasks:
    - name: Gathering the facts...
      ec2_remote_facts:
        aws_secret_key:
        aws_access_key:
        region: us-west-2
      register: ec2_facts

    - name: Snapshoting the instance...
      ec2_snapshot:
        aws_secret_key:
        aws_access_key:
        region: us-west-2
        volume_id: "{{ item.volume_id }}"
      with_items: "{{ ec2_facts | json_query('instances[].block_device_mapping[]') }}"
</code>```

Hope above helps the future visitors.

Title: Ansible EC2 Snapshots

Body:
I'm trying to automate the EC2 snapshots using the Ansible. I wrote the following play to gather the facts:

- hosts: localhost
  connection: local
  tasks:
    - name: Gathering the facts...
        ec2_remote_facts:
        aws_secret_key: bcv.jdbvdjbvdfjbv
        aws_access_key: dfnvdfnbvdfjbvndfj
        region: us-west-2
      register: ec2_facts

- name: printing the results
  debug: var=ec2_facts

Above play works fine and returns the following output:

ok: [localhost] => {
    "ec2_facts": {
    "changed": false,
    "instances": [
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-12-08T08:52:21.000Z",
                    "delete_on_termination": true,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-0f0026ee65c5452e4"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-e5d10780",
                    "name": "default"
                }
            ],
            "hypervisor": "xen",
            "id": "i-0409acd413bb9db0f",
            "image_id": "ami-03445933",
            "instance_profile": null,
            "interfaces": [
                {
                    "id": "eni-1ea57b3d",
                    "mac_address": "02:04:f4:3a:92:34"
                }
            ],
            "kernel": null,
            "key_name": "ansible-test",
            "launch_time": "2017-12-08T08:52:20.000Z",
            "monitoring_state": "disabled",
            "persistent": false,
            "placement": {
                "tenancy": "default",
                "zone": "us-west-2b"
            },
            "private_dns_name": "ip-172-31-41-48.us-west-2.compute.internal",
            "private_ip_address": "172.31.41.48",
            "public_dns_name": "ec2-x-x-x-x.us-west-2.compute.amazonaws.com",
            "public_ip_address": "x.x.x.x",
            "ramdisk": null,
            "region": "us-west-2",
            "requester_id": null,
            "root_device_type": "ebs",
            "source_destination_check": "true",
            "spot_instance_request_id": null,
            "state": "running",
            "tags": {},
            "virtualization_type": "hvm",
            "vpc_id": "vpc-4a77992f"
        },
        {
            "ami_launch_index": "0",
            "architecture": "x86_64",
            "block_device_mapping": [
                {
                    "attach_time": "2017-12-08T11:43:45.000Z",
                    "delete_on_termination": false,
                    "device_name": "/dev/sda1",
                    "status": "attached",
                    "volume_id": "vol-036a851b5b96ac359"
                }
            ],
            "client_token": "",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-c63677a3",
                    "name": "test"
                }
            ],
            "hypervisor": "xen",
            "id": "i-05b9ecfe5fa30be49",
            "image_id": "ami-02c71d7a",
            "instance_profile": null,
            "interfaces": [
                {
                    "id": "eni-e2d40dc1",
                    "mac_address": "02:7c:b1:08:45:e8"
                }
            ],
            "kernel": null,
            "key_name": "ansible-test",
            "launch_time": "2017-12-08T11:43:44.000Z",
            "monitoring_state": "disabled",
            "persistent": false,
            "placement": {
                "tenancy": "default",
                "zone": "us-west-2b"
            },
            "private_dns_name": "ip-172-31-35-159.us-west-2.compute.internal",
            "private_ip_address": "172.31.35.159",
            "public_dns_name": "ec2-x-x-x-x.us-west-2.compute.amazonaws.com",
            "public_ip_address": "x.x.x.x",
            "ramdisk": null,
            "region": "us-west-2",
            "requester_id": null,
            "root_device_type": "ebs",
            "source_destination_check": "true",
            "spot_instance_request_id": null,
            "state": "running",
            "tags": {},
            "virtualization_type": "hvm",
            "vpc_id": "vpc-4a77992f"
        }
    ]
}
}

I have two running test instances in my AWS account and above output shows the correct information. Now using the above facts, I want to snapshot the EBS volumes attached to the respective instances. But theami_launch_index value always returns 0 even if there are multiple instances. So i believe I cannot dynamically select the instances and attached EBS volumes to snapshot it. Following is the play I've wrote to snapshot the instances based on the above facts:

- name: Snapshoting the instance...
  ec2_snapshot:
    aws_secret_key: bcv.jdbvdjbvdfjbv
    aws_access_key: dfnvdfnbvdfjbvndfj
    region: us-west-2
    instance_id: "{{ item.id }}"
    device_name: "{{ item['device_name'] }}"
    description: "Snapshot test by"
  with_items: "{{ ec2_facts.instances }}"

So can anyone please help me to solve the issue?

Body:
I'm able to snapshot all the running AWS instances using the following play:

- hosts: localhost
  connection: local
  tasks:
    - name: Gathering the facts...
      ec2_remote_facts:
        aws_secret_key:
        aws_access_key:
        region: us-west-2
      register: ec2_facts

    - name: Snapshoting the instance...
      ec2_snapshot:
        aws_secret_key:
        aws_access_key:
        region: us-west-2
        volume_id: "{{ item.volume_id }}"
      with_items: "{{ ec2_facts | json_query('instances[].block_device_mapping[]') }}"

Hope above helps the future visitors.


问:
How to clean foreverjs logs for running processes?
How do I clean logs for foreverjs for a running process? I can manually delete the log files but that results in forever not logging anymore. </p>

<p>I've also seen cleanlogs but that only removes historical logs, but not affecting logs of any active processes.  </p>

答:
You can:

```<code>$ forever list
</code>```

Copy log path.

Using VIM:

Select all and delete (actually move to buffer)

```<code>:%d
</code>```

Then save file

```<code>:x
</code>```

Body:
How do I clean logs for foreverjs for a running process? I can manually delete the log files but that results in forever not logging anymore.

I've also seen cleanlogs but that only removes historical logs, but not affecting logs of any active processes.

Body:
You can:

$ forever list

Copy log path.

Using VIM:

Select all and delete (actually move to buffer)

:%d

Then save file

:x