问:
Recursive file search using PowerShell
I am searching for a file in all the folders.

Copyforbuild.bat is available in many places, and I would like to search recursively.

```<code>$File = "V:\Myfolder\**\*.CopyForbuild.bat"
</code>```

How can I do it in PowerShell?

答:
Here is the method that I finally came up with after struggling:

```<code>Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*
</code>```

To make the output cleaner (only path), use:

```<code>(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname
</code>```

To get only the first result, use:

```<code>(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname | Select -First 1
</code>```

Now for the important stuff:

To search only for files/directories do not use -File or -Directory (see below why). Instead use this for files:

```<code>Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}
</code>```

and remove the -eq $false for directories. Do not leave a trailing wildcard like bin/*.

Why not use the built in switches? They are terrible and remove features randomly. For example, in order to use -Include with a file, you must end the path with a wildcard. However, this disables the -Recurse switch without telling you:

```<code>Get-ChildItem -File -Recurse -Path ./bin/* -Include *.lib
</code>```

You'd think that would give you all *.libs in all subdirectories, but it only will search top level of bin.

In order to search for directories, you can use -Directory, but then you must remove the trailing wildcard. For whatever reason, this will not deactivate -Recurse. It is for these reasons that I recommend not using the builtin flags.

You can shorten this command considerably:

```<code>Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}
</code>```

becomes

```<code>gci './path*/' -s -Include 'name*' | where {$_.PSIsContainer -eq $false}
</code>```

Get-ChildItem is aliased to gci

-Path is default to position 0, so you can just make first argument path

-Recurse is aliased to -s

-Include does not have a shorthand

Use single quotes for spaces in names/paths, so that you can surround the whole command with double quotes and use it in Command Prompt. Doing it the other way around (surround with single quotes) causes errors

Title: Recursive file search using PowerShell

Body:
I am searching for a file in all the folders.

Copyforbuild.bat is available in many places, and I would like to search recursively.

$File = "V:\Myfolder\**\*.CopyForbuild.bat"

How can I do it in PowerShell?

Body:
Here is the method that I finally came up with after struggling:

Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*

To make the output cleaner (only path), use:

(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname

To get only the first result, use:

(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname | Select -First 1

Now for the important stuff:

To search only for files/directories do not use -File or -Directory (see below why). Instead use this for files:

Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}

and remove the -eq $false for directories. Do not leave a trailing wildcard like bin/*.

Why not use the built in switches? They are terrible and remove features randomly. For example, in order to use -Include with a file, you must end the path with a wildcard. However, this disables the -Recurse switch without telling you:

Get-ChildItem -File -Recurse -Path ./bin/* -Include *.lib

You'd think that would give you all *.libs in all subdirectories, but it only will search top level of bin.

In order to search for directories, you can use -Directory, but then you must remove the trailing wildcard. For whatever reason, this will not deactivate -Recurse. It is for these reasons that I recommend not using the builtin flags.

You can shorten this command considerably:

Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}

becomes

gci './path*/' -s -Include 'name*' | where {$_.PSIsContainer -eq $false}

Get-ChildItem is aliased to gci

-Path is default to position 0, so you can just make first argument path

-Recurse is aliased to -s

-Include does not have a shorthand

Use single quotes for spaces in names/paths, so that you can surround the whole command with double quotes and use it in Command Prompt. Doing it the other way around (surround with single quotes) causes errors


来源: stackexchange

问:
Identifying kernel threads
I'd like to know how I can distinguish a kernel-thread from a user-thread for a process-scanner I'm building. I'm having a hard time finding a good definition of both types.

I found that kernel-threads don't have memory of their own, so no Vm* values in /proc/$pid/status, and that a stat on /proc/$pid/exe does not return anything.

So, I figured I could identify kernel threads if a process has no Vm* values and no inode number. I figured wrong... my script sees php-cgi processes that are identified as kernel processes sometime.

If found that most of those wrongly identified processes are zombies that are gone a second later. So I implemented a simple check to see if the status is "Z". If so, ignore it.
That saved me a lot of false positives, but still I receive messages about php-cgi kernel-processes.

Can anyone tell me how I can distinguish a kernel-thread from a user-thread the right way?

答:
You can read thread flags value from /proc/[pid]/stat (see proc(5) manpage) and check if it has PF_KTHREAD bit flag set.

PF_KTHREAD constant itself has been available since 2.6.17, which is roughly for 10 years, and it's value hasn't changed since then:

```<code>#define PF_KTHREAD      0x00200000  /* I am a kernel thread */
</code>```

Even through the header file containing this constant (include/linux/sched.h) is not exported to userspace, having a copy of this definition in your source code combined with kernel version check done from userspace at runtime (e.g. using uname(2) system call) should be pretty robust.

ContentLicense: CC BY-SA 3.0

Title: Identifying kernel threads

Body:
You can read thread flags value from /proc/[pid]/stat (see proc(5) manpage) and check if it has PF_KTHREAD bit flag set.

PF_KTHREAD constant itself has been available since 2.6.17, which is roughly for 10 years, and it's value hasn't changed since then:

#define PF_KTHREAD      0x00200000  /* I am a kernel thread */

Even through the header file containing this constant (include/linux/sched.h) is not exported to userspace, having a copy of this definition in your source code combined with kernel version check done from userspace at runtime (e.g. using uname(2) system call) should be pretty robust.

ContentLicense: CC BY-SA 4.0


问:
Is is possible to scale pagekite on multiple machine?
Is it possible to scale pagekite on multiple servers so that:

It is not anymore a single point of failure

When the traffic gets heavy it gets distributed

答:
The public service on pagekite.net is distributed over about 50 relays all over the world, for those reasons. But also to reduce latency, you get better service if your relay is nearby.

So yes, but it's a fair bit of work.

If you need that sort of thing, maybe consider working with us?


问:
Check if options(coming from the Json object) exists in select drop down
Two scenarios: the below two cases doesn't run at a same time.
I have a select drop down with existing options, what I need to do is

Add 'selected' attribute to the option which matches with the key from the object. I don't need multiple selections here, I didn't know how to explain my actual scenario here hence I have used 'Batman' in the if condition if(jQuery(this).val() == "Batman"), in my scenario batman is dynamic.

If the keys doesn't match and doesn't exist in the DOM(select) then append that key as an option and the add 'selected' attribute.

I'm almost there but I couldn't figure out a solution without replacing all the values in the drop down(Please run the snippet). I have tried append option as well but couldn't get it right.

var obj = {"characters": [{"Hulk": "Hulk"}]};
var opt;
$.each(obj["characters"], function(index, value) {
  $.each(value, function(val) {
    $('.sel-dropdwn').each(function() {
      if ($(this).find('option').val() == val)
        $(this).find('option').attr('selected', 'selected');
      else{
       opt = $('<option></option>');
       opt.text(val).val(val).attr('selected','selected');
       $(this).append(opt)
      }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select aria-required="true" class="form-control sel-dropdwn">
  <option value="">-- None --</option>
  <option value="Superman">Superman</option>
  <option value="Batman">Batman</option>
  <option value="Ironman">Ironman</option>
</select></code>```

答:
Based on comment and OP's clarification we understand that we want to select or add and select a given value.

```<code>let character = 'Hulk';
let exists = $('.sel-dropdwn option[value="'+ character + '"]').length > 0;

if(!exists){
   let option = $('<option value="'+ character + '"></option>').text(character);
   $('.sel-dropdwn').append(option);
}
$('.sel-dropdwn').val(character);
</code>```

I am using a single value for character here. You may have an obj with key/value.

Body:
Two scenarios: the below two cases doesn't run at a same time.
I have a select drop down with existing options, what I need to do is

Add 'selected' attribute to the option which matches with the key from the object. I don't need multiple selections here, I didn't know how to explain my actual scenario here hence I have used 'Batman' in the if condition if(jQuery(this).val() == "Batman"), in my scenario batman is dynamic.

If the keys doesn't match and doesn't exist in the DOM(select) then append that key as an option and the add 'selected' attribute.

I'm almost there but I couldn't figure out a solution without replacing all the values in the drop down(Please run the snippet). I have tried append option as well but couldn't get it right.

var obj = {"characters": [{"Hulk": "Hulk"}]};
var opt;
$.each(obj["characters"], function(index, value) {
  $.each(value, function(val) {
    $('.sel-dropdwn').each(function() {
      if ($(this).find('option').val() == val)
        $(this).find('option').attr('selected', 'selected');
      else{
       opt = $('<option></option>');
       opt.text(val).val(val).attr('selected','selected');
       $(this).append(opt)
      }
    });
});

<select aria-required="true" class="form-control sel-dropdwn">
  <option value="">-- None --</option>
  <option value="Superman">Superman</option>
  <option value="Batman">Batman</option>
  <option value="Ironman">Ironman</option>
</select>

Body:
Based on comment and OP's clarification we understand that we want to select or add and select a given value.

let character = 'Hulk';
let exists = $('.sel-dropdwn option[value="'+ character + '"]').length > 0;

if(!exists){
   let option = $('<option value="'+ character + '"></option>').text(character);
   $('.sel-dropdwn').append(option);
}
$('.sel-dropdwn').val(character);

I am using a single value for character here. You may have an obj with key/value.


问:
Decorator pattern for a Customer class
Suppose I have a Customer class. A customer can have multiple kinds of loyalty points. For one promotion, the customer may be collecting Rewards. In another, the customer may be collecting Miles. And there is no fixed number of kinds of loyalty points that the Customer is built for. I am sure this is a common use case. Is the decorator pattern a good fit given below sample code?

```<code>    public interface ICustomer
    {
        void Display();
    }

    public class SimpleCustomer : ICustomer
    {
        public void Display()
        {
            Console.WriteLine("I am simple customer");
        }
    }

    public abstract class CustomerDecorator : ICustomer
    {
        protected ICustomer customer;

        public CustomerDecorator(ICustomer customer)
        {
            this.customer = customer ?? throw new ArgumentNullException("customer");
        }

        public abstract void Display();
    }

    public class RewardsDecorator : CustomerDecorator
    {
        private int rewards;
        public RewardsDecorator(ICustomer customer, int rewards) : base(customer)
        {
            this.rewards = rewards;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + rewards.ToString() + " rewards");
        }
    }

    public class MilesDecorator : CustomerDecorator
    {
        private int miles;
        public MilesDecorator(ICustomer customer, int miles) : base(customer)
        {
            this.miles = miles;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + miles.ToString() + " miles");
        }
    }
</code>```

答:
I would use the visitor pattern, this is pretty ideal for your situation. This will allow you nicely separate the rewards calculations for you different customer types and run operations against all supported rewards types.</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        MilesCustomer customer = new MilesCustomer();
        ICustomerVisitor<int> visitor = new MilesCalculation(10);
        var miles = customer.Visit(visitor);
        visitor = new RewardsCalucation(100);
        var rewards = customer.Visit(visitor);
    }
}
public interface ICustomerVisitor<T>
{
    T Visit(SimpleCustomer cusomter);
    T Visit(RewardsCustomer cusomter);
    T Visit(MilesCustomer cusomter);
}

