问:
Finding the true anomaly from state vectors
I'm attempting to convert from state vectors (position and speed) into Kepler elements, however I'm running into problems where a negative velocity or position will give me wrong results when trying to calculate true anomaly.

Here are the different ways I'm trying to calculate the True Anomaly:

```<code>/// <summary>
/// https://en.wikipedia.org/wiki/True_anomaly#From_state_vectors
/// </summary>
public static double TrueAnomaly(Vector4 eccentVector, Vector4 position, Vector4 velocity)
{
    var dotEccPos = Vector4.Dot(eccentVector, position);
    var talen = eccentVector.Length() * position.Length();
    talen = dotEccPos / talen;
    talen = GMath.Clamp(talen, -1, 1);
    var trueAnomoly = Math.Acos(talen);

    if (Vector4.Dot(position, velocity) < 0)
        trueAnomoly = Math.PI * 2 - trueAnomoly;

    return trueAnomoly;
}
</code>```

```<code>//sgp = standard gravitational parameter
public static double TrueAnomaly(double sgp, Vector4 position, Vector4 velocity)
{
    var H = Vector4.Cross(position, velocity).Length();
    var R = position.Length();
    var q = Vector4.Dot(position, velocity);  // dot product of r*v
    var TAx = H * H / (R * sgp) - 1;
    var TAy = H * q / (R * sgp);
    var TA = Math.Atan2(TAy, TAx);
    return TA;
}
</code>```

```<code>public static double TrueAnomalyFromEccentricAnomaly(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Sqrt(1 - Math.Pow(eccentricity, 2)) * Math.Sin(eccentricAnomaly);
    var y = Math.Cos(eccentricAnomaly) - eccentricity;
    return Math.Atan2(x, y);
}
</code>```

```<code>public static double TrueAnomalyFromEccentricAnomaly2(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Cos(eccentricAnomaly) - eccentricity;
    var y = 1 - eccentricity * Math.Cos(eccentricAnomaly);
    return Math.Acos(x / y);
}
</code>```

Edit: another way of doing it which Spectre pointed out:

```<code>public static double TrueAnomaly(Vector4 position, double loP)
{
    return Math.Atan2(position.Y, position.X) - loP;
}
</code>```

Positions are all relative to the parent body.

These functions all agree if position.x, position.y and velocity.y are all positive.
How do I fix these so that I get a consistent results when position and velocity are negitive?

Just to clarify: My angles appear to be sort of correct, just pointing in the wrong quadrant depending on the position and or velocity vectors.

Yeah so I was wrong, the above all do return the correct values after all.

So I found an edge case where most of the above calculations fail.
Given position and velocity:

```<code>pos = new Vector4() { X = -0.208994076275941, Y = 0.955838328099748 };
vel = new Vector4() { X = -2.1678187689294E-07, Y = -7.93096769486992E-08 };
</code>```

I get some odd results, ie ~ -31.1 degrees, when I think it should return ` 31.1 (non negative). one of them returns ~ 328.8.

However testing with this position and velocity the results apear to be ok:

```<code>pos = new Vector4() { X = -0.25, Y = 0.25 };
vel = new Vector4() { X = Distance.KmToAU(-25), Y = Distance.KmToAU(-25) };
</code>```

See my answer for extra code on how I'm testing and the math I'm using for some of the other variables.

I'm going around in circles on this one. this is a result of a bug in my existing code that shows up under some conditions but not others.
I guess the real question now is WHY am I getting different results with position/velocity above that don't match to my expectations or each other?

答:
I am assuming you are working in two dimensions?

Two dimensional vectors of position p and velocity v. The constant K is the the product of the gravitational constant and the mass of the gravity generating body. Calculate the eccentricity vector

```<code>eccVector = (dot(v, v)*p - dot(v, p)*v) / K - p / sqrt(dot(p, p));

eccentricity = sqrt(dot(eccVector, eccVector));

eccVector = eccVector / eccentricity;

b = { - eccVector.y, eccVector.x};  //unit vector perpendicular to eccVector

r = sqrt(dot(p, p));

cos_TA = dot(p, eccVector) / r;   \\ cosine of true anomaly
sin_TA = dot(p, b) / r;           \\ sine of true anomaly

if (sin_TA >= 0) {
   trueAnomaly = arccos(cos_TA);
}
else if (sin_TA < 0){
   trueAnomaly = 2*pi - arccos(cos_TA);
}
</code>```

Body:
I'm attempting to convert from state vectors (position and speed) into Kepler elements, however I'm running into problems where a negative velocity or position will give me wrong results when trying to calculate true anomaly.

Here are the different ways I'm trying to calculate the True Anomaly:

///
/// https://en.wikipedia.org/wiki/True_anomaly#From_state_vectors
///
public static double TrueAnomaly(Vector4 eccentVector, Vector4 position, Vector4 velocity)
{
    var dotEccPos = Vector4.Dot(eccentVector, position);
    var talen = eccentVector.Length() * position.Length();
    talen = dotEccPos / talen;
    talen = GMath.Clamp(talen, -1, 1);
    var trueAnomoly = Math.Acos(talen);

    if (Vector4.Dot(position, velocity) < 0)
        trueAnomoly = Math.PI * 2 - trueAnomoly;

    return trueAnomoly;
}

//sgp = standard gravitational parameter
public static double TrueAnomaly(double sgp, Vector4 position, Vector4 velocity)
{
    var H = Vector4.Cross(position, velocity).Length();
    var R = position.Length();
    var q = Vector4.Dot(position, velocity);  // dot product of r*v
    var TAx = H * H / (R * sgp) - 1;
    var TAy = H * q / (R * sgp);
    var TA = Math.Atan2(TAy, TAx);
    return TA;
}

public static double TrueAnomalyFromEccentricAnomaly(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Sqrt(1 - Math.Pow(eccentricity, 2)) * Math.Sin(eccentricAnomaly);
    var y = Math.Cos(eccentricAnomaly) - eccentricity;
    return Math.Atan2(x, y);
}

public static double TrueAnomalyFromEccentricAnomaly2(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Cos(eccentricAnomaly) - eccentricity;
    var y = 1 - eccentricity * Math.Cos(eccentricAnomaly);
    return Math.Acos(x / y);
}

Edit: another way of doing it which Spectre pointed out:

public static double TrueAnomaly(Vector4 position, double loP)
{
    return Math.Atan2(position.Y, position.X) - loP;
}

Positions are all relative to the parent body.

These functions all agree if position.x, position.y and velocity.y are all positive.
How do I fix these so that I get a consistent results when position and velocity are negitive?

Just to clarify: My angles appear to be sort of correct, just pointing in the wrong quadrant depending on the position and or velocity vectors.

Yeah so I was wrong, the above all do return the correct values after all.

So I found an edge case where most of the above calculations fail.
Given position and velocity:

pos = new Vector4() { X = -0.208994076275941, Y = 0.955838328099748 };
vel = new Vector4() { X = -2.1678187689294E-07, Y = -7.93096769486992E-08 };

I get some odd results, ie ~ -31.1 degrees, when I think it should return ` 31.1 (non negative). one of them returns ~ 328.8.

However testing with this position and velocity the results apear to be ok:

pos = new Vector4() { X = -0.25, Y = 0.25 };
vel = new Vector4() { X = Distance.KmToAU(-25), Y = Distance.KmToAU(-25) };

See my answer for extra code on how I'm testing and the math I'm using for some of the other variables.

I'm going around in circles on this one. this is a result of a bug in my existing code that shows up under some conditions but not others.
I guess the real question now is WHY am I getting different results with position/velocity above that don't match to my expectations or each other?

Body:
I am assuming you are working in two dimensions?

Two dimensional vectors of position p and velocity v. The constant K is the the product of the gravitational constant and the mass of the gravity generating body. Calculate the eccentricity vector

eccVector = (dot(v, v)*p - dot(v, p)*v) / K - p / sqrt(dot(p, p));

eccentricity = sqrt(dot(eccVector, eccVector));

eccVector = eccVector / eccentricity;

b = { - eccVector.y, eccVector.x};  //unit vector perpendicular to eccVector

r = sqrt(dot(p, p));

cos_TA = dot(p, eccVector) / r;   \\ cosine of true anomaly
sin_TA = dot(p, b) / r;           \\ sine of true anomaly

if (sin_TA >= 0) {
   trueAnomaly = arccos(cos_TA);
}
else if (sin_TA < 0){
   trueAnomaly = 2*pi - arccos(cos_TA);
}


来源: stackexchange

问:
How can i delete directories including their contents using perl?
It is possible to delete few directories including their contents at once using perl ?
Eg:- I have below folders

test1

test2

test3

test4

Can i delete them like rm -rf test* ?
i tried with below

```<code>system(@rm, '-fr', "$path/test*");
</code>```

but its not taking *

答:
I must first say that this is inherently dangerous, recursively removing directories out of a program.

Having said that, one module that provides the capability is the core File::Path

```<code>use File::Path qw(remove_tree);

...

remove_tree( @dirs_to_delete, safe => 1 );
</code>```

This will croak on errors, which is a pretty good idea in my opinion if recursive removal had trouble.  But if that won't work with your designs you can use the error option and then it's up to you to check for errors. See Error Handling, and see a few other useful options.

This removes files as well. So be careful in composing the list of things to blow away, for example

```<code>use File::Glob ':bsd_glob';

my @dirs_to_delete = glob "$path/test*/";   # note the trailing /
</code>```

where the trailing / makes it so that only directories are returned.  With File::Glob use statement we get the glob from :bsd_glob which works with filenames that have spaces.†

It may also be safer to first get "closer" to what you want to remove

```<code>my $orig_cwd = Cwd::cwd;

chdir $path  or die "Can't \"chdir $path\": $!";

my @dirs_to_delete = glob "test*/";

# chdir $orig_cwd;
</code>```

(there are options other than Cwd for chdir-ing and getting back to the original cwd)

This of course does not (at all) make it error-proof.

Please excuse repeated warnings but posting on recursive removal makes me a little nervous.

† Or double those (double) quotes, glob qq{"$path/test*/"}, or use the \Q form of quotemeta, glob "\Q$path/test/*/", but which also escapes all non-word characters.

ContentLicense: CC BY-SA 4.0

Body:
It is possible to delete few directories including their contents at once using perl ?
Eg:- I have below folders

test1

test2

test3

test4

Can i delete them like rm -rf test* ?
i tried with below

system(@rm, '-fr', "$path/test*");

but its not taking *

Body:
I must first say that this is inherently dangerous, recursively removing directories out of a program.