public abstract class Customer
{
    public Customer()
    {
        TotalMoneySpent = 10;
    }

    public int TotalMoneySpent { get; private set; }

    public abstract T Visit<T>(ICustomerVisitor<T> visitor);

    public virtual void Display()
    {
        Console.WriteLine("I am simple customer");
    }
}

public class RewardsCalucation : ICustomerVisitor<int>
{
    private int _rewardsPerDollar;

    public RewardsCalucation(int rewardsPerDollar) => _rewardsPerDollar = rewardsPerDollar;

    public int Visit(SimpleCustomer cusomter)
    {
        return 0;
    }

    public int Visit(RewardsCustomer cusomter)
    {
        return cusomter.TotalMoneySpent * _rewardsPerDollar;
    }

    public int Visit(MilesCustomer cusomter)
    {
        return 0;
    }
}

public class MilesCalculation : ICustomerVisitor<int>
{
    private int _milesPerDollar;
    public MilesCalculation(int milesPerDollar) => _milesPerDollar = milesPerDollar;
    public int Visit(SimpleCustomer cusomter)
    {
        return 0;
    }

    public int Visit(RewardsCustomer cusomter)
    {
        return 0;
    }

    public int Visit(MilesCustomer cusomter)
    {
        return cusomter.TotalMoneySpent * _milesPerDollar;
    }
}

public class SimpleCustomer : Customer
{
    public override T Visit<T>(ICustomerVisitor<T> visitor)
    {
        return visitor.Visit(this);
    }
}

public class RewardsCustomer : Customer
{
    public override T Visit<T>(ICustomerVisitor<T> visitor)
    {
        return visitor.Visit(this);
    }
}

public class MilesCustomer : Customer
{
    public override T Visit<T>(ICustomerVisitor<T> visitor)
    {
        return visitor.Visit(this);
    }
}
</code>```

Title: Decorator pattern for a Customer class

Body:
Suppose I have a Customer class. A customer can have multiple kinds of loyalty points. For one promotion, the customer may be collecting Rewards. In another, the customer may be collecting Miles. And there is no fixed number of kinds of loyalty points that the Customer is built for. I am sure this is a common use case. Is the decorator pattern a good fit given below sample code?

    public interface ICustomer
    {
        void Display();
    }

    public class SimpleCustomer : ICustomer
    {
        public void Display()
        {
            Console.WriteLine("I am simple customer");
        }
    }

    public abstract class CustomerDecorator : ICustomer
    {
        protected ICustomer customer;

        public CustomerDecorator(ICustomer customer)
        {
            this.customer = customer ?? throw new ArgumentNullException("customer");
        }

        public abstract void Display();
    }

    public class RewardsDecorator : CustomerDecorator
    {
        private int rewards;
        public RewardsDecorator(ICustomer customer, int rewards) : base(customer)
        {
            this.rewards = rewards;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + rewards.ToString() + " rewards");
        }
    }

    public class MilesDecorator : CustomerDecorator
    {
        private int miles;
        public MilesDecorator(ICustomer customer, int miles) : base(customer)
        {
            this.miles = miles;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + miles.ToString() + " miles");
        }
    }

Body:
I would use the visitor pattern, this is pretty ideal for your situation. This will allow you nicely separate the rewards calculations for you different customer types and run operations against all supported rewards types.

class Program
{
    static void Main(string[] args)
    {
        MilesCustomer customer = new MilesCustomer();
        ICustomerVisitor<int> visitor = new MilesCalculation(10);
        var miles = customer.Visit(visitor);
        visitor = new RewardsCalucation(100);
        var rewards = customer.Visit(visitor);
    }
}
public interface ICustomerVisitor<T>
{
    T Visit(SimpleCustomer cusomter);
    T Visit(RewardsCustomer cusomter);
    T Visit(MilesCustomer cusomter);
}

public abstract class Customer
{
    public Customer()
    {
        TotalMoneySpent = 10;
    }

    public int TotalMoneySpent { get; private set; }

    public abstract T Visit<T>(ICustomerVisitor<T> visitor);

    public virtual void Display()
    {
        Console.WriteLine("I am simple customer");
    }
}

public class RewardsCalucation : ICustomerVisitor<int>
{
    private int _rewardsPerDollar;

    public RewardsCalucation(int rewardsPerDollar) => _rewardsPerDollar = rewardsPerDollar;

    public int Visit(SimpleCustomer cusomter)
    {
        return 0;
    }

    public int Visit(RewardsCustomer cusomter)
    {
        return cusomter.TotalMoneySpent * _rewardsPerDollar;
    }

    public int Visit(MilesCustomer cusomter)
    {
        return 0;
    }
}

public class MilesCalculation : ICustomerVisitor<int>
{
    private int _milesPerDollar;
    public MilesCalculation(int milesPerDollar) => _milesPerDollar = milesPerDollar;
    public int Visit(SimpleCustomer cusomter)
    {
        return 0;
    }

    public int Visit(RewardsCustomer cusomter)
    {
        return 0;
    }

    public int Visit(MilesCustomer cusomter)
    {
        return cusomter.TotalMoneySpent * _milesPerDollar;
    }
}

public class SimpleCustomer : Customer
{
    public override T Visit<T>(ICustomerVisitor<T> visitor)
    {
        return visitor.Visit(this);
    }
}

public class RewardsCustomer : Customer
{
    public override T Visit<T>(ICustomerVisitor<T> visitor)
    {
        return visitor.Visit(this);
    }
}

public class MilesCustomer : Customer
{
    public override T Visit<T>(ICustomerVisitor<T> visitor)
    {
        return visitor.Visit(this);
    }
}


问:
Generate regularly spaced points in polygon
Is there a way to generate regularly spaced (e.g., 500 meters apart) points within a polygon using R? I have been trying to use the sp package but can't seem to define a set of points that are spaced a certain distance apart from one another. My aim is to generate the points, then extract their lat/long coordinates into a new dataframe. Any help would be much appreciated! Thanks</p>

答:
Quite straight forward and almost out-of-the-box.

As OP did not share data, buckle up, put your seats in a vertical position and let us fly to Paris. There, we will adapt a geosphere function, and with its help we will divide up Paris' shape into lon / lat coordinates that are 500 meters apart each (vertically and horizontally).

```<code># Load necessary libraries.
library(raster)
library(geosphere)
library(tidyverse)
library(sp)

# This is an adapted version of geosphere's destPoint() function that works with
# changing d (distance).
destPoint_v <- function (x, y, b, d, a = 6378137, f = 1/298.257223563, ...)
{
    r <- list(...)$r
    if (!is.null(r)) {
        return(.old_destPoint(x, y, b, d, r = r))
    }
    b <- as.vector(b)
    d <- as.vector(d)
    x <- as.vector(x)
    y <- as.vector(y)
    p <- cbind(x, y, b, d)
    r <- .Call("_geodesic", as.double(p[, 1]), as.double(p[, 2]),
               as.double(p[, 3]), as.double(p[, 4]),
               as.double(a), as.double(f),
               PACKAGE = "geosphere")
    r <- matrix(r, ncol = 3, byrow = TRUE)
    colnames(r) <- c("lon", "lat", "finalbearing")
    return(r[, 1:2, drop = FALSE])
}

# Data can be downloaded from
# http://osm13.openstreetmap.fr/~cquest/openfla/export/communes-20190101-shp.zip
# or
# https://www.data.gouv.fr/en/datasets/decoupage-administratif-communal-francais-issu-d-openstreetmap/
# ("Export simple de janvier 2019 (225Mo)")

# Load shapefile.
# shp <- raster::shapefile("Dropbox/work/crema/communes-20190101-shp/communes-20190101.shp")
# Extract Paris.
paris <- shp[shp$nom == "Paris", ]

# Set distance of points in meters.
dist <- 500

# Extract bounding box from Paris' SpatialPolygonDataFrame.
bbox <- raster::extent(paris)

# Calculate number of points on the vertical axis.
ny <- ceiling(geosphere::distGeo(p1 = c(bbox@xmin, bbox@ymin),
                               p2 = c(bbox@xmin, bbox@ymax)) / dist)
# Calculate maximum number of points on the horizontal axis.
# This needs to be calculated for the lowermost and uppermost horizontal lines
# as the distance between latitudinal lines varies when the longitude changes.
nx <- ceiling(max(geosphere::distGeo(p1 = c(bbox@xmin, bbox@ymin),
                                   p2 = c(bbox@xmax, bbox@ymin)) / dist,
                geosphere::distGeo(p1 = c(bbox@xmin, bbox@ymax),
                                   p2 = c(bbox@xmax, bbox@ymax)) / dist))

# Create result data frame with number of points on vertical axis.
df <- data.frame(ny = 1:ny)

# Calculate coordinates along the vertical axis.
pts <- geosphere::destPoint(p = c(bbox@xmin, bbox@ymin),
                            b = 0, d = dist * (1:ny - 1))
df$x <- pts[, 1]
df$y <- pts[, 2]

# Add points on horizontal axis.
df <- tidyr::crossing(nx = 1:nx, df)

# Calculate coordinates.
pts <- destPoint_v(df$x, df$y, b = 90, 500 * (df$nx - 1))

# Turn coordinates into SpatialPoints.
pts <- SpatialPoints(cbind(pts[, 1], pts[, 2]), proj4string = CRS(proj4string(paris)))

# Cut to boundaries of Paris.
result <- raster::intersect(pts, paris)

# Plot result.
plot(result)
title("Paris in Points")
</code>```

Kind of looks like a fish, doesn't it?

Body:
Quite straight forward and almost out-of-the-box.

As OP did not share data, buckle up, put your seats in a vertical position and let us fly to Paris. There, we will adapt a geosphere function, and with its help we will divide up Paris' shape into lon / lat coordinates that are 500 meters apart each (vertically and horizontally).

# Load necessary libraries.
library(raster)
library(geosphere)
library(tidyverse)
library(sp)

# This is an adapted version of geosphere's destPoint() function that works with
# changing d (distance).
destPoint_v <- function (x, y, b, d, a = 6378137, f = 1/298.257223563, ...)
{
    r <- list(...)$r
    if (!is.null(r)) {
        return(.old_destPoint(x, y, b, d, r = r))
    }
    b <- as.vector(b)
    d <- as.vector(d)
    x <- as.vector(x)
    y <- as.vector(y)
    p <- cbind(x, y, b, d)
    r <- .Call("_geodesic", as.double(p[, 1]), as.double(p[, 2]),
               as.double(p[, 3]), as.double(p[, 4]),
               as.double(a), as.double(f),
               PACKAGE = "geosphere")
    r <- matrix(r, ncol = 3, byrow = TRUE)
    colnames(r) <- c("lon", "lat", "finalbearing")
    return(r[, 1:2, drop = FALSE])
}

# Data can be downloaded from
# http://osm13.openstreetmap.fr/~cquest/openfla/export/communes-20190101-shp.zip
# or
# https://www.data.gouv.fr/en/datasets/decoupage-administratif-communal-francais-issu-d-openstreetmap/
# ("Export simple de janvier 2019 (225Mo)")

# Load shapefile.
# shp <- raster::shapefile("Dropbox/work/crema/communes-20190101-shp/communes-20190101.shp")
# Extract Paris.
paris <- shp[shp$nom == "Paris", ]

# Set distance of points in meters.
dist <- 500

# Extract bounding box from Paris' SpatialPolygonDataFrame.
bbox <- raster::extent(paris)

# Calculate number of points on the vertical axis.
ny <- ceiling(geosphere::distGeo(p1 = c(bbox@xmin, bbox@ymin),
                               p2 = c(bbox@xmin, bbox@ymax)) / dist)
# Calculate maximum number of points on the horizontal axis.
# This needs to be calculated for the lowermost and uppermost horizontal lines
# as the distance between latitudinal lines varies when the longitude changes.
nx <- ceiling(max(geosphere::distGeo(p1 = c(bbox@xmin, bbox@ymin),
                                   p2 = c(bbox@xmax, bbox@ymin)) / dist,
                geosphere::distGeo(p1 = c(bbox@xmin, bbox@ymax),
                                   p2 = c(bbox@xmax, bbox@ymax)) / dist))

# Create result data frame with number of points on vertical axis.
df <- data.frame(ny = 1:ny)

# Calculate coordinates along the vertical axis.
pts <- geosphere::destPoint(p = c(bbox@xmin, bbox@ymin),
                            b = 0, d = dist * (1:ny - 1))
df$x <- pts[, 1]
df$y <- pts[, 2]

# Add points on horizontal axis.
df <- tidyr::crossing(nx = 1:nx, df)

# Calculate coordinates.
pts <- destPoint_v(df$x, df$y, b = 90, 500 * (df$nx - 1))

# Turn coordinates into SpatialPoints.
pts <- SpatialPoints(cbind(pts[, 1], pts[, 2]), proj4string = CRS(proj4string(paris)))

# Cut to boundaries of Paris.
result <- raster::intersect(pts, paris)

# Plot result.
plot(result)
title("Paris in Points")

Kind of looks like a fish, doesn't it?


问:
How to provide a python argparse.parser with arguments from inside the code, without command-line arguments?
I have a code that takes the command-line arguments into a parser and modifies some configuration settings. Something like this:

command:

```<code>python mycode.py --config-file "some_file.yaml" SOMETHING.subsetting_a 2 SOMETHING.subsetting_b 3
</code>```

and then it does:

```<code>import argparse
parser = argparse.ArgumentParser(description="Some description here")
parser.add_argument(
    "--config-file",
    default="",
    metavar="FILE",
    help="path to config file",
    type=str,
)
//some more 'add_argument' lines here
args = parser.parse_args()
</code>```

But as I am using jupyter notebook, it would be easier to provide the arguments directly to the parser, as if they come from the command-line. How can I create a string containing the command (as mentioned above) and pass it to parser?

答:
parse_args's first optional argument is the list of arguments to parse, the signature is:

ArgumentParser.parse_args(args=None, namespace=None)

It just takes args from sys.argv if you don't provide it.

So just call it as:

```<code>args = parser.parse_args(['mycode.py', '--config-file', "some_file.yaml", 'SOMETHING.subsetting_a', '2', 'SOMETHING.subsetting_a'])
</code>```

(with the list containing whatever you like instead) and it will use it instead of sys.argv.

Body:
I have a code that takes the command-line arguments into a parser and modifies some configuration settings. Something like this:

command:

python mycode.py --config-file "some_file.yaml" SOMETHING.subsetting_a 2 SOMETHING.subsetting_b 3

and then it does:

import argparse
parser = argparse.ArgumentParser(description="Some description here")
parser.add_argument(
    "--config-file",
    default="",
    metavar="FILE",
    help="path to config file",
    type=str,
)
//some more 'add_argument' lines here
args = parser.parse_args()

But as I am using jupyter notebook, it would be easier to provide the arguments directly to the parser, as if they come from the command-line. How can I create a string containing the command (as mentioned above) and pass it to parser?

Body:
parse_args's first optional argument is the list of arguments to parse, the signature is:

ArgumentParser.parse_args(args=None, namespace=None)

It just takes args from sys.argv if you don't provide it.

So just call it as:

args = parser.parse_args(['mycode.py', '--config-file', "some_file.yaml", 'SOMETHING.subsetting_a', '2', 'SOMETHING.subsetting_a'])

(with the list containing whatever you like instead) and it will use it instead of sys.argv.


问:
Ionic 4 change ion-tab-button with custom icon
I'm trying to change ion-icon with custom src after ion-tab-button is clicked

What I have tried, using (click) event to trigger function and change the [src]="..." inside the ion-icon

Is there any proper way to change this hackish style?

HTML:

```<code> <ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="news/home" (click)="changeNewsIcon()">
      <ion-icon [src]="newsIcon"></ion-icon>
      <ion-label class="tab-title">News</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="user" (click)="changeSearchIcon()">
      <ion-icon [src]="searchIcon"></ion-icon>
      <ion-label class="tab-title">Search</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="networking" (click)="changeNetworkIcon()">
      <ion-icon [src]="notiIcon"></ion-icon>
      <ion-label class="tab-title">Networking</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="chat" (click)="changeChatIcon()">
      <ion-icon [src]="chatIcon"></ion-icon>
      <ion-label class="tab-title">Chat</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="profile" (click)="changeProfIcon()">
      <ion-icon [src]="profIcon"></ion-icon>
      <ion-label class="tab-title">Profile</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>
</code>```

TS :

```<code>newsIcon = './assets/tabs/home.svg';
searchIcon = './assets/tabs/search.svg';
notiIcon = './assets/tabs/group.svg';
chatIcon = './assets/tabs/chat.svg';
profIcon = './assets/tabs/user.svg';

changeNewsIcon(): void {
  // change news icon
  this.newsIcon = './assets/tabs/clicked-home.svg';

  // reset others icon
  this.searchIcon = './assets/tabs/search.svg';
  this.notiIcon = './assets/tabs/group.svg';
  this.chatIcon = './assets/tabs/chat.svg';
  this.profIcon = './assets/tabs/user.svg';
}

changeSearchIcon(): void {
  // change user icon
  this.searchIcon = './assets/tabs/clicked-search.svg';

  // reset others icon
  this.newsIcon = './assets/tabs/home.svg';
  this.notiIcon = './assets/tabs/group.svg';
  this.chatIcon = './assets/tabs/chat.svg';
  this.profIcon = './assets/tabs/user.svg';
}

...
</code>```

Appreciate if anyone would help

答:
Before, I tried to put css color into ion-tab-button and ion-icon with an ionic icon. The color change as expected, but not with custom icon.

```<code><ion-tab-button tab="news/home" style="color: blue">
  <ion-icon name="home"></ion-icon>
  <ion-label class="tab-title">News</ion-label>
</ion-tab-button>
</code>```

After a day, I try to check why the custom icon won't change the color if we do like this method. Then I try to check the Ionic SVG icon layers in Adobe Illustrator CC. and there is it.

As you can see there is <path> inside layer 1 (Ionic icon)

And the problem is my SVG file. To make this work with css properties, I just need to edit the layer.

this is the result after editing the layer, work as expected :)

Solution: You just need to add color css and get the right layer SVG icon

Further, I will update how to use custom icon when the tab is active.

UPDATE 2:

This is the working html code:

```<code><ion-tabs>
  <ion-tab-bar class="tab-bar" slot="bottom">
    <ion-tab-button tab="news/home">
      <ion-icon class="icon-news" src="./assets/tabs/md-custom-home.svg"></ion-icon>
      <ion-label class="tab-title">News</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="search">
      <ion-icon class="icon-search" src="./assets/tabs/md-custom-search.svg"></ion-icon>
      <ion-label class="tab-title">Search</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="networking">
      <ion-icon class="icon-networking" src="./assets/tabs/md-custom-networking.svg"></ion-icon>
      <ion-label class="tab-title">Networking</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>