Having said that, one module that provides the capability is the core File::Path

use File::Path qw(remove_tree);

...

remove_tree( @dirs_to_delete, safe => 1 );

This will croak on errors, which is a pretty good idea in my opinion if recursive removal had trouble.  But if that won't work with your designs you can use the error option and then it's up to you to check for errors. See Error Handling, and see a few other useful options.

This removes files as well. So be careful in composing the list of things to blow away, for example

use File::Glob ':bsd_glob';

my @dirs_to_delete = glob "$path/test*/";   # note the trailing /

where the trailing / makes it so that only directories are returned.  With File::Glob use statement we get the glob from :bsd_glob which works with filenames that have spaces.†

It may also be safer to first get "closer" to what you want to remove

my $orig_cwd = Cwd::cwd;

chdir $path  or die "Can't \"chdir $path\": $!";

my @dirs_to_delete = glob "test*/";

# chdir $orig_cwd;

(there are options other than Cwd for chdir-ing and getting back to the original cwd)

This of course does not (at all) make it error-proof.

Please excuse repeated warnings but posting on recursive removal makes me a little nervous.

† Or double those (double) quotes, glob qq{"$path/test*/"}, or use the \Q form of quotemeta, glob "\Q$path/test/*/", but which also escapes all non-word characters.


问:
Decoding JSON when feed is inconsistent - Swift
I don’t know how to handle a JSON feed in swift with the decodable protocol when the feed gives me two different results.  If there is more than one ‘entry’,  the json looks like this and the entry value is an array of objects

```<code>{
  "feed": {
    "publisher": "Penguin",
    "country": "ca"
  },
  "entry": [
    {
      "author": "Margaret Atwood",
      "nationality": "Canadian"
    },
    {
      "author": "Dan Brown",
      "nationality": "American"
    }
  ]
}
</code>```

However, if there is only a single entry, the json looks like this where entry is just a dictionary

```<code>{
  "feed": {
    "publisher": "Penguin",
    "country": "ca"
  },
  "entry": {
    "author": "Margaret Atwood",
    "nationality": "Canadian"
  }
}
</code>```

to decode the first case, I would use the following structs

```<code>struct Book: Decodable {
    let feed: Feed
    let entry: [Entry]
}

// MARK: - Entry
struct Entry: Decodable {
    let author, nationality: String
}

// MARK: - Feed
struct Feed: Decodable {
    let publisher, country: String
}
</code>```

And then use something like this to decode the data retrieved

```<code> let  object = try JSONDecoder().decode(Book.self, from: data)
</code>```

How do I handle the case when the entry is not an array of objects?

答:
You could possibly override the decoder for Book. What you can do is to try to unwrap an [Entry]s and upon failing that, just try to unwrap a single Entry.

For example:

```<code>struct Book: Decodable {
   let feed: Feed
   let entry: [Entry]
   init (from decoder :Decoder) throws {
     let container = try decoder.container(keyedBy: CodingKeys.self)
      do {
        value = try container.decode([Entry].self, forKey: .value)
      } catch {
        let newValue = try container.decode(Entry.self, forKey: .value)
        value = [newValue]
      }
   }
}
</code>```

Note: that's not a comprehensive sample on what you want to do but just a way you can accomplish what you want to do

Body:
I don’t know how to handle a JSON feed in swift with the decodable protocol when the feed gives me two different results.  If there is more than one ‘entry’,  the json looks like this and the entry value is an array of objects

{
  "feed": {
    "publisher": "Penguin",
    "country": "ca"
  },
  "entry": [
    {
      "author": "Margaret Atwood",
      "nationality": "Canadian"
    },
    {
      "author": "Dan Brown",
      "nationality": "American"
    }
  ]
}

However, if there is only a single entry, the json looks like this where entry is just a dictionary

{
  "feed": {
    "publisher": "Penguin",
    "country": "ca"
  },
  "entry": {
    "author": "Margaret Atwood",
    "nationality": "Canadian"
  }
}

to decode the first case, I would use the following structs

struct Book: Decodable {
    let feed: Feed
    let entry: [Entry]
}

// MARK: - Entry
struct Entry: Decodable {
    let author, nationality: String
}

// MARK: - Feed
struct Feed: Decodable {
    let publisher, country: String
}

And then use something like this to decode the data retrieved

 let  object = try JSONDecoder().decode(Book.self, from: data)

How do I handle the case when the entry is not an array of objects?

Body:
You could possibly override the decoder for Book. What you can do is to try to unwrap an [Entry]s and upon failing that, just try to unwrap a single Entry.

For example:

struct Book: Decodable {
   let feed: Feed
   let entry: [Entry]
   init (from decoder :Decoder) throws {
     let container = try decoder.container(keyedBy: CodingKeys.self)
      do {
        value = try container.decode([Entry].self, forKey: .value)
      } catch {
        let newValue = try container.decode(Entry.self, forKey: .value)
        value = [newValue]
      }
   }
}

Note: that's not a comprehensive sample on what you want to do but just a way you can accomplish what you want to do


问:
How to define IF clause within WHERE condition in SQL?
I'm trying a simple if statement within where condition in SQL. I don't want CASE statement since it is very simple.

Example:

```<code>CREATE PROCEDURE [dbo].[usp_GetStatus]
    @siteId INT,

    ........
    FROM sites
    WHERE StartDate = @reportMonth
      AND..
      AND ...
      AND IF(@siteId > 0) sites.SiteId = @siteId
    ........
</code>```

I would like to define simple as above.

My siteId parameter can be 0 or greater than that, if user passes a integer value. I want to omit my AND condition if siteId parameter is 0.

答:
You normally handle this with boolean logic within your SQL. So you can just write:

```<code>WHERE  StartDate = @reportMonth
AND..
AND ...
AND (@siteId <=0 OR  sites.SiteId = @siteId)
</code>```

So if @siteId is not greater than 0 it ignores the rest of the OR clause, but if it is, then it evaluates your sites.SiteId clause. Normally for a stored proc I'd set default value to null and check for nullness:

```<code>CREATE PROCEDURE [dbo].[usp_GetStatus]

@siteId INT = NULL,
........
from sites;
 WHERE  StartDate = @reportMonth
AND..
AND ...
AND (@siteId IS NULL OR  sites.SiteId = @siteId)
</code>```

Body:
I'm trying a simple if statement within where condition in SQL. I don't want CASE statement since it is very simple.

Example:

CREATE PROCEDURE [dbo].[usp_GetStatus]
    @siteId INT,

    ........
    FROM sites
    WHERE StartDate = @reportMonth
      AND..
      AND ...
      AND IF(@siteId > 0) sites.SiteId = @siteId
    ........

I would like to define simple as above.

My siteId parameter can be 0 or greater than that, if user passes a integer value. I want to omit my AND condition if siteId parameter is 0.

Body:
You normally handle this with boolean logic within your SQL. So you can just write:

WHERE  StartDate = @reportMonth
AND..
AND ...
AND (@siteId <=0 OR  sites.SiteId = @siteId)

So if @siteId is not greater than 0 it ignores the rest of the OR clause, but if it is, then it evaluates your sites.SiteId clause. Normally for a stored proc I'd set default value to null and check for nullness:

CREATE PROCEDURE [dbo].[usp_GetStatus]

@siteId INT = NULL,
........
from sites;
 WHERE  StartDate = @reportMonth
AND..
AND ...
AND (@siteId IS NULL OR  sites.SiteId = @siteId)


问:
global name is not defined error for static method
For the code below I wrote for Binary Search Tree, I get the error delete_node(curr,value)
NameError: global name 'delete_node' is not defined. I am wondering why this will be the case for static method which is called from the instance method delete(self,value) . Why does it not work as a static method? I am calling it from a instance method 'delete' so does it does not require access to instance members explicitly.</p>

```<code>class Node:
    def __init__(self,value=None):
        self.value = value
        self.left = None
        self.right = None

class BST:
    def __init__(self,value=None):
        self.root = Node(value)
    @staticmethod
    def delete_node(node,value):
       if node is None:
           return node
       if value > node.value:
           node.right = delete_node(node.right,value)
       elif value < node.value:
           node.left = delete_node(node.left,value)
       else:
           if node.left is None and node.right is None:
               node = None
               return None
           elif node.left is None:
               temp = node.right
               node = None
               return temp
           elif node.right is None:
               temp = node.left
               node = None
               return temp
           else:
            #min_value = get_min(node.right)
               node.value = get_min(node.right)
               node.right = delete_node(node.right,node.value)

       def delete(self,value):
           if self.root == None:
           return
           curr = self.root
           delete_node(curr,value)
def get_min(node):
    curr = node
    while curr.left:
        curr = curr.left
    return curr.value

if __name__ == '__main__':
    tree = BST(5)
    tree.delete(5)
</code>```

答:
As others have eluded to, in order to call methods on a class object you have to specify the thing you're calling it on.

So where you use delete_node, you can use BST.delete_node since it's static. The design is a bit odd given a BST would normally be done as an object encapsulated completely, but this is your immediate problem.

If it's an instance method, then you would call  self.delete_node

Body:
For the code below I wrote for Binary Search Tree, I get the error delete_node(curr,value)
NameError: global name 'delete_node' is not defined. I am wondering why this will be the case for static method which is called from the instance method delete(self,value) . Why does it not work as a static method? I am calling it from a instance method 'delete' so does it does not require access to instance members explicitly.

class Node:
    def __init__(self,value=None):
        self.value = value
        self.left = None
        self.right = None

class BST:
    def __init__(self,value=None):
        self.root = Node(value)
    @staticmethod
    def delete_node(node,value):
       if node is None:
           return node
       if value > node.value:
           node.right = delete_node(node.right,value)
       elif value < node.value:
           node.left = delete_node(node.left,value)
       else:
           if node.left is None and node.right is None:
               node = None
               return None
           elif node.left is None:
               temp = node.right
               node = None
               return temp
           elif node.right is None:
               temp = node.left
               node = None
               return temp
           else:
            #min_value = get_min(node.right)
               node.value = get_min(node.right)
               node.right = delete_node(node.right,node.value)

       def delete(self,value):
           if self.root == None:
           return
           curr = self.root
           delete_node(curr,value)
def get_min(node):
    curr = node
    while curr.left:
        curr = curr.left
    return curr.value

if __name__ == '__main__':
    tree = BST(5)
    tree.delete(5)


问:
navigation hide menu with jQuery
I build a nav menu with jquery, when I clicked on menu icon it will open but when I clicked again on menu icon it will not close

this is html code:

```<code><aside class="aside_menu">
        <span class="arrow"></span>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
</aside>
</code>```