</code>```

SCSS:

```<code>ion-tab-button {
  --color: #000000;
  --color-selected: #00cee5;
}
</code>```

just make sure to use the right SVG ;)

Body:
I'm trying to change ion-icon with custom src after ion-tab-button is clicked

What I have tried, using (click) event to trigger function and change the [src]="..." inside the ion-icon

Is there any proper way to change this hackish style?

HTML:

 <ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="news/home" (click)="changeNewsIcon()">
      <ion-icon [src]="newsIcon"></ion-icon>
      <ion-label class="tab-title">News</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="user" (click)="changeSearchIcon()">
      <ion-icon [src]="searchIcon"></ion-icon>
      <ion-label class="tab-title">Search</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="networking" (click)="changeNetworkIcon()">
      <ion-icon [src]="notiIcon"></ion-icon>
      <ion-label class="tab-title">Networking</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="chat" (click)="changeChatIcon()">
      <ion-icon [src]="chatIcon"></ion-icon>
      <ion-label class="tab-title">Chat</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="profile" (click)="changeProfIcon()">
      <ion-icon [src]="profIcon"></ion-icon>
      <ion-label class="tab-title">Profile</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

TS :

newsIcon = './assets/tabs/home.svg';
searchIcon = './assets/tabs/search.svg';
notiIcon = './assets/tabs/group.svg';
chatIcon = './assets/tabs/chat.svg';
profIcon = './assets/tabs/user.svg';

changeNewsIcon(): void {
  // change news icon
  this.newsIcon = './assets/tabs/clicked-home.svg';

  // reset others icon
  this.searchIcon = './assets/tabs/search.svg';
  this.notiIcon = './assets/tabs/group.svg';
  this.chatIcon = './assets/tabs/chat.svg';
  this.profIcon = './assets/tabs/user.svg';
}

changeSearchIcon(): void {
  // change user icon
  this.searchIcon = './assets/tabs/clicked-search.svg';

  // reset others icon
  this.newsIcon = './assets/tabs/home.svg';
  this.notiIcon = './assets/tabs/group.svg';
  this.chatIcon = './assets/tabs/chat.svg';
  this.profIcon = './assets/tabs/user.svg';
}

...

Appreciate if anyone would help

Body:
Before, I tried to put css color into ion-tab-button and ion-icon with an ionic icon. The color change as expected, but not with custom icon.

<ion-tab-button tab="news/home" style="color: blue">
  <ion-icon name="home"></ion-icon>
  <ion-label class="tab-title">News</ion-label>
</ion-tab-button>

After a day, I try to check why the custom icon won't change the color if we do like this method. Then I try to check the Ionic SVG icon layers in Adobe Illustrator CC. and there is it.

As you can see there is <path> inside layer 1 (Ionic icon)

And the problem is my SVG file. To make this work with css properties, I just need to edit the layer.

this is the result after editing the layer, work as expected :)

Solution: You just need to add color css and get the right layer SVG icon

Further, I will update how to use custom icon when the tab is active.

UPDATE 2:

This is the working html code:

<ion-tabs>
  <ion-tab-bar class="tab-bar" slot="bottom">
    <ion-tab-button tab="news/home">
      <ion-icon class="icon-news" src="./assets/tabs/md-custom-home.svg"></ion-icon>
      <ion-label class="tab-title">News</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="search">
      <ion-icon class="icon-search" src="./assets/tabs/md-custom-search.svg"></ion-icon>
      <ion-label class="tab-title">Search</ion-label>
    </ion-tab-button>
    <ion-tab-button tab="networking">
      <ion-icon class="icon-networking" src="./assets/tabs/md-custom-networking.svg"></ion-icon>
      <ion-label class="tab-title">Networking</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

SCSS:

ion-tab-button {
  --color: #000000;
  --color-selected: #00cee5;
}

just make sure to use the right SVG ;)


问:
How to format pattern text export in Powershell
I'm creating an powershell script to format .txt files and eventually be converted to a csv file (unless this can be done together). I've dug through quite a few other questions but haven't been able to figure it out. Every time I run the script below it selects all the data I need but puts it altogether on one line.

```<code>$importPath = 'C:\Example.txt'
$pattern = "<return>(.*?)</return>"

$string = Get-Content $importPath
$result = [regex]::match($string, $pattern).Groups[1].Value
$result | Out-File -FilePath 'C:\ResponseOnly.txt'
</code>```

I'd appreciate some help in figuring a way to get all the information between the <return> and </return> but still having all the data broken out on the original rows.

Example of source file:

```<code>Status: OK
Time Taken: 193
Size: 46511
Timestamp: Thu May 30 03:39:37 MDT 2019
TestStep: getReportResultCsv

----------------- Messages ------------------------------

----------------- Properties ------------------------------
Endpoint: XXXXXXXXXXXXXXXXXXXXXXX
Username: XXXXXXXXXXXXXXXXXXXXXXX
domain: XXXXXXXXXXXXXXXXXXXXXXX HTTP/1.1
Encoding: UTF-8
Password: XXXXXXXXXXXXXXXXXXXXXXX

---------------- Request ---------------------------
Request Headers: SOAPAction : ""
Authorization : Basic XXXXXXXXXXXXXXXXXXXXXXX
Connection : Keep-Alive
User-Agent : Apache-HttpClient/4.1.1 (java 1.5)
Host : XXXXXXXXXXXXXXXXXXXXXXX
Accept-Encoding : gzip,deflate
Content-Length : 378
Content-Type : text/xml;charset=UTF-8

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="XXXXXXXXXXXXXXXXXXXXXXX">
  <soapenv:Header/>
   <soapenv:Body>
      <ser:getReportResultCsv>
         <!--Optional:-->
         <identifier>A0294584B2F933513rt0.c.ie.oF0BBB@5p70B7FsBlEf4v490cAm</identifier>
      </ser:getReportResultCsv>
   </soapenv:Body>
</soapenv:Envelope>

---------------- Response --------------------------
Response Headers: Transfer-Encoding : chunked
Server : nginx
Access-Control-Allow-Origin : *
Access-Control-Allow-Methods : POST,GET,OPTIONS
Connection : keep-alive
Content-Encoding : gzip
Set-Cookie : clientId=XXXXXXXXXXXXXXXXXXXXXXX
#status# : HTTP/1.1 200 OK
Date : Thu, 30 May 2019 09:39:37 GMT
Content-Type : text/xml;charset=UTF-8

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header/>
   <env:Body>
      <ns2:getReportResultCsvResponse xmlns:ns2="XXXXXXXXXXXXXXXXXXXXXXX">
         <return>DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44</return>
      </ns2:getReportResultCsvResponse>
   </env:Body>
</env:Envelope>
</code>```

Example of how file should be:

```<code>DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44
</code>```

答:
_[

edit - i missed the post by TheMadTechnician. [sigh ...] i will leave this here just in case the minor differences help the OP a bit.

edit 2 - TheMadTechnician pointed out that using the -Raw parameter for Get-Content was unneeded in this case. removed that and added the needed -split to make a proper fake Get-Content data set.

]_

here's one way to get that data into a CSV. since it is valid XML, you can use the [xml] type accelerator to convert it from text to an XML object. then you can navigate the XML to the place where the csv data is. once you are there, you can feed that to the ConvertFrom-CSV cmdlet to make an array of objects.

then, finally [grin], you can export that nice, neat array to a CSV file with Export-CSV.

here's the code ...

```<code># fake reading in a text file
#    in real life, use Get-Content
$InStuff = @'
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header/>
   <env:Body>
      <ns2:getReportResultCsvResponse xmlns:ns2="XXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
         <return>DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44</return>
      </ns2:getReportResultCsvResponse>
   </env:Body>
</env:Envelope>
'@ -split [System.Environment]::NewLine

$IS_XML = [xml]$InStuff
$ReportResult = $IS_XML.Envelope.Body.getReportResultCsvResponse.return |
    ConvertFrom-Csv

# on screen
$ReportResult

# to CSV
$ReportResult |
    Export-Csv -LiteralPath "$env:TEMP\TaylorGreen_-_ReportResult.csv" -NoTypeInformation
</code>```

truncated screen output ...

```<code>DATE                         : 2019/04/04
AGENT GROUP                  : Billy Bob
AGENT NAME                   : Joe Joseph
CALLS                        : 6
HANDLE TIME                  : 04:15:53
Average HANDLE TIME          : 00:42:39
HOLD TIME                    : 00:00:00
Average HOLD TIME            : 00:00:00
Average AFTER CALL WORK TIME : 00:01:55

[*...snip...*]

DATE                         : 2019/04/08
AGENT GROUP                  : Billy Bob
AGENT NAME                   : Joe Joseph
CALLS                        : 11
HANDLE TIME                  : 03:20:21
Average HANDLE TIME          : 00:18:13
HOLD TIME                    : 00:00:03
Average HOLD TIME            : 00:00:00
Average AFTER CALL WORK TIME : 00:02:44
</code>```

csv file file content ...

```<code>"DATE","AGENT GROUP","AGENT NAME","CALLS","HANDLE TIME","Average HANDLE TIME","HOLD TIME","Average HOLD TIME","Average AFTER CALL WORK TIME"
"2019/04/04","Billy Bob","Joe Joseph","6","04:15:53","00:42:39","00:00:00","00:00:00","00:01:55"
"2019/04/05","Billy Bob","Joe Joseph","14","04:39:26","00:19:58","00:47:53","00:03:25","00:02:20"
"2019/04/06","Billy Bob","Joe Joseph","11","06:33:13","00:35:45","00:17:21","00:01:35","00:04:30"
"2019/04/07","Billy Bob","Joe Joseph","13","05:47:06","00:26:42","00:02:03","00:00:09","00:02:27"
"2019/04/08","Billy Bob","Joe Joseph","11","03:20:21","00:18:13","00:00:03","00:00:00","00:02:44"
</code>```

Body:
I'm creating an powershell script to format .txt files and eventually be converted to a csv file (unless this can be done together). I've dug through quite a few other questions but haven't been able to figure it out. Every time I run the script below it selects all the data I need but puts it altogether on one line.

$importPath = 'C:\Example.txt'
$pattern = "<return>(.*?)</return>"

$string = Get-Content $importPath
$result = [regex]::match($string, $pattern).Groups[1].Value
$result | Out-File -FilePath 'C:\ResponseOnly.txt'

I'd appreciate some help in figuring a way to get all the information between the <return> and </return> but still having all the data broken out on the original rows.

Example of source file:

Status: OK
Time Taken: 193
Size: 46511
Timestamp: Thu May 30 03:39:37 MDT 2019
TestStep: getReportResultCsv

----------------- Messages ------------------------------

----------------- Properties ------------------------------
Endpoint: XXXXXXXXXXXXXXXXXXXXXXX
Username: XXXXXXXXXXXXXXXXXXXXXXX
domain: XXXXXXXXXXXXXXXXXXXXXXX HTTP/1.1
Encoding: UTF-8
Password: XXXXXXXXXXXXXXXXXXXXXXX

---------------- Request ---------------------------
Request Headers: SOAPAction : ""
Authorization : Basic XXXXXXXXXXXXXXXXXXXXXXX
Connection : Keep-Alive
User-Agent : Apache-HttpClient/4.1.1 (java 1.5)
Host : XXXXXXXXXXXXXXXXXXXXXXX
Accept-Encoding : gzip,deflate
Content-Length : 378
Content-Type : text/xml;charset=UTF-8

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="XXXXXXXXXXXXXXXXXXXXXXX">
  <soapenv:Header/>
   <soapenv:Body>
      <ser:getReportResultCsv>

         <identifier>A0294584B2F933513rt0.c.ie.oF0BBB@5p70B7FsBlEf4v490cAm</identifier>
      </ser:getReportResultCsv>
   </soapenv:Body>
</soapenv:Envelope>

---------------- Response --------------------------
Response Headers: Transfer-Encoding : chunked
Server : nginx
Access-Control-Allow-Origin : *
Access-Control-Allow-Methods : POST,GET,OPTIONS
Connection : keep-alive
Content-Encoding : gzip
Set-Cookie : clientId=XXXXXXXXXXXXXXXXXXXXXXX
#status# : HTTP/1.1 200 OK
Date : Thu, 30 May 2019 09:39:37 GMT
Content-Type : text/xml;charset=UTF-8

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header/>
   <env:Body>
      <ns2:getReportResultCsvResponse xmlns:ns2="XXXXXXXXXXXXXXXXXXXXXXX">
         <return>DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44</return>
      </ns2:getReportResultCsvResponse>
   </env:Body>
</env:Envelope>

Example of how file should be:

DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44

Body:
_[

edit - i missed the post by TheMadTechnician. [sigh ...] i will leave this here just in case the minor differences help the OP a bit.

edit 2 - TheMadTechnician pointed out that using the -Raw parameter for Get-Content was unneeded in this case. removed that and added the needed -split to make a proper fake Get-Content data set.

]_

here's one way to get that data into a CSV. since it is valid XML, you can use the [xml] type accelerator to convert it from text to an XML object. then you can navigate the XML to the place where the csv data is. once you are there, you can feed that to the ConvertFrom-CSV cmdlet to make an array of objects.

then, finally [grin], you can export that nice, neat array to a CSV file with Export-CSV.

here's the code ...

# fake reading in a text file
#    in real life, use Get-Content
$InStuff = @'
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header/>
   <env:Body>
      <ns2:getReportResultCsvResponse xmlns:ns2="XXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
         <return>DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44</return>
      </ns2:getReportResultCsvResponse>
   </env:Body>
</env:Envelope>
'@ -split [System.Environment]::NewLine

$IS_XML = [xml]$InStuff
$ReportResult = $IS_XML.Envelope.Body.getReportResultCsvResponse.return |
    ConvertFrom-Csv

# on screen
$ReportResult

# to CSV
$ReportResult |
    Export-Csv -LiteralPath "$env:TEMP\TaylorGreen_-_ReportResult.csv" -NoTypeInformation

truncated screen output ...

DATE                         : 2019/04/04
AGENT GROUP                  : Billy Bob
AGENT NAME                   : Joe Joseph
CALLS                        : 6
HANDLE TIME                  : 04:15:53
Average HANDLE TIME          : 00:42:39
HOLD TIME                    : 00:00:00
Average HOLD TIME            : 00:00:00
Average AFTER CALL WORK TIME : 00:01:55

[*...snip...*]

DATE                         : 2019/04/08
AGENT GROUP                  : Billy Bob
AGENT NAME                   : Joe Joseph
CALLS                        : 11
HANDLE TIME                  : 03:20:21
Average HANDLE TIME          : 00:18:13
HOLD TIME                    : 00:00:03
Average HOLD TIME            : 00:00:00
Average AFTER CALL WORK TIME : 00:02:44

csv file file content ...

"DATE","AGENT GROUP","AGENT NAME","CALLS","HANDLE TIME","Average HANDLE TIME","HOLD TIME","Average HOLD TIME","Average AFTER CALL WORK TIME"
"2019/04/04","Billy Bob","Joe Joseph","6","04:15:53","00:42:39","00:00:00","00:00:00","00:01:55"
"2019/04/05","Billy Bob","Joe Joseph","14","04:39:26","00:19:58","00:47:53","00:03:25","00:02:20"
"2019/04/06","Billy Bob","Joe Joseph","11","06:33:13","00:35:45","00:17:21","00:01:35","00:04:30"
"2019/04/07","Billy Bob","Joe Joseph","13","05:47:06","00:26:42","00:02:03","00:00:09","00:02:27"
"2019/04/08","Billy Bob","Joe Joseph","11","03:20:21","00:18:13","00:00:03","00:00:00","00:02:44"


问:
How to use SDL2 Texture as sort of updating canvas?
I am trying to create a dynamic plotter in SDL2 for an embedded project. Currently, the code executes on both architectures, x86, and ARM. On x86 I get a smooth running plotter, however, on ARM it runs very slow at a fraction of the frames I get on x86. I am pretty sure this is because I rerender every pixel on the surface at this is a massive overheat on the embedded device.

I tried rendering the new content to a texture, copy it to the renderer and then render, but this did not work at all.

Due to the double-buffering, I have to clear every frame. Otherwise, I will "drop" changes. But I also need to render the old data points and only overwrite them when the plotter reaches them again.

Is there a way in SDL2 to save these data points to some sort of canvas and only add (redraw) the newly added ones?

Heres my source code:

Plotter.cpp

```<code>#include <SDL2/SDL.h>
#include <stdio.h>
#include "PlotterHelper.h"

/*Implementation*/
int main(int arhc, char * argv[])
{
    //Top and bottom viewport
    SDL_Rect topViewport;
    SDL_Rect bottomViewport;
    topViewport = CreateViewPort(0,0, SCREEN_WIDTH, (SCREEN_HEIGHT/2));
    bottomViewport = CreateViewPort(0,(SCREEN_HEIGHT/2), SCREEN_WIDTH, SCREEN_HEIGHT/2);

    float timeFrame = 4.0;
    int updateWidth = round(SCREEN_WIDTH/(60.0 * timeFrame));

    uint8_t backgroundColor = 0xff;

    int delayTime = 0;
    int sinusScale = 0;
    int rectWidth = RECT_WIDTH;
    bool rectEnd = false;

    SDL_Point points[SCREEN_WIDTH] = {0,0};
    int pointPosition = 0;

    if (!init())
    {
        printf("Init failed!\n");
    }
    else
    {

        SDL_ShowCursor(SDL_DISABLE);
        //Main lopp flag
        bool quit = false;
        //Event handler
        SDL_Event event;

        //While application is running
        while(!quit)
        {
            //Handle events on queue
            while (SDL_PollEvent( &event) != 0)
            {
                //User requests quit
                if(event.type == SDL_QUIT)
                {
                    quit = true;
                }
                else if(event.type == SDL_KEYDOWN)
                {
                    switch(event.key.keysym.sym)
                    {
                    case SDLK_w:
                        delayTime += 50;
                        if(delayTime > 5000)
                            delayTime = 5000;
                        break;
                    case SDLK_s:
                        delayTime -= 50;
                        if(delayTime < 0)
                            delayTime = 0;
                        break;
                    case SDLK_d:
                        timeFrame -= 1;
                        if(timeFrame < 1)
                            timeFrame = 1.0;
                        updateWidth = round(SCREEN_WIDTH/(60.0 * timeFrame));
                        printf("timeFrame = %lf\n", timeFrame);
                        break;
                    case SDLK_a:
                        timeFrame += 1;
                        if(timeFrame > 44)
                            timeFrame = 44.0;
                        updateWidth = round(SCREEN_WIDTH/(60.0 * timeFrame));
                        printf("timeFrame = %lf\n", timeFrame);
                        break;
                    case SDLK_r:
                        if(backgroundColor == 0x3f)
                            break;
                        else
                        {
                            ++backgroundColor;
                            break;
                        }
                    case SDLK_f:
                        if(backgroundColor == 0x00)
                                break;
                        else
                        {
                            --backgroundColor;
                            break;
                        }
                    }
                }
            }

            //Reset Plotter when the end of the window was reached
            if(pointPosition > SCREEN_WIDTH-1)
            {
                pointPosition = 0;
                sinusScale = (rand() % 100 + 1) - 50;
                rectWidth = RECT_WIDTH;
                rectEnd = false;
            }

            //Handler eraser when he reaches end of window
            if(((SCREEN_WIDTH-1) - pointPosition) < RECT_WIDTH)
            {
                rectWidth = (SCREEN_WIDTH -1) - pointPosition;
                rectEnd = true;

            }

            //Clear screen
            SDL_SetRenderDrawColor(gRenderer, backgroundColor, backgroundColor, backgroundColor, 0xff);
            SDL_RenderClear(gRenderer);

            //Draw top viewport
            SDL_RenderSetViewport( gRenderer, &topViewport );

            SDL_SetRenderDrawColor(gRenderer, 0x00, 0x66, 0x00, 0xff);
            for(int iterator = 0; iterator <= SCREEN_WIDTH -1; ++iterator)
            {
                SDL_RenderDrawLine(
                        gRenderer,
                        points[iterator].x,
                        0,
                        points[iterator].x,
                        SCREEN_HEIGHT/2);
            }

            PlotEraser(rectEnd, backgroundColor, rectWidth,points[pointPosition].x );

            //raw bottom viewport
            SDL_RenderSetViewport( gRenderer, &bottomViewport );

            SDL_SetRenderDrawColor(gRenderer, 0x00, 0x66, 0x00, 0xff);
            for(int iterator = 0; iterator <= SCREEN_WIDTH -1; ++iterator)
                {
                    SDL_RenderDrawLine(
                            gRenderer,
                            points[iterator].x,
                            SCREEN_HEIGHT/2,
                            points[iterator].x,
                            points[iterator].y);
                }

            PlotEraser(rectEnd, backgroundColor, rectWidth,points[pointPosition].x );

            for(int iterator = pointPosition; iterator <= pointPosition + updateWidth; ++iterator)
            {
                points[iterator].x = iterator;
                points[iterator].y = round(((SCREEN_HEIGHT/4 )* sin(iterator/(100.0+sinusScale))) + SCREEN_HEIGHT/4);
            }
            pointPosition += updateWidth;

            //Update Screen
            SDL_RenderPresent(gRenderer);

            SDL_Delay(delayTime);
        }

    }

    //Free resources and close SDL
    close();

    return 0;
}

/*End of File*/

</code>```

PlotterHelper.cpp

```<code>/*Includes*/

#include "PlotterHelper.h"

SDL_Window  * gWindow = NULL;
SDL_Renderer * gRenderer = NULL;
SDL_Renderer * intermediate = NULL;

/*Implementation*/

/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
bool init()
{
    //Init  flag
    bool success = true;

    //Init SDL
    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        success = false;
    }
    else
    {
        //Set texture filtering to linear
        if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
        {
            printf( "Warning: Linear texture filtering not enabled!" );
        }

        //Set VSYNC
        if( !SDL_SetHint( SDL_HINT_RENDER_VSYNC, "1" ) )
        {
            printf( "Warning: VSYNC not enabled!" );
        }

        //Create window
        gWindow = SDL_CreateWindow(
                "SDL Plotter",
                SDL_WINDOWPOS_UNDEFINED,
                SDL_WINDOWPOS_UNDEFINED,
                SCREEN_WIDTH,
                SCREEN_HEIGHT,
                SDL_WINDOW_SHOWN );
        if (NULL == gWindow)
        {
            printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
            success = false;
        }
        else
        {
            //Create renderer for window
            gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED );
            if(NULL == gRenderer)
            {
                printf("Renderer could not be created! SDLError: %s\n", SDL_GetError());
                success = false;
            }
            else
            {
                //Initialise renderer colour
                SDL_SetRenderDrawColor(gRenderer, 0xff, 0xff, 0xff, 0xff);
            }

        }
    }
    return success;
}

/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
void close()
{
    //Destroy window
    SDL_DestroyRenderer(gRenderer);
    SDL_DestroyWindow(gWindow);
    gRenderer = NULL;
    gWindow = NULL;

    //Quit SDL subsystems
    SDL_Quit();
}