this is jquery code:

```<code>$(document).ready(function () {
$(".aside_menu .arrow").click(function () {
    var aside_menu = $(this).parent();
    if (aside_menu.offset().right === 0)
        aside_menu.animate({right: "-200px"})
    else
        aside_menu.animate({right: "0px"})
})
</code>```

})

the menu hide in the right side of page and only menu icon show up

sorry for bad language

答:
Simple things after the biggest resistance line, instead of jQuery, it's better to use JS for such simple things. In addition, animations in JS are clumsy, especially on weaker com-puter and smartphones, which destroys user experience. It's much easier to do it with simple JS and CSS. Probably my code will not help you, but I hope to guide you on the right path.
Ps. Try not to use: "_" (underline) in classes and attributes and id's, because it is in terms of SEO, it is a shot in the knee, a better alternative is: "-" (dash).

var menu = document.querySelector("#menu");
var button = document.querySelector("#button");

function toggleMenu(){
 if(!menu.classList.contains("fade")){
   menu.classList.add("fade");
  }else{
   menu.classList.remove("fade");
  }
}

button.addEventListener("click", toggleMenu);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  margin: 0;
  display: flex;
  }
#menu{
  background: pink;
  width: 70px;
  height: 100%;
  text-align: center;
  transition: 0.34s;
  }
#button{
  height: 30px;
  transition: 0.34s;
  }
.fade{
  width: 0 !important;
  }
.fade *{
  display: none;
}</code>```

test

test

test

test

test

test

test

test

test

test

<button id="button">
Button
</button>```

Title: navigation hide menu with jQuery

Body:
I build a nav menu with jquery, when I clicked on menu icon it will open but when I clicked again on menu icon it will not close

this is html code:

test

test

test

test

test

test

test

test

test

test

this is jquery code:

$(document).ready(function () {
$(".aside_menu .arrow").click(function () {
    var aside_menu = $(this).parent();
    if (aside_menu.offset().right === 0)
        aside_menu.animate({right: "-200px"})
    else
        aside_menu.animate({right: "0px"})
})

})

the menu hide in the right side of page and only menu icon show up

sorry for bad language

Body:
Simple things after the biggest resistance line, instead of jQuery, it's better to use JS for such simple things. In addition, animations in JS are clumsy, especially on weaker com-puter and smartphones, which destroys user experience. It's much easier to do it with simple JS and CSS. Probably my code will not help you, but I hope to guide you on the right path.
Ps. Try not to use: "_" (underline) in classes and attributes and id's, because it is in terms of SEO, it is a shot in the knee, a better alternative is: "-" (dash).

var menu = document.querySelector("#menu");
var button = document.querySelector("#button");

function toggleMenu(){
 if(!menu.classList.contains("fade")){
   menu.classList.add("fade");
  }else{
   menu.classList.remove("fade");
  }
}

button.addEventListener("click", toggleMenu);

body{
  margin: 0;
  display: flex;
  }
#menu{
  background: pink;
  width: 70px;
  height: 100%;
  text-align: center;
  transition: 0.34s;
  }
#button{
  height: 30px;
  transition: 0.34s;
  }
.fade{
  width: 0 !important;
  }
.fade *{
  display: none;
}

<aside id="menu" class="fade">
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
        <div><a href="#">test</a></div>
</aside>
<button id="button">
Button
</button>


问:
/bin/bash^M: bad interpreter: No such file or directory
I am facing
 /bin/bash^M: bad interpreter: No such file or directory
issue and I have already got the solution for it from this stack flow answer

-bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory

which works fine.

My question is every time when I restart my ubuntu machine I have to redo everything
That is I execute
dos2unix -k -o filename
every time I start my system.

Is there any way this can be just once?

Please note: I had to create a new question because I was not able to ask the question or comment in the existing question due to less reputation