/*********************************************************************
 *********************************************************************
 *********************************************************************
*/

SDL_Rect CreateViewPort(int x, int y, int w, int h)
{
    SDL_Rect Viewport;
    Viewport.x = x;
    Viewport.y = y;
    Viewport.w = w;
    Viewport.h = h;

    return Viewport;
}
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
void PlotEraser(bool rectEnd, uint8_t backgroundColor, int rectWidth, int x)
{
    SDL_Rect fillRectBot = {x, 0, rectWidth, SCREEN_HEIGHT/2};

    SDL_SetRenderDrawColor(gRenderer, backgroundColor, backgroundColor, backgroundColor, 0xff);
    SDL_RenderFillRect(gRenderer, &fillRectBot);

    if(rectEnd)
    {
        int startRecWidth = RECT_WIDTH - rectWidth;

        SDL_Rect startRec = {0, 0, startRecWidth, SCREEN_HEIGHT/2};
        SDL_RenderFillRect(gRenderer, &startRec);
    }
}

/*End of File*/

</code>```

PlotterHelper.h

```<code>

#ifndef PLOTTER_HELPER_H_
#define PLOTTER_HELPER_H_

#include <SDL2/SDL.h>
#include <stdio.h>
#include <cmath>
#include <string>
/*Globals*/

//Screen  constants
const int SCREEN_WIDTH = 1024;
const int SCREEN_HEIGHT = 768;
const int RECT_WIDTH = 10;

//The window we'll be rendering to
extern SDL_Window * gWindow;
//The window renderer
extern SDL_Renderer * gRenderer;
extern SDL_Renderer * intermediate;

/*Prototypes*/
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
//Starts up SDL and creates window
bool init();
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
//Free media and shut down SDL
void close();
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
//CreateVieport
SDL_Rect CreateViewPort(int x, int y, int w, int h);
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
//Plot Eraser
void PlotEraser(bool rectEnd, uint8_t backgroundColor, int rectWidth, int x);
#endif /* PLOTTER_HELPER_H_ */
/*End of File*/

</code>```

答:
You probably have a couple of options that can help:

Use a texture render target

You ought to be able to accomplish this using a "render target texture". That is an SDL_Texture you create (see SDL_CreateTexture) with the SDL_TEXTUREACCESS_TARGET flag.

You would draw new points to this texture by calling SDL_SetRenderTarget and passing this texture before then rendering the points.

your main loop would then need to call SDL_SetRenderTarget and pass nullptr to restore the window as the rendering target. You then render your texture to the window every frame.

The SDL documentation has a small sample demoing how to use a render target texture.

update to SDL 2.0.9 and use render batching

the latest version of SDL 2 supports render batching if you set SDL_HINT_RENDER_BATCHING (SDL_SetHint(SDL_HINT_RENDER_BATCHING, "1");). You should use SDL_CreateWindowAndRenderer() to ensure you have batching enabled.

This may not do anything if your platform doesnt support hardware acceleration. You can use this in conjunction with a render target. read about SDL render batching here.

Batch your rects/points together

This is separate from render batching and should work on any version of SDL 2.

If you can, collect all your rectangles/points together in an array you can use
SDL_RenderDrawPoints or SDL_RenderDrawRects to have SDL do them all at once which should improve performance even if you have no hardware acceleration. This can be used in conjunction with a render target.

Ditch SDL_Renderer/SDL_Texture

If your device lacks hardware acceleration, then it might be faster to ditch SDL_Renderer and instead use SDL_GetWindowSurface to get the SDL_Surface for the window and use SDL_BlitSurface (or manually set pixels via surface->pixels) to draw directly to that then update the window with SDL_UpdateWindowSurface. See also SDL_UpdateWindowSurfaceRects for how to only update the rectangles you are changing for even better performance.

You will need to familiarize yourself with SDL_Surface as you will need to inspect the pixel format of the window surface in order to update it correctly should you choose to directly manipulate the pixels.

Body:
I am trying to create a dynamic plotter in SDL2 for an embedded project. Currently, the code executes on both architectures, x86, and ARM. On x86 I get a smooth running plotter, however, on ARM it runs very slow at a fraction of the frames I get on x86. I am pretty sure this is because I rerender every pixel on the surface at this is a massive overheat on the embedded device.

I tried rendering the new content to a texture, copy it to the renderer and then render, but this did not work at all.

Due to the double-buffering, I have to clear every frame. Otherwise, I will "drop" changes. But I also need to render the old data points and only overwrite them when the plotter reaches them again.

Is there a way in SDL2 to save these data points to some sort of canvas and only add (redraw) the newly added ones?

Heres my source code:

Plotter.cpp

#include <SDL2/SDL.h>
#include <stdio.h>
#include "PlotterHelper.h"

/*Implementation*/
int main(int arhc, char * argv[])
{
    //Top and bottom viewport
    SDL_Rect topViewport;
    SDL_Rect bottomViewport;
    topViewport = CreateViewPort(0,0, SCREEN_WIDTH, (SCREEN_HEIGHT/2));
    bottomViewport = CreateViewPort(0,(SCREEN_HEIGHT/2), SCREEN_WIDTH, SCREEN_HEIGHT/2);

    float timeFrame = 4.0;
    int updateWidth = round(SCREEN_WIDTH/(60.0 * timeFrame));

    uint8_t backgroundColor = 0xff;

    int delayTime = 0;
    int sinusScale = 0;
    int rectWidth = RECT_WIDTH;
    bool rectEnd = false;

    SDL_Point points[SCREEN_WIDTH] = {0,0};
    int pointPosition = 0;

    if (!init())
    {
        printf("Init failed!\n");
    }
    else
    {

        SDL_ShowCursor(SDL_DISABLE);
        //Main lopp flag
        bool quit = false;
        //Event handler
        SDL_Event event;

        //While application is running
        while(!quit)
        {
            //Handle events on queue
            while (SDL_PollEvent( &event) != 0)
            {
                //User requests quit
                if(event.type == SDL_QUIT)
                {
                    quit = true;
                }
                else if(event.type == SDL_KEYDOWN)
                {
                    switch(event.key.keysym.sym)
                    {
                    case SDLK_w:
                        delayTime += 50;
                        if(delayTime > 5000)
                            delayTime = 5000;
                        break;
                    case SDLK_s:
                        delayTime -= 50;
                        if(delayTime < 0)
                            delayTime = 0;
                        break;
                    case SDLK_d:
                        timeFrame -= 1;
                        if(timeFrame < 1)
                            timeFrame = 1.0;
                        updateWidth = round(SCREEN_WIDTH/(60.0 * timeFrame));
                        printf("timeFrame = %lf\n", timeFrame);
                        break;
                    case SDLK_a:
                        timeFrame += 1;
                        if(timeFrame > 44)
                            timeFrame = 44.0;
                        updateWidth = round(SCREEN_WIDTH/(60.0 * timeFrame));
                        printf("timeFrame = %lf\n", timeFrame);
                        break;
                    case SDLK_r:
                        if(backgroundColor == 0x3f)
                            break;
                        else
                        {
                            ++backgroundColor;
                            break;
                        }
                    case SDLK_f:
                        if(backgroundColor == 0x00)
                                break;
                        else
                        {
                            --backgroundColor;
                            break;
                        }
                    }
                }
            }

            //Reset Plotter when the end of the window was reached
            if(pointPosition > SCREEN_WIDTH-1)
            {
                pointPosition = 0;
                sinusScale = (rand() % 100 + 1) - 50;
                rectWidth = RECT_WIDTH;
                rectEnd = false;
            }

            //Handler eraser when he reaches end of window
            if(((SCREEN_WIDTH-1) - pointPosition) < RECT_WIDTH)
            {
                rectWidth = (SCREEN_WIDTH -1) - pointPosition;
                rectEnd = true;

            }

            //Clear screen
            SDL_SetRenderDrawColor(gRenderer, backgroundColor, backgroundColor, backgroundColor, 0xff);
            SDL_RenderClear(gRenderer);

            //Draw top viewport
            SDL_RenderSetViewport( gRenderer, &topViewport );

            SDL_SetRenderDrawColor(gRenderer, 0x00, 0x66, 0x00, 0xff);
            for(int iterator = 0; iterator <= SCREEN_WIDTH -1; ++iterator)
            {
                SDL_RenderDrawLine(
                        gRenderer,
                        points[iterator].x,
                        0,
                        points[iterator].x,
                        SCREEN_HEIGHT/2);
            }

            PlotEraser(rectEnd, backgroundColor, rectWidth,points[pointPosition].x );

            //raw bottom viewport
            SDL_RenderSetViewport( gRenderer, &bottomViewport );

            SDL_SetRenderDrawColor(gRenderer, 0x00, 0x66, 0x00, 0xff);
            for(int iterator = 0; iterator <= SCREEN_WIDTH -1; ++iterator)
                {
                    SDL_RenderDrawLine(
                            gRenderer,
                            points[iterator].x,
                            SCREEN_HEIGHT/2,
                            points[iterator].x,
                            points[iterator].y);
                }

            PlotEraser(rectEnd, backgroundColor, rectWidth,points[pointPosition].x );

            for(int iterator = pointPosition; iterator <= pointPosition + updateWidth; ++iterator)
            {
                points[iterator].x = iterator;
                points[iterator].y = round(((SCREEN_HEIGHT/4 )* sin(iterator/(100.0+sinusScale))) + SCREEN_HEIGHT/4);
            }
            pointPosition += updateWidth;

            //Update Screen
            SDL_RenderPresent(gRenderer);

            SDL_Delay(delayTime);
        }

    }

    //Free resources and close SDL
    close();

    return 0;
}

/*End of File*/

PlotterHelper.cpp

/*Includes*/

#include "PlotterHelper.h"

SDL_Window  * gWindow = NULL;
SDL_Renderer * gRenderer = NULL;
SDL_Renderer * intermediate = NULL;

/*Implementation*/

/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
bool init()
{
    //Init  flag
    bool success = true;

    //Init SDL
    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        success = false;
    }
    else
    {
        //Set texture filtering to linear
        if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
        {
            printf( "Warning: Linear texture filtering not enabled!" );
        }

        //Set VSYNC
        if( !SDL_SetHint( SDL_HINT_RENDER_VSYNC, "1" ) )
        {
            printf( "Warning: VSYNC not enabled!" );
        }

        //Create window
        gWindow = SDL_CreateWindow(
                "SDL Plotter",
                SDL_WINDOWPOS_UNDEFINED,
                SDL_WINDOWPOS_UNDEFINED,
                SCREEN_WIDTH,
                SCREEN_HEIGHT,
                SDL_WINDOW_SHOWN );
        if (NULL == gWindow)
        {
            printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
            success = false;
        }
        else
        {
            //Create renderer for window
            gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED );
            if(NULL == gRenderer)
            {
                printf("Renderer could not be created! SDLError: %s\n", SDL_GetError());
                success = false;
            }
            else
            {
                //Initialise renderer colour
                SDL_SetRenderDrawColor(gRenderer, 0xff, 0xff, 0xff, 0xff);
            }

        }
    }
    return success;
}

/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
void close()
{
    //Destroy window
    SDL_DestroyRenderer(gRenderer);
    SDL_DestroyWindow(gWindow);
    gRenderer = NULL;
    gWindow = NULL;

    //Quit SDL subsystems
    SDL_Quit();
}

/*********************************************************************
 *********************************************************************
 *********************************************************************
*/

SDL_Rect CreateViewPort(int x, int y, int w, int h)
{
    SDL_Rect Viewport;
    Viewport.x = x;
    Viewport.y = y;
    Viewport.w = w;
    Viewport.h = h;

    return Viewport;
}
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
void PlotEraser(bool rectEnd, uint8_t backgroundColor, int rectWidth, int x)
{
    SDL_Rect fillRectBot = {x, 0, rectWidth, SCREEN_HEIGHT/2};

    SDL_SetRenderDrawColor(gRenderer, backgroundColor, backgroundColor, backgroundColor, 0xff);
    SDL_RenderFillRect(gRenderer, &fillRectBot);

    if(rectEnd)
    {
        int startRecWidth = RECT_WIDTH - rectWidth;

        SDL_Rect startRec = {0, 0, startRecWidth, SCREEN_HEIGHT/2};
        SDL_RenderFillRect(gRenderer, &startRec);
    }
}

/*End of File*/

PlotterHelper.h

#ifndef PLOTTER_HELPER_H_
#define PLOTTER_HELPER_H_

#include <SDL2/SDL.h>
#include <stdio.h>
#include <cmath>
#include <string>
/*Globals*/

//Screen  constants
const int SCREEN_WIDTH = 1024;
const int SCREEN_HEIGHT = 768;
const int RECT_WIDTH = 10;

//The window we'll be rendering to
extern SDL_Window * gWindow;
//The window renderer
extern SDL_Renderer * gRenderer;
extern SDL_Renderer * intermediate;

/*Prototypes*/
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
//Starts up SDL and creates window
bool init();
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
//Free media and shut down SDL
void close();
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
//CreateVieport
SDL_Rect CreateViewPort(int x, int y, int w, int h);
/*********************************************************************
 *********************************************************************
 *********************************************************************
*/
//Plot Eraser
void PlotEraser(bool rectEnd, uint8_t backgroundColor, int rectWidth, int x);
#endif /* PLOTTER_HELPER_H_ */
/*End of File*/


问:
JavaScript - Generate a random number between 1 and 5, but never the same number twice consecutively
I have some simple code to generate a random number between 1 and 5.

Depending on what number is pulled, a certain sound file will play. However, how could I prevent this simple program from generating the same number twice in a row consequently making the same audio to play twice?

For example: a roll of the dice is never the same twice consecutively, meaning you cannot roll a 2 if you just rolled a 2 etc.

I was experimenting with if else statements and kind of backed myself into a corner. I know this may seem like a simple problem but I'm at my wits end on this one.

```<code><!DOCTYPE html>
<html>
<body>

  <p>Click the button to display a random number between 1 and 5.</p>

  <button onclick="myFunction()">ROLL DICE</button>

  <p id="demo"></p>

  <script>
    function myFunction() {
      var x = Math.floor((Math.random() * 5) + 1);
      document.getElementById("demo").innerHTML = x;
    }
  </script>
</body>
</html>
</code>```

答:
Here is a function that you can use. It's quite simple:

min: minimum range;
max: maximum range;
length: how many numbers to generate.

Function and usage:

```<code>const randomUniqueNumbers = (min, max, length=1) =>
{
    const limit = max-min+1;
    if (min > max || max < min){
       throw new Error(`Parameter "min" has to be smaller than "max" and vice-versa.`)
    }
    else if (length > limit){
      throw new Error(`The length between ${min} and ${max} cannot exceed ${limit}.`)
    }

    let uniqueNumbers = [];
    let number;
    for(var i=0; i<length; i++){
        do
            number = Math.floor(Math.random() * limit) + min;
        while(uniqueNumbers.indexOf(number) !== -1);

       uniqueNumbers[i] = number;
    }

    return uniqueNumbers;
}

console.log(randomUniqueNumbers(20, 30, 3)); //[24, 27, 26]
console.log(randomUniqueNumbers(100, 1000, 5)) //[865, 438, 798, 247, 232]
console.log(randomUniqueNumbers(1, 5, 5)) //[5, 2, 1, 3, 4]
</code>```

Body:
I have some simple code to generate a random number between 1 and 5.

Depending on what number is pulled, a certain sound file will play. However, how could I prevent this simple program from generating the same number twice in a row consequently making the same audio to play twice?

For example: a roll of the dice is never the same twice consecutively, meaning you cannot roll a 2 if you just rolled a 2 etc.

I was experimenting with if else statements and kind of backed myself into a corner. I know this may seem like a simple problem but I'm at my wits end on this one.

<!DOCTYPE html>

Click the button to display a random number between 1 and 5.

  <button onclick="myFunction()">ROLL DICE</button>

Body:
Here is a function that you can use. It's quite simple:

min: minimum range;
max: maximum range;
length: how many numbers to generate.

Function and usage:

const randomUniqueNumbers = (min, max, length=1) =>
{
    const limit = max-min+1;
    if (min > max || max < min){
       throw new Error(`Parameter "min" has to be smaller than "max" and vice-versa.`)
    }
    else if (length > limit){
      throw new Error(`The length between ${min} and ${max} cannot exceed ${limit}.`)
    }

    let uniqueNumbers = [];
    let number;
    for(var i=0; i<length; i++){
        do
            number = Math.floor(Math.random() * limit) + min;
        while(uniqueNumbers.indexOf(number) !== -1);

       uniqueNumbers[i] = number;
    }

    return uniqueNumbers;
}

console.log(randomUniqueNumbers(20, 30, 3)); //[24, 27, 26]
console.log(randomUniqueNumbers(100, 1000, 5)) //[865, 438, 798, 247, 232]
console.log(randomUniqueNumbers(1, 5, 5)) //[5, 2, 1, 3, 4]


问:
I am facing this android exception when i run android application on (Android-1.6) device and application is build in android platform(2.2
I am facing this android exception when i run android application on (Android-1.6) device and application is build in android platform(2.2)..do you have any solution to fix this exception if so please replay...

exception shows on logcat....is

04-12 19:45:30.498: ERROR/AndroidRuntime(476): Uncaught handler: thread main exiting due to uncaught exception
04-12 19:45:30.549: ERROR/AndroidRuntime(476): java.lang.VerifyError: org.exmp.pickcontactquicksms.Controller
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at java.lang.Class.newInstanceImpl(Native Method)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at java.lang.Class.newInstance(Class.java:1472)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at android.app.Instrumentation.newActivity(Instrumentation.java:1097)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2316)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at android.os.Looper.loop(Looper.java:123)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at android.app.ActivityThread.main(ActivityThread.java:4203)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at java.lang.reflect.Method.invokeNative(Native Method)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at java.lang.reflect.Method.invoke(Method.java:521)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
04-12 19:45:30.549: ERROR/AndroidRuntime(476):     at dalvik.system.NativeStart.main(Native Method)

答: That's not possible. You can run an application made for 1.6 on a device with 2.2, but not the other way around...</p>


问:
UWP sqlite-net Async database access
On my UWP app, I'm using sqlite-net to access the database. According to their GitHub Page I'm using Source Installation. Now I want to migrate to using the Nuget package (To get the latest updates) and they have mentioned getting the PCL package. When I add the PCL package I don't have Async operations available like it was on Source Installation. Please let me know how to proceed on this matter.

When it comes to UWP and I want to use sqlite-net I see soo many nugets in VS 2015 Nuget Package Manager. Please help me which one to choose. (Selected package should not be deprecated in the near future and should be developed actively by the vendor, providing continues updates)

答:
Based on your requirements of active development and support, have a look at EntityFramework Core with their SQLite Provider: https://learn.microsoft.com/en-us/ef/core/get-started/uwp/getting-started

This, however, limits the target version of platform to: Windows 10 Fall Creators Update (10.0; build 16299.0)

The package you have highlighted is a wrapper around the SQLite C library developed by the SQLite authors. There is no guarantee that the wrapper lib will always be under active development, but the SQLite C library should be.

Title: UWP sqlite-net Async database access


问:
ChartJS with ChartJS DataLabels: Change Color per Dataset for Value Labels
I'm using ChartJS with the plug-in ChartJS DataLabels to show text values right next to the points (who would have thought that a plugin is necessary for this basic task, but I digress).

My issue I need to vary the color of my text labels along with the individual dataset. But so far I haven't found a solution. I'm adding new datasets dynamically, they're not statically pre-loaded. The color should match the color of the dataset.

Suppose I have

```<code>var colorpalette = ["red", "blue", "green", "magenta", "yellow", "brown", "purple", "orange", "black", "gray"];
var currseriesnum = 0;
var chart = null;