答:
The first line of your bash script should be the Shebang (#!/bin/bash).

I see the error says: /bin/bash
But is should be changed to: #!/bin/bash

Then run:

```<code>$ dos2unix my_script
</code>```

This will change all the line terminators from \r\n (Windows) to \n (Linux), this will modify the original my_script file so it will persist even after a reboot.

Body:
The first line of your bash script should be the Shebang (#!/bin/bash).

I see the error says: /bin/bash
But is should be changed to: #!/bin/bash

Then run:

$ dos2unix my_script

This will change all the line terminators from \r\n (Windows) to \n (Linux), this will modify the original my_script file so it will persist even after a reboot.


问:
Silverstripe create a simple static HTML page
How do I with Silverstrip just create a plain HTML page ?

I am trying to add a page, then edit HTML to put in my own script tags etc, and won't let me.

答:
i think you're talking about editing the page templates (mysite/templates/Page.ss), right? a common mistake is not flushing the template cache whenever you change a template. just add ?flush=1 to your page url to do so.

also see the docs on URL Variable Tools for further information on this.

additionally, in case you don't want to have pages in the cms, you might be interested in this tutorial on ssbits to bypass the cms and render arbitrary html code.

ContentLicense: CC BY-SA 3.0


问:
How to change content mode on AVPlayer video?
My problem is that when I'm displaying video it's bigger than my screen size. Maybe the problem is not content mode but wrong frame bounds or something.

```<code>let theURL = Bundle.main.url(forResource:"videkas", withExtension: "mp4")

    avPlayer = AVPlayer(url: theURL!)
    avPlayerLayer = AVPlayerLayer(player: avPlayer)
    avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    avPlayer.volume = 0
    avPlayer.actionAtItemEnd = .none

    avPlayerLayer.frame = (featureView13?.bounds)!
    featureView13?.backgroundColor = .clear
    featureView13?.layer.insertSublayer(avPlayerLayer, at: 0)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(playerItemDidReachEnd(notification:)),
                                           name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                           object: avPlayer.currentItem)
</code>```

I also tried avPlayerLayer.frame = (featureView13?.layer.bounds)! but no luck.

答: Change resizeAspectFill to resizeAspect. There is a big difference!

Body:
My problem is that when I'm displaying video it's bigger than my screen size. Maybe the problem is not content mode but wrong frame bounds or something.

let theURL = Bundle.main.url(forResource:"videkas", withExtension: "mp4")

    avPlayer = AVPlayer(url: theURL!)
    avPlayerLayer = AVPlayerLayer(player: avPlayer)
    avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    avPlayer.volume = 0
    avPlayer.actionAtItemEnd = .none

    avPlayerLayer.frame = (featureView13?.bounds)!
    featureView13?.backgroundColor = .clear
    featureView13?.layer.insertSublayer(avPlayerLayer, at: 0)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(playerItemDidReachEnd(notification:)),
                                           name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                           object: avPlayer.currentItem)

I also tried avPlayerLayer.frame = (featureView13?.layer.bounds)! but no luck.


问:
How to trigger full-screen mode on play for embedded YouTube video in React Native WebView?
I have a YouTube video embedded in a React Native WebView. I'm using the react-native-android-fullscreen-webview-video library for Android which works well in both portrait and landscape mode, but I need the video to default to fullscreen when the user presses play.

I've tried other libraries for this, including react-native-youtube, but each resulted in buggy playback either in portrait or landscape.

This is my code. Everything works well, I just need fullscreen play by default.

```<code><WebView source={{ uri: videoUrl }} />
</code>```

答:
This library works

react-native-android-fullscreen-webview-video

```<code>import WebView from 'react-native-android-fullscreen-webview-video';
<WebView style={{flex:1, height: 300} source={{ uri: 'https://www.youtube.com/embed/GV0B6nGf9mcrel=0&autoplay=0&showinfo=0&controls=1&fullscreen=1' }}/>
</code>```

Body:
I have a YouTube video embedded in a React Native WebView. I'm using the react-native-android-fullscreen-webview-video library for Android which works well in both portrait and landscape mode, but I need the video to default to fullscreen when the user presses play.

I've tried other libraries for this, including react-native-youtube, but each resulted in buggy playback either in portrait or landscape.

This is my code. Everything works well, I just need fullscreen play by default.

<WebView source={{ uri: videoUrl }} />

Body:
This library works

react-native-android-fullscreen-webview-video

import WebView from 'react-native-android-fullscreen-webview-video';
<WebView style={{flex:1, height: 300} source={{ uri: 'https://www.youtube.com/embed/GV0B6nGf9mcrel=0&autoplay=0&showinfo=0&controls=1&fullscreen=1' }}/>


问:
how to set array elements equal to the number of chars in a word
Create and assign, to instance variable progress, a new array of char with a number of elements equal to the length of the String you just assigned to word. (I have a set of words that gets assigned to string "word")

I honestly dont know a simple way to do this. I can think of some long ways but it seems from context that there is a simple way.

答:
Try this code,

```<code>    Scanner sc = new Scanner(System.in);
    String testString = sc.nextLine();
    char[] stringToCharArray = testString.toCharArray();

    for (char output : stringToCharArray) {
        System.out.println(output);
    }
    sc.close();
</code>```

Output:

```<code>word
w
o
r
d
</code>```

Body:
Try this code,

    Scanner sc = new Scanner(System.in);
    String testString = sc.nextLine();
    char[] stringToCharArray = testString.toCharArray();

    for (char output : stringToCharArray) {
        System.out.println(output);
    }
    sc.close();

Output:

word
w
o
r
d


问:
How to FilterItems by Contains
I can collect items if I have the exact string of a text field but I need to collect items if I have a partial string in a text field.

Here is the code that I have for exact match...

```<code>public static async Task<int> Items_With_String(int appId, string textFieldId, string stringToSearch)
{

    var filter = new Dictionary<string, string>
    {
        {textFieldId, stringToSearch }
    };

    var filteredItems = await Program.podio.ItemService.FilterItems(appId: appId, filters: filter);

    foreach (var item in filteredItems.Items)
    {
        Console.WriteLine($"{stringToSearch} found in {item.Title}");
    }

    return filteredItems.Total;
}
</code>```

答:
You haven't actually provided the implementation of FilterItems method.

But generally for a partial match you may use linq query and add a where
clause with a predicate to do the partial match. Here i give you a sample of
how it looks like so you could use it for your list and filter properties.

```<code>string filter = "something";
List<MyClass> myList = new List<MyClass>();
// add items to the list
myList.Where(item => item.Contains(filter));
// or for the partial match with a shared beginning
myList.Where(item => item.StartsWith(filter));
</code>```

Hope this would be helpful to your case.

Title: How to FilterItems by Contains

Body:
I can collect items if I have the exact string of a text field but I need to collect items if I have a partial string in a text field.

Here is the code that I have for exact match...

public static async Task<int> Items_With_String(int appId, string textFieldId, string stringToSearch)
{

    var filter = new Dictionary<string, string>
    {
        {textFieldId, stringToSearch }
    };

    var filteredItems = await Program.podio.ItemService.FilterItems(appId: appId, filters: filter);

    foreach (var item in filteredItems.Items)
    {
        Console.WriteLine($"{stringToSearch} found in {item.Title}");
    }

    return filteredItems.Total;
}

Body:
You haven't actually provided the implementation of FilterItems method.

But generally for a partial match you may use linq query and add a where
clause with a predicate to do the partial match. Here i give you a sample of
how it looks like so you could use it for your list and filter properties.

string filter = "something";
List<MyClass> myList = new List<MyClass>();
// add items to the list
myList.Where(item => item.Contains(filter));
// or for the partial match with a shared beginning
myList.Where(item => item.StartsWith(filter));

Hope this would be helpful to your case.


问:
Can jqGrid summary footer be populated without userdata server request?
I have poured through every question asked on this website related to populating the jqGrid summary footer WITHOUT the userdata being a server request. And the jqGrid wiki resource and just cannot find an answer. Is this possible to do?

I use the jqGrid in many typical ways as part of my admin portal but have one particular use where I want the look & feel of the jqGrid to start out as an empty UI container of sorts for some user interaction adding rows through a form which doesn't post on Submit (thanks to Oleg's great script below) but simply adds the row and updates the summary footer with the values from the newly added row. I have 'summarytype:"sum"' in the colModel, "grouping:true", footerrow: true, userDataOnFooter: true, altRows: true, in the grid options but apart from the initial values supplied by the userdata in the local data string, the summary footer values never change. It seems like no one wants to touch this subject. Is it because the primary nature of the jqGrid is it's database driven functionality? I use about 15 instances of the jqGrid in it's database driven stance (many of which are in a production service now) but need to use it for consistency sake (all my UI's are inside jqTabs) initially as a client side UI with no server request (everything will be saved later to db) but I am pulling my hair out trying to manipulate the summary footer programmatically on and by the client only. Can anyone suggest how to cause values to the summary footer to update when a new row is added the values of which would be summed up with any existing rows and which does not involve any posting to server, just updates inside the grid?

The code supplied is kind of long and based primarily on user Oleg's solution for adding a row from a modal form without posting to the server. I've changed the local array data to JSON string simply to better understand the notation as I'm used to xml. The jsonstring initializes the grid with one default row for the user to edit. I've left out the jsonReader because the grid would not render with it.

In a nutshell then what I want to do is to have the summary footer update when a new row is added to the grid (no posting to server occurring at this point) or edited or deleted. When a certain set of values is achieved the user is prompted by a displayed button to save row data to db.

```<code>var lastSel, mydata = { "total": 1, "page": 1, "records": 1, "rows": [{ "id": acmid, "cell": ["0.00", "0.00", "0.00", "0.00"]}], "userdata":{ "mf": 0.00, "af":0.00,"pf":0.00,"cf":0.00 }}

grid = $("#ta_form_d"),
    onclickSubmitLocal = function (options, postdata) {

        var grid_p = grid[0].p,
            idname = grid_p.prmNames.id,
            grid_id = grid[0].id,
            id_in_postdata = grid_id + "_id",
            rowid = postdata[id_in_postdata],
            addMode = rowid === "_empty",
            oldValueOfSortColumn;

        // postdata has row id property with another name. we fix it:
        if (addMode) {
            // generate new id
            var new_id = grid_p.records + 1;
            while ($("#" + new_id).length !== 0) {
                new_id++;
            }
            postdata[idname] = String(new_id);
            //alert(postdata[idname]);
        } else if (typeof (postdata[idname]) === "undefined") {
            // set id property only if the property not exist
            postdata[idname] = rowid;
        }

        delete postdata[id_in_postdata];

        // prepare postdata for tree grid
        if (grid_p.treeGrid === true) {
            if (addMode) {
                var tr_par_id = grid_p.treeGridModel === 'adjacency' ? grid_p.treeReader.parent_id_field : 'parent_id';
                postdata[tr_par_id] = grid_p.selrow;
            }

            $.each(grid_p.treeReader, function (i) {
                if (postdata.hasOwnProperty(this)) {
                    delete postdata[this];
                }
            });
        }

        // decode data if there encoded with autoencode
        if (grid_p.autoencode) {
            $.each(postdata, function (n, v) {
                postdata[n] = $.jgrid.htmlDecode(v); // TODO: some columns could be skipped
            });
        }

        // save old value from the sorted column
        oldValueOfSortColumn = grid_p.sortname === "" ? undefined : grid.jqGrid('getCell', rowid, grid_p.sortname);
        //alert(oldValueOfSortColumn);
        // save the data in the grid
        if (grid_p.treeGrid === true) {
            if (addMode) {
                grid.jqGrid("addChildNode", rowid, grid_p.selrow, postdata);
            } else {
                grid.jqGrid("setTreeRow", rowid, postdata);
            }
        } else {

           if (addMode) {
                grid.jqGrid("addRowData", rowid, postdata, options.addedrow);

            } else {
                grid.jqGrid("setRowData", rowid, postdata);
            }
        }

        if ((addMode && options.closeAfterAdd) || (!addMode && options.closeAfterEdit)) {
            // close the edit/add dialog
            $.jgrid.hideModal("#editmod" + grid_id,
                              { gb: "#gbox_" + grid_id, jqm: options.jqModal, onClose: options.onClose });
        }

        if (postdata[grid_p.sortname] !== oldValueOfSortColumn) {
            // if the data are changed in the column by which are currently sorted
            // we need resort the grid
            setTimeout(function () {
                grid.trigger("reloadGrid", [{ current: true}]);
            }, 100);
        }

        // !!! the most important step: skip ajax request to the server
        this.processing = true;
        return {};

    },

    editSettings = {
        //recreateForm:true,
        jqModal: false,
        reloadAfterSubmit: false,
        closeOnEscape: true,
        savekey: [true, 13],
        closeAfterEdit: true,
        onclickSubmit: onclickSubmitLocal
    },

    addSettings = {
        //recreateForm:true,
        jqModal: false,
        reloadAfterSubmit: false,
        savekey: [true, 13],
        closeOnEscape: true,
        closeAfterAdd: true,
        onclickSubmit: onclickSubmitLocal
    },

    delSettings = {
        // because I use "local" data I don't want to send the changes to the server
        // so I use "processing:true" setting and delete the row manually in onclickSubmit
        onclickSubmit: function (options, rowid) {
            var grid_id = grid[0].id,
                grid_p = grid[0].p,
                newPage = grid[0].p.page;

            // delete the row
            grid.delRowData(rowid);
            $.jgrid.hideModal("#delmod" + grid_id,
                              { gb: "#gbox_" + grid_id, jqm: options.jqModal, onClose: options.onClose });

            if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
                if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
                    // if after deliting there are no rows on the current page
                    // which is the last page of the grid
                    newPage--; // go to the previous page
                }
                // reload grid to make the row from the next page visable.
                grid.trigger("reloadGrid", [{ page: newPage}]);
            }

            return true;
        },
        processing: true
    };         //,
    /*initDateEdit = function (elem) {
        setTimeout(function () {
            $(elem).datepicker({
                dateFormat: 'dd-M-yy',
                autoSize: true,
                showOn: 'button', // it dosn't work in searching dialog
                changeYear: true,
                changeMonth: true,
                showButtonPanel: true,
                showWeek: true
            });
            //$(elem).focus();
        }, 100);
    },
    initDateSearch = function (elem) {
        setTimeout(function () {
            $(elem).datepicker({
                dateFormat: 'dd-M-yy',
                autoSize: true,
                //showOn: 'button', // it dosn't work in searching dialog
                changeYear: true,
                changeMonth: true,
                showButtonPanel: true,
                showWeek: true
            });
            //$(elem).focus();
        }, 100);
    };*/

    //jQuery("#ta_form_d").jqGrid({
    grid.jqGrid({
        // url:'/admin/tg_cma/ta_allocations.asp?acmid=' + acmid + '&mid=' + merchantid + '&approval_code=' + approval_code,
        //datatype: "local",
        //data: mydata,
        datatype: 'jsonstring',
        datastr: mydata,

        colNames: ['ID', 'Monthly Fees', 'ATM Fees', 'POS Fees', 'Card to Card Fees'],
        colModel: [
        { name: 'id', index: 'id', width: 90, align: "center", editable: true, editoptions: { size: 25 }, formoptions: { rowpos: 1, colpos: 1, label: "EzyAccount ID", elmprefix: "(*) " }, editrules: { required: true} },
        { name: 'mf', index: 'mf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 2, colpos: 1, label: "Monthly Fee", elmprefix: "(*) " }, editrules: { required: true} },
        { name: 'af', index: 'af', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 3, colpos: 1, label: "ATM Fee", elmprefix: "(*) " }, editrules: { required: true} },
        { name: 'pf', index: 'pf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 4, colpos: 1, label: "POS Fee", elmprefix: "(*) " }, editrules: { required: true} },
        { name: 'cf', index: 'cf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 5, colpos: 1, label: "Card to Card Fee", elmprefix: "(*) " }, editrules: { required: true} }
    ],
        rowNum: 5,
        rowList: [5, 10, 20],
        pager: '#pta_form_d',
        toolbar: [true, "top"],
        width: 500,
        height: 100,
        editurl: 'clientArray',
        sortname: 'id',
        viewrecords: true,
        sortorder: "asc",
        multiselect: false,
        cellEdit: false,
        caption: "Allocations",
        grouping: true,
        /*groupingView: {
            groupField: ['id', 'mf', 'af', 'pf', 'cf'],
            groupColumnShow: [true],
            groupText: ['<b>{0}</b>'],
            groupCollapse: false,
            groupOrder: ['asc'],
            groupSummary: [true],
            groupDataSorted: true
        },*/
        footerrow: true,
        userDataOnFooter: true,
        altRows: true,
        ondblClickRow: function (rowid, ri, ci) {
            var p = grid[0].p;
            if (p.selrow !== rowid) {
                // prevent the row from be unselected on double-click
                // the implementation is for "multiselect:false" which we use,
                // but one can easy modify the code for "multiselect:true"
                grid.jqGrid('setSelection', rowid);
            }
            grid.jqGrid('editGridRow', rowid, editSettings);
        },
        onSelectRow: function (id) {
            if (id && id !== lastSel) {
                // cancel editing of the previous selected row if it was in editing state.
                // jqGrid hold intern savedRow array inside of jqGrid object,
                // so it is safe to call restoreRow method with any id parameter
                // if jqGrid not in editing state
                if (typeof lastSel !== "undefined") {
                    grid.jqGrid('restoreRow', lastSel);
                }
                lastSel = id;
            }
        },
        afterEditCell: function (rowid, cellname, value, iRow, iCol) {
            alert(iCol);
        },
        gridComplete: function () {

        },
        loadComplete: function (data) {

        }

    })
.jqGrid('navGrid', '#pta_form_d', {}, editSettings, addSettings, delSettings,
          { multipleSearch: true, overlay: false,
              onClose: function (form) {
                  // if we close the search dialog during the datapicker are opened
                  // the datepicker will stay opened. To fix this we have to hide
                  // the div used by datepicker
                  //$("div#ui-datepicker-div.ui-datepicker").hide();
              }
          });

$("#t_ta_form_d").append("<input type='button' class='add' value='Add New Allocation' style='height:20px; color:green; font-size:11px;' />");
$("input.add", "#t_ta_form_d").click(function () {
    jQuery("#ta_form_d").jqGrid('editGridRow', "new", {
        //recreateForm:true,
        jqModal: false,
        reloadAfterSubmit: false,
        savekey: [true, 13],
        closeOnEscape: true,
        closeAfterAdd: true,
        onclickSubmit: onclickSubmitLocal

    })
})
</code>```

答:
In case of "local" datatype one can use footerData method to set (or get) the data in the footer. Additionally the method getCol can be used co calculate the sum of elements in the column.

Look at the answer for more information. I hope it will solve your problem.

Body:
I have poured through every question asked on this website related to populating the jqGrid summary footer WITHOUT the userdata being a server request. And the jqGrid wiki resource and just cannot find an answer. Is this possible to do?

I use the jqGrid in many typical ways as part of my admin portal but have one particular use where I want the look & feel of the jqGrid to start out as an empty UI container of sorts for some user interaction adding rows through a form which doesn't post on Submit (thanks to Oleg's great script below) but simply adds the row and updates the summary footer with the values from the newly added row. I have 'summarytype:"sum"' in the colModel, "grouping:true", footerrow: true, userDataOnFooter: true, altRows: true, in the grid options but apart from the initial values supplied by the userdata in the local data string, the summary footer values never change. It seems like no one wants to touch this subject. Is it because the primary nature of the jqGrid is it's database driven functionality? I use about 15 instances of the jqGrid in it's database driven stance (many of which are in a production service now) but need to use it for consistency sake (all my UI's are inside jqTabs) initially as a client side UI with no server request (everything will be saved later to db) but I am pulling my hair out trying to manipulate the summary footer programmatically on and by the client only. Can anyone suggest how to cause values to the summary footer to update when a new row is added the values of which would be summed up with any existing rows and which does not involve any posting to server, just updates inside the grid?

The code supplied is kind of long and based primarily on user Oleg's solution for adding a row from a modal form without posting to the server. I've changed the local array data to JSON string simply to better understand the notation as I'm used to xml. The jsonstring initializes the grid with one default row for the user to edit. I've left out the jsonReader because the grid would not render with it.

In a nutshell then what I want to do is to have the summary footer update when a new row is added to the grid (no posting to server occurring at this point) or edited or deleted. When a certain set of values is achieved the user is prompted by a displayed button to save row data to db.

var lastSel, mydata = { "total": 1, "page": 1, "records": 1, "rows": [{ "id": acmid, "cell": ["0.00", "0.00", "0.00", "0.00"]}], "userdata":{ "mf": 0.00, "af":0.00,"pf":0.00,"cf":0.00 }}

grid = $("#ta_form_d"),
    onclickSubmitLocal = function (options, postdata) {

        var grid_p = grid[0].p,
            idname = grid_p.prmNames.id,
            grid_id = grid[0].id,
            id_in_postdata = grid_id + "_id",
            rowid = postdata[id_in_postdata],
            addMode = rowid === "_empty",
            oldValueOfSortColumn;

        // postdata has row id property with another name. we fix it:
        if (addMode) {
            // generate new id
            var new_id = grid_p.records + 1;
            while ($("#" + new_id).length !== 0) {
                new_id++;
            }
            postdata[idname] = String(new_id);
            //alert(postdata[idname]);
        } else if (typeof (postdata[idname]) === "undefined") {
            // set id property only if the property not exist
            postdata[idname] = rowid;
        }

        delete postdata[id_in_postdata];

        // prepare postdata for tree grid
        if (grid_p.treeGrid === true) {
            if (addMode) {
                var tr_par_id = grid_p.treeGridModel === 'adjacency' ? grid_p.treeReader.parent_id_field : 'parent_id';
                postdata[tr_par_id] = grid_p.selrow;
            }

            $.each(grid_p.treeReader, function (i) {
                if (postdata.hasOwnProperty(this)) {
                    delete postdata[this];
                }
            });
        }

        // decode data if there encoded with autoencode
        if (grid_p.autoencode) {
            $.each(postdata, function (n, v) {
                postdata[n] = $.jgrid.htmlDecode(v); // TODO: some columns could be skipped
            });
        }

        // save old value from the sorted column
        oldValueOfSortColumn = grid_p.sortname === "" ? undefined : grid.jqGrid('getCell', rowid, grid_p.sortname);
        //alert(oldValueOfSortColumn);
        // save the data in the grid
        if (grid_p.treeGrid === true) {
            if (addMode) {
                grid.jqGrid("addChildNode", rowid, grid_p.selrow, postdata);
            } else {
                grid.jqGrid("setTreeRow", rowid, postdata);
            }
        } else {

           if (addMode) {
                grid.jqGrid("addRowData", rowid, postdata, options.addedrow);

            } else {
                grid.jqGrid("setRowData", rowid, postdata);
            }
        }

        if ((addMode && options.closeAfterAdd) || (!addMode && options.closeAfterEdit)) {
            // close the edit/add dialog
            $.jgrid.hideModal("#editmod" + grid_id,
                              { gb: "#gbox_" + grid_id, jqm: options.jqModal, onClose: options.onClose });
        }

        if (postdata[grid_p.sortname] !== oldValueOfSortColumn) {
            // if the data are changed in the column by which are currently sorted
            // we need resort the grid
            setTimeout(function () {
                grid.trigger("reloadGrid", [{ current: true}]);
            }, 100);
        }

        // !!! the most important step: skip ajax request to the server
        this.processing = true;
        return {};

    },

    editSettings = {
        //recreateForm:true,
        jqModal: false,
        reloadAfterSubmit: false,
        closeOnEscape: true,
        savekey: [true, 13],
        closeAfterEdit: true,
        onclickSubmit: onclickSubmitLocal
    },

    addSettings = {
        //recreateForm:true,
        jqModal: false,
        reloadAfterSubmit: false,
        savekey: [true, 13],
        closeOnEscape: true,
        closeAfterAdd: true,
        onclickSubmit: onclickSubmitLocal
    },

    delSettings = {
        // because I use "local" data I don't want to send the changes to the server
        // so I use "processing:true" setting and delete the row manually in onclickSubmit
        onclickSubmit: function (options, rowid) {
            var grid_id = grid[0].id,
                grid_p = grid[0].p,
                newPage = grid[0].p.page;

            // delete the row
            grid.delRowData(rowid);
            $.jgrid.hideModal("#delmod" + grid_id,
                              { gb: "#gbox_" + grid_id, jqm: options.jqModal, onClose: options.onClose });

            if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
                if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
                    // if after deliting there are no rows on the current page
                    // which is the last page of the grid
                    newPage--; // go to the previous page
                }
                // reload grid to make the row from the next page visable.
                grid.trigger("reloadGrid", [{ page: newPage}]);
            }

            return true;
        },
        processing: true
    };         //,
    /*initDateEdit = function (elem) {
        setTimeout(function () {
            $(elem).datepicker({
                dateFormat: 'dd-M-yy',
                autoSize: true,
                showOn: 'button', // it dosn't work in searching dialog
                changeYear: true,
                changeMonth: true,
                showButtonPanel: true,
                showWeek: true
            });
            //$(elem).focus();
        }, 100);
    },
    initDateSearch = function (elem) {
        setTimeout(function () {
            $(elem).datepicker({
                dateFormat: 'dd-M-yy',
                autoSize: true,
                //showOn: 'button', // it dosn't work in searching dialog
                changeYear: true,
                changeMonth: true,
                showButtonPanel: true,
                showWeek: true
            });
            //$(elem).focus();
        }, 100);
    };*/

    //jQuery("#ta_form_d").jqGrid({
    grid.jqGrid({
        // url:'/admin/tg_cma/ta_allocations.asp?acmid=' + acmid + '&mid=' + merchantid + '&approval_code=' + approval_code,
        //datatype: "local",
        //data: mydata,
        datatype: 'jsonstring',
        datastr: mydata,

        colNames: ['ID', 'Monthly Fees', 'ATM Fees', 'POS Fees', 'Card to Card Fees'],
        colModel: [
        { name: 'id', index: 'id', width: 90, align: "center", editable: true, editoptions: { size: 25 }, formoptions: { rowpos: 1, colpos: 1, label: "EzyAccount ID", elmprefix: "(*) " }, editrules: { required: true} },
        { name: 'mf', index: 'mf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 2, colpos: 1, label: "Monthly Fee", elmprefix: "(*) " }, editrules: { required: true} },
        { name: 'af', index: 'af', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 3, colpos: 1, label: "ATM Fee", elmprefix: "(*) " }, editrules: { required: true} },
        { name: 'pf', index: 'pf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 4, colpos: 1, label: "POS Fee", elmprefix: "(*) " }, editrules: { required: true} },
        { name: 'cf', index: 'cf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 5, colpos: 1, label: "Card to Card Fee", elmprefix: "(*) " }, editrules: { required: true} }
    ],
        rowNum: 5,
        rowList: [5, 10, 20],
        pager: '#pta_form_d',
        toolbar: [true, "top"],
        width: 500,
        height: 100,
        editurl: 'clientArray',
        sortname: 'id',
        viewrecords: true,
        sortorder: "asc",
        multiselect: false,
        cellEdit: false,
        caption: "Allocations",
        grouping: true,
        /*groupingView: {
            groupField: ['id', 'mf', 'af', 'pf', 'cf'],
            groupColumnShow: [true],
            groupText: ['{0}'],
            groupCollapse: false,
            groupOrder: ['asc'],
            groupSummary: [true],
            groupDataSorted: true
        },*/
        footerrow: true,
        userDataOnFooter: true,
        altRows: true,
        ondblClickRow: function (rowid, ri, ci) {
            var p = grid[0].p;
            if (p.selrow !== rowid) {
                // prevent the row from be unselected on double-click
                // the implementation is for "multiselect:false" which we use,
                // but one can easy modify the code for "multiselect:true"
                grid.jqGrid('setSelection', rowid);
            }
            grid.jqGrid('editGridRow', rowid, editSettings);
        },
        onSelectRow: function (id) {
            if (id && id !== lastSel) {
                // cancel editing of the previous selected row if it was in editing state.
                // jqGrid hold intern savedRow array inside of jqGrid object,
                // so it is safe to call restoreRow method with any id parameter
                // if jqGrid not in editing state
                if (typeof lastSel !== "undefined") {
                    grid.jqGrid('restoreRow', lastSel);
                }
                lastSel = id;
            }
        },
        afterEditCell: function (rowid, cellname, value, iRow, iCol) {
            alert(iCol);
        },
        gridComplete: function () {

        },
        loadComplete: function (data) {

        }

    })
.jqGrid('navGrid', '#pta_form_d', {}, editSettings, addSettings, delSettings,
          { multipleSearch: true, overlay: false,
              onClose: function (form) {
                  // if we close the search dialog during the datapicker are opened
                  // the datepicker will stay opened. To fix this we have to hide
                  // the div used by datepicker
                  //$("div#ui-datepicker-div.ui-datepicker").hide();
              }
          });

$("#t_ta_form_d").append("<input type='button' class='add' value='Add New Allocation' style='height:20px; color:green; font-size:11px;' />");
$("input.add", "#t_ta_form_d").click(function () {
    jQuery("#ta_form_d").jqGrid('editGridRow', "new", {
        //recreateForm:true,
        jqModal: false,
        reloadAfterSubmit: false,
        savekey: [true, 13],
        closeOnEscape: true,
        closeAfterAdd: true,
        onclickSubmit: onclickSubmitLocal

    })
})


问:
Getting AAD App access token to call Azure App service with client secret
I am writing a Nodejs CLI to Deploy AAD-Auth Protected Web API via Azure ARM template. Facing issues in getting Access-Token to invoke the Web API.

I have used adal-node library to generate access token using AAD-App clientID and secret, but the generated token doesn't have valid objectId.

I also tried to get device_code and then tried to acquire access-token with same, but failed with error "needs permission to access resources in your organization that only an admin can grant. Please ask an admin to grant permission to this app before you can use it."..

However, if I go to the browser and enter https://app-service-name.azurewebsites.net/.auth/me, i am prompted to enter my azure login credentials and consent to let AAD-App access the resources, I am getting Access-token on the browser. And this access-token has all the properties (audience, issuer, objectId) i need. I am struggling to acquire similar access-token from nodejs CLI.

```<code>const context = new AuthenticationContext('https://login.microsoftonline.com/my-tenant-id');
context.acquireTokenWithClientCredentials(
    aadAppIdUri, aadAppId, aadClientSecret, (err: Error, result: any) => {
        if (err) {
            reject(err);
        } else {
            resolve(result.accessToken);
        }
    });
</code>```

I want to invoke the AAD-Protected web api from my Node CLI with valid Access-Token. Kindly help me generate the Access-Token for this.

答:
The way you get the access token via client credentials need application permission.

The way you get the access token via login credentials need delegated permission.

Make sure you have the needed application permission for your app.

Also, remember to click grant admin consent button.

Body:
I am writing a Nodejs CLI to Deploy AAD-Auth Protected Web API via Azure ARM template. Facing issues in getting Access-Token to invoke the Web API.

I have used adal-node library to generate access token using AAD-App clientID and secret, but the generated token doesn't have valid objectId.

I also tried to get device_code and then tried to acquire access-token with same, but failed with error "needs permission to access resources in your organization that only an admin can grant. Please ask an admin to grant permission to this app before you can use it."..

However, if I go to the browser and enter https://app-service-name.azurewebsites.net/.auth/me, i am prompted to enter my azure login credentials and consent to let AAD-App access the resources, I am getting Access-token on the browser. And this access-token has all the properties (audience, issuer, objectId) i need. I am struggling to acquire similar access-token from nodejs CLI.

const context = new AuthenticationContext('https://login.microsoftonline.com/my-tenant-id');
context.acquireTokenWithClientCredentials(
    aadAppIdUri, aadAppId, aadClientSecret, (err: Error, result: any) => {
        if (err) {
            reject(err);
        } else {
            resolve(result.accessToken);
        }
    });

I want to invoke the AAD-Protected web api from my Node CLI with valid Access-Token. Kindly help me generate the Access-Token for this.


答:
use AVLayerVideoGravity.resizeAspectFit to fit the video in the screen:</p>

```<code>avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFit
</code>```

Title: How to change content mode on AVPlayer video?

Body:
use AVLayerVideoGravity.resizeAspectFit to fit the video in the screen:

avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFit


问:
Circular Reference in Unity Tutorial
I'm pretty new to Unity so I was watching some tutorials and in one of them they did this pattern:

GameController.cs

```<code>public class GameController : MonoBehaviour {

    [HideInInspector] public RoomNavigation roomNavigation;

    void Awake()
    {
        roomNavigation = GetComponent<RoomNavigation>();
    }
}
</code>```

RoomNavigation.cs

```<code>public class RoomNavigation: MonoBehaviour {

    GameController controller;

    void Awake()
    {
        controller = GetComponent<GameController>();
    }
}
</code>```

To me this seems like a pretty obvious case of circular reference but seeing as it was on one of their official tutorial I think I might be missing something about GetComponent. Can someone clarify as to if it is circular reference and if so, why would they teach it this way?

答:
There is no problem here

Just because ObjectA has a reference to ObjectB and ObjectB also has a reference to ObjectA doesn't mean anything beyond "they reference each other."

Computer science has been dealing with doubly linked lists for decades.

Does this cause a problem with garbage collection?

No, because GC knows about stuff like this unless it is a naive implementation of GC, but C# .NET has a good (or at least, not naive) GC system. It doesn't check to see if any object has any references it works top down: Main has a reference to GameObject which has a reference SomeObject, which has a reference to ObjectA which has a reference to ObjectB, which has a reference to ObjectA (oh, that one's already tracked, move on...).

Among other tactics, such as putting newly created objects in a pool to periodically check for still-alive-ness, and once its been alive for a while, it puts it into a pool of probably-still-alive that gets checked less often. Or using a field called isDead that gets marked as true by the class's Deconstructor (this will happen way, way down in the C++ underlying Unity code) that flags an object for the GC.

If both objects become isolated (i.e. their parent Game Object is destroyed), they too, will be destroyed.

What about code style or software architecture problems?

Probably. But that's entirely subjective and not on-topic here. Do these two objects HAVE to know about each other? Can they be one object instead? Do these classes have subtypes and are interchangeable?

Keep in mind that GameObject knows about Transform and Transform knows about GameObject already, and there's perfectly legitimate reasons for this to be true.

Title: Circular Reference in Unity Tutorial

Body:
I'm pretty new to Unity so I was watching some tutorials and in one of them they did this pattern:

GameController.cs

public class GameController : MonoBehaviour {

    [HideInInspector] public RoomNavigation roomNavigation;

    void Awake()
    {
        roomNavigation = GetComponent<RoomNavigation>();
    }
}

RoomNavigation.cs

public class RoomNavigation: MonoBehaviour {

    GameController controller;

    void Awake()
    {
        controller = GetComponent<GameController>();
    }
}

To me this seems like a pretty obvious case of circular reference but seeing as it was on one of their official tutorial I think I might be missing something about GetComponent. Can someone clarify as to if it is circular reference and if so, why would they teach it this way?


问:
How to detect if the audio is currently playing on an Android phone speaker?
I need to have some custom behavior in my app when the audio playback is done on the device speaker (not a wired headphone and not a BlueTooth receiver).
To do so I'm doing the following

```<code>    AudioManager audioManager = (AudioManager) service.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    isSpeakerPhoneOn = audioManager.isSpeakerphoneOn();
</code>```

But isSpeakerPhoneOn is always false.
By the way, I'm calling the code after playback is started.

Any idea what I'm doing wrong?

答:
I suggest you to try this</p>

```<code>AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
 {
     // do something - or don't
 }
</code>```

Body:
I need to have some custom behavior in my app when the audio playback is done on the device speaker (not a wired headphone and not a BlueTooth receiver).
To do so I'm doing the following

    AudioManager audioManager = (AudioManager) service.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    isSpeakerPhoneOn = audioManager.isSpeakerphoneOn();

But isSpeakerPhoneOn is always false.
By the way, I'm calling the code after playback is started.

Any idea what I'm doing wrong?

Body:
I suggest you to try this

AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
 {
     // do something - or don't
 }


问:
replaceChild() to move images functioning only once in javascript
I have 3 images side by side, and I have to put 2 buttons under them. Clicking on go forward, the images should move forward and change places, and go backward, vice versa.
I've tried to get this done with arrays, but it is not responding. It moves only once, and does the same action on the one click whether forward or backward. I've pasted my code in the codepen, please have a look. Pasting code here gives me trouble.
https://codepen.io/anon/pen/JqZPVW

```<code>function goleft(){
    imgscroll[0] = document.createElement("imgscl");
    imgscroll[1] = document.createElement("imgscl");
    imgscroll[2] = document.createElement("imgscl");

    for(var index=0 ; index < 3; index++)
    {
        legendChildNodes[index] = document.getElementById("legends").childNodes[index];
        imgscroll[index].src = imgArray[index];
    }
    if(imgArray[0] == document.getElementById("legends").childNodes[0].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[2]);
    }
    else if (imgArray[0] == document.getElementById("legends").childNodes[1].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[2]);
    }
    else if (imgArray[0] == document.getElementById("legends").childNodes[2].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[2]);
    }
}
</code>```

If anyone can help me with this.

答:
As the answer above to append image nodes dynamically..., though will render the whole area each time you go left or right. (But with only one time loading for images);

Refer code here: https://codepen.io/JohnnyWang0530/pen/OYEJaJ

<button onclick="goTo('left')">GO LEFT</button>
<button onclick="goTo('right')">GO RIGHT</button>
```

<pre class="lang-css prettyprint-override"><code>#legends img {
  width: 300px;
  margin: 0 5px;
}
</code>```

// Create image Src
let imgSrc = [
  "https://imagizer.imageshack.com/img921/9646/HCBvlG.jpg",
  "https://imagizer.imageshack.com/img924/3295/Fb6gMO.jpg",
  "https://imagizer.imageshack.com/img923/6089/01GQK7.jpg"
];
// Create image Nodes for use later
let imgNodes = [];

// Init images & dynamically append them into "legend"
function createImages() {
  let legend = document.getElementById('legends');

  // create image nodes at first time executing
  if (imgNodes.length === 0) {
    for (let i=0;i<imgSrc.length;i++) {
      imgNodes[i] = document.createElement('IMG');
      imgNodes[i].src = imgSrc[i];
    }
  }

  // clear all each time you press left or right
  legend.innerHTML = '';

  // append image nodes
  for (let i=0;i<imgNodes.length;i++) {
    legend.appendChild(imgNodes[i]);
  }
}

// function for goLeft & goRight
function goTo(direct) {
  let output = [];
  for (let i=0;i<imgNodes.length;i++) {
    if (direct === 'left') {
      output[i] = imgNodes[i + 1];
      output[imgNodes.length - 1] = imgNodes[0];
    } else if (direct === 'right') {
      output[i] = imgNodes[i - 1];
      output[0] = imgNodes[imgNodes.length - 1];
    }
  }
  imgNodes = output;
  createImages();
}

// Initiate the function
createImages();
```

Body:
I have 3 images side by side, and I have to put 2 buttons under them. Clicking on go forward, the images should move forward and change places, and go backward, vice versa.
I've tried to get this done with arrays, but it is not responding. It moves only once, and does the same action on the one click whether forward or backward. I've pasted my code in the codepen, please have a look. Pasting code here gives me trouble.
https://codepen.io/anon/pen/JqZPVW

function goleft(){
    imgscroll[0] = document.createElement("imgscl");
    imgscroll[1] = document.createElement("imgscl");
    imgscroll[2] = document.createElement("imgscl");

    for(var index=0 ; index < 3; index++)
    {
        legendChildNodes[index] = document.getElementById("legends").childNodes[index];
        imgscroll[index].src = imgArray[index];
    }
    if(imgArray[0] == document.getElementById("legends").childNodes[0].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[2]);
    }
    else if (imgArray[0] == document.getElementById("legends").childNodes[1].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[2]);
    }
    else if (imgArray[0] == document.getElementById("legends").childNodes[2].src)
    {
        document.getElementById("legends").replaceChild(imgscroll[0], legendChildNodes[0]);
        document.getElementById("legends").replaceChild(imgscroll[1], legendChildNodes[1]);
        document.getElementById("legends").replaceChild(imgscroll[2], legendChildNodes[2]);
    }
}

If anyone can help me with this.

Body:
As the answer above to append image nodes dynamically..., though will render the whole area each time you go left or right. (But with only one time loading for images);

Refer code here: https://codepen.io/JohnnyWang0530/pen/OYEJaJ

<div id="legends"></div>
<button onclick="goTo('left')">GO LEFT</button>
<button onclick="goTo('right')">GO RIGHT</button>

#legends img {
  width: 300px;
  margin: 0 5px;
}

// Create image Src
let imgSrc = [
  "https://imagizer.imageshack.com/img921/9646/HCBvlG.jpg",
  "https://imagizer.imageshack.com/img924/3295/Fb6gMO.jpg",
  "https://imagizer.imageshack.com/img923/6089/01GQK7.jpg"
];
// Create image Nodes for use later
let imgNodes = [];

// Init images & dynamically append them into "legend"
function createImages() {
  let legend = document.getElementById('legends');

  // create image nodes at first time executing
  if (imgNodes.length === 0) {
    for (let i=0;i<imgSrc.length;i++) {
      imgNodes[i] = document.createElement('IMG');
      imgNodes[i].src = imgSrc[i];
    }
  }

  // clear all each time you press left or right
  legend.innerHTML = '';

  // append image nodes
  for (let i=0;i<imgNodes.length;i++) {
    legend.appendChild(imgNodes[i]);
  }
}

// function for goLeft & goRight
function goTo(direct) {
  let output = [];
  for (let i=0;i<imgNodes.length;i++) {
    if (direct === 'left') {
      output[i] = imgNodes[i + 1];
      output[imgNodes.length - 1] = imgNodes[0];
    } else if (direct === 'right') {
      output[i] = imgNodes[i - 1];
      output[0] = imgNodes[imgNodes.length - 1];
    }
  }
  imgNodes = output;
  createImages();
}

// Initiate the function
createImages();


问:
Unable to force strictness in tail recursion
I am dealing with memory leaks in my Haskell program and I was able to isolate it to very basic laziness problem in dealing with arrays. I understand what's happening there. First element of the array is computed while the rest produce the delayed computations which consumes the heap. Unfortunately, I was unable to force strictness for the entire array computation.

I tried various combinations of seq, BangPatterns, ($!) without much success.

import Control.Monad

force x = x `seq` x

loop :: [Int] -> IO ()
loop x = do
  when (head x `mod` 10000000 == 0) $ print x
  let x' = force $ map (+1) x
  loop x'

main = loop $ replicate 200 1
```

<p>The profile with standard profiling options didn't give me any more information than I already know:</p>

<pre class="lang-sh prettyprint-override"><code>ghc -prof -fprof-auto-calls -rtsopts test.hs
./test +RTS -M300M -p -hc
</code>```

This runs out of memory in the matter of a few seconds.

答:
```<code>force x = x `seq` x
</code>```

That's useless. seq doesn't mean "evaluate this thing now"; it means "evaluate the left thing before returning the result of evaluating the right thing". When they're the same, it does nothing, and your force is equivalent to just id. Try this instead:

```<code>import Control.DeepSeq
import Control.Monad

loop :: [Int] -> IO ()
loop x = do
  when (head x `mod` 10000000 == 0) $ print x
  let x' = map (+1) x
  loop $!! x'

main = loop $ replicate 200 1
</code>```

That evaluates x' and everything in it before loop x', which is useful.

Alternatively, Control.DeepSeq has a force function that is useful. Its semantics in this case are "evaluate all of the elements of your list before returning the result of evaluating any of it". If you used its force function in place of your own, your original code would otherwise work, since the first line of loop does evaluate the beginning of the list.

Body:
I am dealing with memory leaks in my Haskell program and I was able to isolate it to very basic laziness problem in dealing with arrays. I understand what's happening there. First element of the array is computed while the rest produce the delayed computations which consumes the heap. Unfortunately, I was unable to force strictness for the entire array computation.

I tried various combinations of seq, BangPatterns, ($!) without much success.

import Control.Monad

force x = x `seq` x

loop :: [Int] -> IO ()
loop x = do
  when (head x `mod` 10000000 == 0) $ print x
  let x' = force $ map (+1) x
  loop x'

main = loop $ replicate 200 1

The profile with standard profiling options didn't give me any more information than I already know:

ghc -prof -fprof-auto-calls -rtsopts test.hs
./test +RTS -M300M -p -hc

This runs out of memory in the matter of a few seconds.

Body:
force x = x `seq` x

That's useless. seq doesn't mean "evaluate this thing now"; it means "evaluate the left thing before returning the result of evaluating the right thing". When they're the same, it does nothing, and your force is equivalent to just id. Try this instead:

import Control.DeepSeq
import Control.Monad

loop :: [Int] -> IO ()
loop x = do
  when (head x `mod` 10000000 == 0) $ print x
  let x' = map (+1) x
  loop $!! x'

main = loop $ replicate 200 1

That evaluates x' and everything in it before loop x', which is useful.

Alternatively, Control.DeepSeq has a force function that is useful. Its semantics in this case are "evaluate all of the elements of your list before returning the result of evaluating any of it". If you used its force function in place of your own, your original code would otherwise work, since the first line of loop does evaluate the beginning of the list.


问:
How to achieve the following using functions/stored procedure in SQL Server database
I have the following table with following data as

```<code>                                            Tab1
FutureMISBoundaryVersion  CurrentMISBoundaryVersion  FutureHAMBoundaryVersion  CurrentHAMBoundaryVersion
2:21,5:50,4:55,7:80,9:33  2:12,5:40,4:35,7:60,9:87   2:52,5:90,4:75,7:30,9:57  2:42,5:60,4:95,7:70,9:37
</code>```

This key value pair has to be split into and the value of each key has to be inserted into another table in the following fashion

```<code>FutureMIS-OAKVersion |FutureMIS-HAMVersion |FutureMIS-DURVersion | FutureMIS-BURVersion| FutureMIS-YRTVersion |DeviceMIS-OAKVersion|DeviceMIS-HAMVersion |DeviceMIS-DURVersion| DeviceMIS-BURVersion| DeviceMIS-YRTVersion
              33     |              80     |            21       |            55       |  50                  | 87                 |  60                 |12                  |35                   | 40
</code>```

i,e: when it finds column 'FutureMISBoundaryVersion' in tab1 then its value
'2:21,5:50,4:55,7:80,9:33' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:21 will be inserted into FutureMIS-DURVersion column.

Similarly key 5's value 50 will be inserted into FutureMIS-BURVersion column and so on for other keys

when it finds column 'CurrentMISBoundaryVersion' then

'2:12,5:40,4:35,7:60,9:87' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:12 will be inserted into CurrentMIS-DURVersion column similarly key 5's 40 value will be inserted into DeviceMIS-YRTVersion column and so on for other columns of the source table.

The table structure may extend as I have shown only 4 source table column  but logic for all the columns remain same

答:
The following query will parse the comma separated string 2:21,5:50,4:55,7:80,9:33 into individual component 2:21, 5:30 etc. From there you can use similar method to extract bb from aa:bb.

Since the key-value pair is in format aa:bb, you can use datepart(hour, 'aa:bb') and datepart(minute, 'aa:bb') to extract aa and bb

```<code>; with
Tab1 as
(
    select  val  = '2:21,5:50,4:55,7:80,9:33'
)
select  t.*, k1.k, k2.k, k3.k, k4.k, k5.k
from    Tab1 t
    cross apply
    (
        select  i = charindex(',', t.val),
            k = substring(t.val, 1, charindex(',', t.val + ',', 1) - 1)
    ) k1
    cross apply
    (
        select  i = charindex(',', t.val, k1.i + 1),
            k = substring(t.val, k1.i + 1, charindex(',', t.val + ',', k1.i + 1) - k1.i - 1)
    ) k2
    cross apply
    (
        select  i = charindex(',', t.val, k2.i + 1),
            k = substring(t.val, k2.i + 1, charindex(',', t.val + ',', k2.i + 1) - k2.i - 1)
    ) k3
    cross apply
    (
        select  i = charindex(',', t.val, k3.i + 1),
            k = substring(t.val, k3.i + 1, charindex(',', t.val + ',', k3.i + 1) - k3.i - 1)
    ) k4
    cross apply
    (
        select  i = charindex(',', t.val, k4.i + 1),
            k = substring(t.val, k4.i + 1, charindex(',', t.val + ',', k4.i + 1) - k4.i - 1)
    ) k5
</code>```

Body:
I have the following table with following data as

                                            Tab1
FutureMISBoundaryVersion  CurrentMISBoundaryVersion  FutureHAMBoundaryVersion  CurrentHAMBoundaryVersion
2:21,5:50,4:55,7:80,9:33  2:12,5:40,4:35,7:60,9:87   2:52,5:90,4:75,7:30,9:57  2:42,5:60,4:95,7:70,9:37

This key value pair has to be split into and the value of each key has to be inserted into another table in the following fashion

FutureMIS-OAKVersion |FutureMIS-HAMVersion |FutureMIS-DURVersion | FutureMIS-BURVersion| FutureMIS-YRTVersion |DeviceMIS-OAKVersion|DeviceMIS-HAMVersion |DeviceMIS-DURVersion| DeviceMIS-BURVersion| DeviceMIS-YRTVersion
              33     |              80     |            21       |            55       |  50                  | 87                 |  60                 |12                  |35                   | 40

i,e: when it finds column 'FutureMISBoundaryVersion' in tab1 then its value
'2:21,5:50,4:55,7:80,9:33' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:21 will be inserted into FutureMIS-DURVersion column.

Similarly key 5's value 50 will be inserted into FutureMIS-BURVersion column and so on for other keys

when it finds column 'CurrentMISBoundaryVersion' then

'2:12,5:40,4:35,7:60,9:87' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:12 will be inserted into CurrentMIS-DURVersion column similarly key 5's 40 value will be inserted into DeviceMIS-YRTVersion column and so on for other columns of the source table.

The table structure may extend as I have shown only 4 source table column  but logic for all the columns remain same

Body:
The following query will parse the comma separated string 2:21,5:50,4:55,7:80,9:33 into individual component 2:21, 5:30 etc. From there you can use similar method to extract bb from aa:bb.

Since the key-value pair is in format aa:bb, you can use datepart(hour, 'aa:bb') and datepart(minute, 'aa:bb') to extract aa and bb

; with
Tab1 as
(
    select  val  = '2:21,5:50,4:55,7:80,9:33'
)
select  t.*, k1.k, k2.k, k3.k, k4.k, k5.k
from    Tab1 t
    cross apply
    (
        select  i = charindex(',', t.val),
            k = substring(t.val, 1, charindex(',', t.val + ',', 1) - 1)
    ) k1
    cross apply
    (
        select  i = charindex(',', t.val, k1.i + 1),
            k = substring(t.val, k1.i + 1, charindex(',', t.val + ',', k1.i + 1) - k1.i - 1)
    ) k2
    cross apply
    (
        select  i = charindex(',', t.val, k2.i + 1),
            k = substring(t.val, k2.i + 1, charindex(',', t.val + ',', k2.i + 1) - k2.i - 1)
    ) k3
    cross apply
    (
        select  i = charindex(',', t.val, k3.i + 1),
            k = substring(t.val, k3.i + 1, charindex(',', t.val + ',', k3.i + 1) - k3.i - 1)
    ) k4
    cross apply
    (
        select  i = charindex(',', t.val, k4.i + 1),
            k = substring(t.val, k4.i + 1, charindex(',', t.val + ',', k4.i + 1) - k4.i - 1)
    ) k5


问:
How to access params in variadic template function
The old way to make variadic function in C/C++ is using va_list, va_start, va_arg, va_end defined in cstdarg. C++11 comes with variadic function template syntax, but how to access the values?</p>

```<code>//example
#include <iostream>
using namespace std;

template <typename... types>
void print(types... Params){
  //this is not working:
  long Param1 = Params[0];
  long Param2 = Params[1];
}

int main(){
  print(123, 456);
  print(123, "foobar");
}
</code>```

答:
This a very simple (not disruptive) way to do it, although perhaps not optimal:

```<code>#include <iostream>
#include<tuple>
#include<cassert>

using namespace std;

template <typename... types>
void print(types... Params){
  long Param1 = std::get<0>(std::tie(Params...));
  long Param2 = std::get<1>(std::tie(Params...));
  assert(Param1 == 123 and Param2 == 456);
}
int main(){
  print(123, 456);
}
</code>```

https://godbolt.org/z/V8VA0W

If all elements are of the same type (and assuming you can copy them):

```<code>#include <iostream>
#include<tuple>
#include<cassert>

using namespace std;

template <typename... types>
void print(types... Params){
  std::array<long, sizeof...(Params)> params = {Params...};
  long Size = params.size();
  long Param1 = params[0];
  long Param2 = params[1];
  assert(Size == 2 and Param1 == 123 and Param2 == 456);
}

int main(){
  print(123, 456);
}
</code>```

It is not clear from your question but it looks like you want to print all the elements in the list, if you just want to do this then you can do it as follows (needs C++17, but you can do this with some work in c++11):

```<code>#include <iostream>

using namespace std;

template <typename... types>
void print(types... Params){
    std::cout << "number of elements: " << sizeof...(Params) << " ";
    ((std::cout << Params), ...);
}

int main(){
  print(123, 456);
}
</code>```

Body:
The old way to make variadic function in C/C++ is using va_list, va_start, va_arg, va_end defined in cstdarg. C++11 comes with variadic function template syntax, but how to access the values?

//example
#include <iostream>
using namespace std;

template <typename... types>
void print(types... Params){
  //this is not working:
  long Param1 = Params[0];
  long Param2 = Params[1];
}

int main(){
  print(123, 456);
  print(123, "foobar");
}

Body:
This a very simple (not disruptive) way to do it, although perhaps not optimal:

#include <iostream>
#include<tuple>
#include<cassert>

using namespace std;

template <typename... types>
void print(types... Params){
  long Param1 = std::get<0>(std::tie(Params...));
  long Param2 = std::get<1>(std::tie(Params...));
  assert(Param1 == 123 and Param2 == 456);
}
int main(){
  print(123, 456);
}

https://godbolt.org/z/V8VA0W

If all elements are of the same type (and assuming you can copy them):

#include <iostream>
#include<tuple>
#include<cassert>

using namespace std;

template <typename... types>
void print(types... Params){
  std::array<long, sizeof...(Params)> params = {Params...};
  long Size = params.size();
  long Param1 = params[0];
  long Param2 = params[1];
  assert(Size == 2 and Param1 == 123 and Param2 == 456);
}

int main(){
  print(123, 456);
}

It is not clear from your question but it looks like you want to print all the elements in the list, if you just want to do this then you can do it as follows (needs C++17, but you can do this with some work in c++11):

#include <iostream>

using namespace std;

template <typename... types>
void print(types... Params){
    std::cout << "number of elements: " << sizeof...(Params) << " ";
    ((std::cout << Params), ...);
}

int main(){
  print(123, 456);
}


问:
Powershell Az Module Remove-AzAutomationAccount Does Not Remove RunAs Account
When I remove an automation account in the Azure console it will remove the run as account connected to the automation account. When I run the 'Remove-AzAutomationAccount' command it will not remove the run as account. How can I remove the run as account through powershell when I'm removing the automation account?</p>

答:
You could remove the run as account via Remove-AzADApplication, try the command as below, it works fine on my side.

```<code>$connection = Get-AzAutomationConnection -ResourceGroupName <ResourceGroupName> -AutomationAccountName <AutomationAccountName> -Name AzureRunAsConnection
$appid = $connection.FieldDefinitionValues.ApplicationId
Remove-AzADApplication -ApplicationId $appid

Remove-AzAutomationAccount -ResourceGroupName <ResourceGroupName> -Name <AutomationAccountName>
</code>```

Body:
You could remove the run as account via Remove-AzADApplication, try the command as below, it works fine on my side.

$connection = Get-AzAutomationConnection -ResourceGroupName <ResourceGroupName> -AutomationAccountName <AutomationAccountName> -Name AzureRunAsConnection
$appid = $connection.FieldDefinitionValues.ApplicationId
Remove-AzADApplication -ApplicationId $appid

Remove-AzAutomationAccount -ResourceGroupName <ResourceGroupName> -Name <AutomationAccountName>


问:
Correct use of Angular TypeScript constructor - Can't resolve all parameters for
```<code>@Injectable({
  providedIn: 'root',
  /* useFactory: () => new MyService(MyAnotherService.myInteger) */
})
export class MyService{

  constructor(private someInteger?: number) {
    // doThings with someInteger
  }
</code>```

--aot build will complain that Warning: Can't resolve all parameters for...

In fact, due to the useFactory: () part, we are still able to run our application correctly. But I do not know if this is the right way or not

We can, of course, change the constructor to

```<code>constructor(private anotherService?: MyAnotherService) {
        // doThings with anotherService
      }
</code>```

To shut the build warning,
However I do not think that MyService should be dependent on MyAnotherService when It can be just dependent on a primitive, It's also bad for code reusability

What is the best thing to do in this situation?

My idea is that. Angular use Decorator to instruct that it is an Angular component ( am I right? )
So the main logic body should not always be coupled to Angular DI logic, especially if It is a service. We can pull the service code and plug it elsewhere ( Using DI or not )

答:
Consider these:

When facing issues that works in dev's ng serve but not in AOT, turn on "strictMetadataEmit" : true to get details on what's wrong.

For example, AOT does not work with arrow functions.

Use @Optional() for optional dependencies.

Body:
@Injectable({
  providedIn: 'root',
  /* useFactory: () => new MyService(MyAnotherService.myInteger) */
})
export class MyService{

  constructor(private someInteger?: number) {
    // doThings with someInteger
  }

--aot build will complain that Warning: Can't resolve all parameters for...

In fact, due to the useFactory: () part, we are still able to run our application correctly. But I do not know if this is the right way or not

We can, of course, change the constructor to

constructor(private anotherService?: MyAnotherService) {
        // doThings with anotherService
      }

To shut the build warning,
However I do not think that MyService should be dependent on MyAnotherService when It can be just dependent on a primitive, It's also bad for code reusability

What is the best thing to do in this situation?

My idea is that. Angular use Decorator to instruct that it is an Angular component ( am I right? )
So the main logic body should not always be coupled to Angular DI logic, especially if It is a service. We can pull the service code and plug it elsewhere ( Using DI or not )