function setUpChart() {

    var ctx = document.getElementById('chartArea').getContext('2d');
    chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: monthnames,
            datasets: [] // Initially blank - series added dynamically with chart.update()
        },
        options: {
            legend: {
                display: false
            },
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            },
            plugins: {  // ChartsJS DataLabels initialized here
                datalabels: {
                    anchor: 'end',
                    align: 'bottom',
                    formatter: Math.round,
                    font: {
                      weight: 'bold',
                      size: 16
                    },
                    color: colorpalette[currseriesnum] // Pick color dynamically
                }
            }
        }
    });

}
</code>```

Doesn't work. Also tried a function, color: function(context), but unsure how to retrieve the current index of the dataset I'm getting here.

I'm adding series to the chart dynamically (initially empty) as below, and incrementing the global var currseriesnum.

```<code>chart.data.datasets.push({
    label: keyValueSelection.label,
    fill: false,
    data: keyValueSelection.value,
    borderColor: colorpalette[currseriesnum],
    borderWidth: 2
});
chart.update();
currseriesnum++;
</code>```

答:
They gave me the answer on the ChartJS DataLabels forum:</p>

```<code>plugins: {
    datalabels: {
        color: function(ctx) {
            // use the same color as the border
            return ctx.dataset.borderColor
        }
    }
}
</code>```

Body:
I'm using ChartJS with the plug-in ChartJS DataLabels to show text values right next to the points (who would have thought that a plugin is necessary for this basic task, but I digress).

My issue I need to vary the color of my text labels along with the individual dataset. But so far I haven't found a solution. I'm adding new datasets dynamically, they're not statically pre-loaded. The color should match the color of the dataset.

Suppose I have

var colorpalette = ["red", "blue", "green", "magenta", "yellow", "brown", "purple", "orange", "black", "gray"];
var currseriesnum = 0;
var chart = null;

function setUpChart() {

    var ctx = document.getElementById('chartArea').getContext('2d');
    chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: monthnames,
            datasets: [] // Initially blank - series added dynamically with chart.update()
        },
        options: {
            legend: {
                display: false
            },
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            },
            plugins: {  // ChartsJS DataLabels initialized here
                datalabels: {
                    anchor: 'end',
                    align: 'bottom',
                    formatter: Math.round,
                    font: {
                      weight: 'bold',
                      size: 16
                    },
                    color: colorpalette[currseriesnum] // Pick color dynamically
                }
            }
        }
    });

}

Doesn't work. Also tried a function, color: function(context), but unsure how to retrieve the current index of the dataset I'm getting here.

I'm adding series to the chart dynamically (initially empty) as below, and incrementing the global var currseriesnum.

chart.data.datasets.push({
    label: keyValueSelection.label,
    fill: false,
    data: keyValueSelection.value,
    borderColor: colorpalette[currseriesnum],
    borderWidth: 2
});
chart.update();
currseriesnum++;

Body:
They gave me the answer on the ChartJS DataLabels forum:

plugins: {
    datalabels: {
        color: function(ctx) {
            // use the same color as the border
            return ctx.dataset.borderColor
        }
    }
}


问:
Handle transition on absolutely position element pushing other elements
I have a responsive nav that expands down into the content below. Even with position: absolute, while the transition occurs it still pushes down the lower content. The problem is with the transition.

My idea to solve it was to add a class to the lower content whenever the navbar gets clicked. This would momentarily add absolute positioning to all the lower content so it does not get in the way of the dropdown.

Beside all the complexity this would take, I am using react and react-bootstrap and this dropdown, last one in the list. This does not have a onTransitionEnd event, so I don't know how to remove this added class once I've added it. I thought after the dropdown ends but without this event not sure how to do.

This is a simple problem but I am not sure how to fix it without rewriting the code. I've tried repositioning the lower content but no matter what I do the dropdown hits it, or its margin.  Some solutions say z-index should solve but that did not work.

If there is no solution I'm happy to hear ways to redesign.

I've made a demo with the issue.

答:
Here's a bit to get you along the right path:

```<code>.top-navbar {
  align-self: flex-end;
  height: 4em;
  max-width: 100px;
  width: 100px;
}
.navbar-nav {
  /*position: absolute;*/
  background-color: red;
}
</code>```

The only thing that's left is making it so the button doesn't bump up/down which shouldn't be too hard to figure out

Body:
Here's a bit to get you along the right path:

.top-navbar {
  align-self: flex-end;
  height: 4em;
  max-width: 100px;
  width: 100px;
}
.navbar-nav {
  /*position: absolute;*/
  background-color: red;
}

The only thing that's left is making it so the button doesn't bump up/down which shouldn't be too hard to figure out


问:
NSClassFromString returns nil
Why does NSClassFromString return nil ? As per the definition it has to return class name.
How should I take care to rectify this problem? I need to instantiate a class from string and call the method, which is in the class, using the instance created.

This is how my code looks like:

```<code>id myclass = [[NSClassFromString(@"Class_from_String") alloc] init];
[myclass method_from_class];
</code>```

But the method_from_class function is not being called, control is not going into it. And my code is error free. Any idea how to solve this in Objective-C?

答: I also saw an oddity where adding the standard singleton code espoused by apple prevented the class from being loaded.  The code was working as expected, then I added the singleton, and suddenly the NSClassFromString started returning nil. Commenting out the singleton code resulted in the NSClassFromString resolving the class correctly.  I don't understand the interaction, but I think the singleton static var was somehow getting mangled to hide the class name...?</p>

Title: NSClassFromString returns nil

Body:
Why does NSClassFromString return nil ? As per the definition it has to return class name.
How should I take care to rectify this problem? I need to instantiate a class from string and call the method, which is in the class, using the instance created.

This is how my code looks like:

id myclass = [[NSClassFromString(@"Class_from_String") alloc] init];
[myclass method_from_class];

But the method_from_class function is not being called, control is not going into it. And my code is error free. Any idea how to solve this in Objective-C?


问:
ERROR: could not load library ~/orafce.so: ~/orafce.so: undefined symbol: pq_sendbyte SQL state: XX000
Im trying to enable Orafce(3.7.1-1) extension on my postgress11 (11.2-2)

My OS is Ubuntu 18.04

The extension is already available in the database , and is listed if I run the following command :

```<code>select *  from pg_catalog.pg_available_extensions
</code>```

However when I try running the following command, I see error below.

```<code>create extension orafce with schema vias;

> Error>

    ERROR: could not load library "/home/vias/path/pg11/lib/postgresql/orafce.so": /home/vias/path/pg11/lib/postgresql/orafce.so: undefined symbol: pq_sendbyte SQL state: XX000
</code>```

Im really stuck... please advice

答: Recompile the extension for Postgres 11, it's likely compiled for Postgres 10</p>

Body:
Im trying to enable Orafce(3.7.1-1) extension on my postgress11 (11.2-2)

My OS is Ubuntu 18.04

The extension is already available in the database , and is listed if I run the following command :

select *  from pg_catalog.pg_available_extensions

However when I try running the following command, I see error below.

create extension orafce with schema vias;

> Error>

    ERROR: could not load library "/home/vias/path/pg11/lib/postgresql/orafce.so": /home/vias/path/pg11/lib/postgresql/orafce.so: undefined symbol: pq_sendbyte SQL state: XX000

Im really stuck... please advice


问:
Accessing Object Property Values Within an Array - JavaScript
Learning how to access property values.

If I have

```<code>let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];
</code>```

How would I console.log just the value of the second object? I.e. "website developer".

I know how to console.log the entire key-value pair (or object) by using .find():

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1.find(function(element) {
    return element.hasOwnProperty("job");
}
));```

But what about just the value of this pair?

答:
You can acces items in arrays at given position by their index. In javascript indexes of arrays are starting with 0: myArray[0]. To access the property of the returned object just use dot-notation: myArray[0].myProperty.

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1[1].job);```
</div>
</div>
</p>

<p>For your given example this can also achieved by appending the property-name (with dot-notation):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1.find(function(element) {
    return element.hasOwnProperty("job");
}).job);</code>```

Body:
Learning how to access property values.

If I have

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

How would I console.log just the value of the second object? I.e. "website developer".

I know how to console.log the entire key-value pair (or object) by using .find():

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1.find(function(element) {
    return element.hasOwnProperty("job");
}
));

But what about just the value of this pair?

Body:
You can acces items in arrays at given position by their index. In javascript indexes of arrays are starting with 0: myArray[0]. To access the property of the returned object just use dot-notation: myArray[0].myProperty.

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1[1].job);

For your given example this can also achieved by appending the property-name (with dot-notation):

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1.find(function(element) {
    return element.hasOwnProperty("job");
}).job);


问:
Overlapping density plots of multiple pandas data frame columns
```<code>import numpy as np
import pandas as pd

col1 = np.random.normal(0, 1, (1000, ))
col2 = np.random.normal(0, 1, (1000, ))
col3 = np.random.normal(0, 1, (1000, ))
df = pd.DataFrame({'col1':col1, 'col2':col2, 'col3':col3})
</code>```

Plot each column as a continuous line

Plot all 3 columns on same axis

Use different colored lines (no fill)

Thanks in advance!

答:
I understood your question! Here's how I would do it in matplotlib.

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

col1 = np.random.normal(0, 1, (1000, ))
col2 = np.random.normal(1, 1, (1000, ))
col3 = np.random.normal(-1, 1, (1000, ))
df = pd.DataFrame({'col1':col1, 'col2':col2, 'col3':col3})

df['col1_bins'] = pd.cut(df['col1'], bins=np.arange(-10, 11, 0.5))
df['col2_bins'] = pd.cut(df['col2'], bins=np.arange(-10, 11, 0.5))
df['col3_bins'] = pd.cut(df['col3'], bins=np.arange(-10, 11, 0.5))

col1_counts = df[['col1_bins', 'col1']].groupby(['col1_bins']).count().reset_index()
col2_counts = df[['col2_bins', 'col1']].groupby(['col2_bins']).count().reset_index()
col3_counts = df[['col3_bins', 'col1']].groupby(['col3_bins']).count().reset_index()

plt.plot(col1_counts['col1_bins'].astype(str), col1_counts['col1'], 'r')
plt.plot(col2_counts['col2_bins'].astype(str), col2_counts['col1'], 'b')
plt.plot(col3_counts['col3_bins'].astype(str), col3_counts['col1'], 'g')
</code>```

Basically you have to bin your data points before you can plot them.

Body:
import numpy as np
import pandas as pd

col1 = np.random.normal(0, 1, (1000, ))
col2 = np.random.normal(0, 1, (1000, ))
col3 = np.random.normal(0, 1, (1000, ))
df = pd.DataFrame({'col1':col1, 'col2':col2, 'col3':col3})

Plot each column as a continuous line

Plot all 3 columns on same axis

Use different colored lines (no fill)

Thanks in advance!

Body:
I understood your question! Here's how I would do it in matplotlib.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

col1 = np.random.normal(0, 1, (1000, ))
col2 = np.random.normal(1, 1, (1000, ))
col3 = np.random.normal(-1, 1, (1000, ))
df = pd.DataFrame({'col1':col1, 'col2':col2, 'col3':col3})

df['col1_bins'] = pd.cut(df['col1'], bins=np.arange(-10, 11, 0.5))
df['col2_bins'] = pd.cut(df['col2'], bins=np.arange(-10, 11, 0.5))
df['col3_bins'] = pd.cut(df['col3'], bins=np.arange(-10, 11, 0.5))

col1_counts = df[['col1_bins', 'col1']].groupby(['col1_bins']).count().reset_index()
col2_counts = df[['col2_bins', 'col1']].groupby(['col2_bins']).count().reset_index()
col3_counts = df[['col3_bins', 'col1']].groupby(['col3_bins']).count().reset_index()

plt.plot(col1_counts['col1_bins'].astype(str), col1_counts['col1'], 'r')
plt.plot(col2_counts['col2_bins'].astype(str), col2_counts['col1'], 'b')
plt.plot(col3_counts['col3_bins'].astype(str), col3_counts['col1'], 'g')

Basically you have to bin your data points before you can plot them.