问:
Google Chrome: Override geolocation via console
So a little background for my question; I am writing a simple driving instructions web application using Google Maps directions API which provides me with a LatLng path along with text instructions.

In order to test this application (without driving around in a car) I need to simulate a geolocation-path. Google Chrome supports overriding geolocation data via the sensors developer settings, which works fine with one coordinate at the time.

So my question is - is it possible to set the browsers navigator.geolocation data via the console (i.e. javascript api) instead manually updating the value in the sensors settings menu?

I know that in this case I could just use another input source than the browser geolocation data and use a static array of LatLng's, or override the browsers navigator.geolocation.getCurrentPosition, but I figured that it would be more sophisticated to override the sensors instead.

Thanks in advance.

答:
One way is to override the function navigator.geolocation.getCurrentPosition with your own custom function. Inside the custom function you can customize the value of latitude & longitude.

```<code>var customPosition = {};
customPosition.coords = {};
customPosition.coords.latitude = 41.89;
customPosition.coords.longitude = 2.89;

navigator.geolocation.getCurrentPosition = function(success, error){
    success(customPosition);

};

function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    console.log("latitude: " + latitude);
    console.log("longitude: " + longitude);
  }
</code>```

Body:
One way is to override the function navigator.geolocation.getCurrentPosition with your own custom function. Inside the custom function you can customize the value of latitude & longitude.

var customPosition = {};
customPosition.coords = {};
customPosition.coords.latitude = 41.89;
customPosition.coords.longitude = 2.89;

navigator.geolocation.getCurrentPosition = function(success, error){
    success(customPosition);

};

function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    console.log("latitude: " + latitude);
    console.log("longitude: " + longitude);
  }


来源: stackexchange

问:
Set variables values whose name is passed by string in C#
I'm searching a method for setting dynamically the values of a list of variables whose names and values are readed from a database.

I've found a lot of code for getting the variable name and value, but nothing that works for setting the value.

I'll try to explain myself better.
Think to have a database that contains two columns, say "name" and "value".
Say for example that you have two records:

1)  Name="string1", Value="message1"
2)  Name="string2", Value="message2"

I have the code to read the two records, what i want is a way to take dinamically the names of the variables from the records and assign to them the corresponding values.

The code is this:

```<code>SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    var v1 = dr["Name"].ToString();
    var v2 = dr[lng].ToString();

    //Something here to assign the value stored in v2 to the variable whose name is stored in v1

}
</code>```

Thank you all

答:
Based on your comments, you want to access "controls by name"; this is accomplished with Controls.Find():</p>

```<code>Control ctl = this.Controls.Find(v1, true).FirstOrDefault();
if (ctl != null && ctl is TextBox)
{
    TextBox tb = (TextBox)ctl;
    tb.Text = v2;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm searching a method for setting dynamically the values of a list of variables whose names and values are readed from a database.

I've found a lot of code for getting the variable name and value, but nothing that works for setting the value.

I'll try to explain myself better.
Think to have a database that contains two columns, say "name" and "value".
Say for example that you have two records:

1)  Name="string1", Value="message1"
2)  Name="string2", Value="message2"

I have the code to read the two records, what i want is a way to take dinamically the names of the variables from the records and assign to them the corresponding values.

The code is this:

SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    var v1 = dr["Name"].ToString();
    var v2 = dr[lng].ToString();

    //Something here to assign the value stored in v2 to the variable whose name is stored in v1

}

Thank you all

Body:
Based on your comments, you want to access "controls by name"; this is accomplished with Controls.Find():

Control ctl = this.Controls.Find(v1, true).FirstOrDefault();
if (ctl != null && ctl is TextBox)
{
    TextBox tb = (TextBox)ctl;
    tb.Text = v2;
}


问:
Maven and Gitlab: release:prepare uses the wrong SCM URL
I am trying to do mvn release:prepare on a multi-module project which is hosted on a Gitlab server.

The pom.xml for my master POM contains:

```<code><scm>
    <connection>scm:git:http://my-git-server.example.com/git/somebody/my-project.git</connection>
    <url>http://my-git-server.example.com/git/somebody/my-project</url>
</scm>
</code>```

When I do mvn release:prepare -DautoVersionSubmodules=true, it compiles everything and runs the test, but then fails with:

```<code>[INFO] Executing: /bin/sh -c cd /home/somebody/git/my-project && git tag -F /tmp/maven-scm-1594218362.commit my-project-1.0.0
[INFO] Working directory: /home/somebody/git/my-project
[INFO] Executing: /bin/sh -c cd /home/somebody/git/my-project && git push http://my-git-server.example.com/git/somebody my-project-1.0.0
[INFO] Working directory: /home/somebody/git/my-project
...
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.3.2:prepare (default-cli) on project iwes-lib-master: Unable to tag SCM
[ERROR] Provider message:
[ERROR] The git-push command failed.
[ERROR] Command output:
[ERROR] fatal: repository 'http://my-git-server.example.com/git/somebody/' not found
[ERROR] -> [Help 1]
</code>```

So it is telling me the maven-release-plugin thinks that the parent directory to my Git repository is the repository, bailing out there.

Adding a developerConnection does not help.

When trying to use SVN, it fails with "Access Denied:

```<code><scm>
    <connection>scm:git:http://my-git-server.example.com/git/somebody/my-project.git</connection>
    <developerConnection>ssh://git@my-git-server.example.com:10022/somebody/my-project.git</developerConnection>
    <url>http://my-git-server.example.com/git/somebody/my-project</url>
</scm>
</code>```

gives me:

```<code>[INFO] Executing: /bin/sh -c cd /home/jra/Documents/git/my-project && git push ssh://git@my-git-server.example.com:10022/somebody my-project-master-1.0.0
....
[ERROR] Access denied.
</code>```

So, it, again, uses the parent directory.

How do I force the release plugin to use the real URL I state there?

答:
I ran in the same issue with a call like that

```<code>mvn deploy scm:tag
</code>```

I'm using a gitlab installation and it also don't allow calls like this

```<code>[INFO] Executing: /bin/sh -c cd /home/user/prog/gitlab/test-user_server && git tag -F /tmp/maven-scm-482134407.commit test-user_server-1.1-SNAPSHOT
[INFO] Working directory: /home/user/prog/gitlab/test-user_server
[INFO] Executing: /bin/sh -c cd /home/user/prog/gitlab/test-user_server && git push user@gitlab.my.server:testplus/test-user_server.git refs/tags/test-user_server-1.1-SNAPSHOT
[INFO] Working directory: /home/user/prog/gitlab/test-user_server
[ERROR] Provider message:
[ERROR] The git-push command failed.
[ERROR] Command output:
[ERROR] Permission denied, please try again.
</code>```

The problem is this call

```<code>/bin/sh -c cd /home/user/prog/gitlab/test-user_server && git push user@gitlab.my.server:testplus/test-user_server.git refs/tags/test-user_server-1.1-SNAPSHOT
</code>```

But this call is not really necessary, because I start the mvn in the root of my git repository. Instead a command line call like the one below works.

git push origin refs/tags/test-user_server-1.1-SNAPSHOT

So I modified my scm configuration inside my pom.xml to a string like the following and it works for me like a charm.

```<code><scm>
    <developerConnection>scm:git:origin</developerConnection>
</scm>
</code>```

I develop under a Linux OS and so I have not tested if it works also on Windows system.

Body:
I am trying to do mvn release:prepare on a multi-module project which is hosted on a Gitlab server.

The pom.xml for my master POM contains:

<scm>
    <connection>scm:git:http://my-git-server.example.com/git/somebody/my-project.git</connection>
    <url>http://my-git-server.example.com/git/somebody/my-project</url>
</scm>

When I do mvn release:prepare -DautoVersionSubmodules=true, it compiles everything and runs the test, but then fails with:

[INFO] Executing: /bin/sh -c cd /home/somebody/git/my-project && git tag -F /tmp/maven-scm-1594218362.commit my-project-1.0.0
[INFO] Working directory: /home/somebody/git/my-project
[INFO] Executing: /bin/sh -c cd /home/somebody/git/my-project && git push http://my-git-server.example.com/git/somebody my-project-1.0.0
[INFO] Working directory: /home/somebody/git/my-project
...
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.3.2:prepare (default-cli) on project iwes-lib-master: Unable to tag SCM
[ERROR] Provider message:
[ERROR] The git-push command failed.
[ERROR] Command output:
[ERROR] fatal: repository 'http://my-git-server.example.com/git/somebody/' not found
[ERROR] -> [Help 1]

So it is telling me the maven-release-plugin thinks that the parent directory to my Git repository is the repository, bailing out there.

Adding a developerConnection does not help.

When trying to use SVN, it fails with "Access Denied:

<scm>
    <connection>scm:git:http://my-git-server.example.com/git/somebody/my-project.git</connection>
    <developerConnection>ssh://git@my-git-server.example.com:10022/somebody/my-project.git</developerConnection>
    <url>http://my-git-server.example.com/git/somebody/my-project</url>
</scm>

gives me:

[INFO] Executing: /bin/sh -c cd /home/jra/Documents/git/my-project && git push ssh://git@my-git-server.example.com:10022/somebody my-project-master-1.0.0
....
[ERROR] Access denied.

So, it, again, uses the parent directory.

How do I force the release plugin to use the real URL I state there?

Body:
I ran in the same issue with a call like that

mvn deploy scm:tag

I'm using a gitlab installation and it also don't allow calls like this

[INFO] Executing: /bin/sh -c cd /home/user/prog/gitlab/test-user_server && git tag -F /tmp/maven-scm-482134407.commit test-user_server-1.1-SNAPSHOT
[INFO] Working directory: /home/user/prog/gitlab/test-user_server
[INFO] Executing: /bin/sh -c cd /home/user/prog/gitlab/test-user_server && git push user@gitlab.my.server:testplus/test-user_server.git refs/tags/test-user_server-1.1-SNAPSHOT
[INFO] Working directory: /home/user/prog/gitlab/test-user_server
[ERROR] Provider message:
[ERROR] The git-push command failed.
[ERROR] Command output:
[ERROR] Permission denied, please try again.

The problem is this call

/bin/sh -c cd /home/user/prog/gitlab/test-user_server && git push user@gitlab.my.server:testplus/test-user_server.git refs/tags/test-user_server-1.1-SNAPSHOT

But this call is not really necessary, because I start the mvn in the root of my git repository. Instead a command line call like the one below works.

git push origin refs/tags/test-user_server-1.1-SNAPSHOT

So I modified my scm configuration inside my pom.xml to a string like the following and it works for me like a charm.

<scm>
    <developerConnection>scm:git:origin</developerConnection>
</scm>

I develop under a Linux OS and so I have not tested if it works also on Windows system.


问:
ImageMagick script takes JPG and places on canvas but changes colour of JPG
I would like to take this logo and place it on a black background.

I am using the below script

```<code>convert -size 4000x4000 canvas:#000000 -background \#000000 background.jpg
composite rev.jpg -gravity center background.jpg output.jpg
open output.jpg
</code>```

Which generates. As you can see the colours have changed and I cannot work out why?

答:
Possibly a colour profile or are you using CMYK for the rev.jpg?

Try this which will shorten your code:

```<code>convert rev.jpg -background black -gravity center -extent 4000x4000 output.jpg
</code>```

Body:
I would like to take this logo and place it on a black background.

I am using the below script

convert -size 4000x4000 canvas:#000000 -background \#000000 background.jpg
composite rev.jpg -gravity center background.jpg output.jpg
open output.jpg

Which generates. As you can see the colours have changed and I cannot work out why?

Body:
Possibly a colour profile or are you using CMYK for the rev.jpg?

Try this which will shorten your code:

convert rev.jpg -background black -gravity center -extent 4000x4000 output.jpg


问:
Cannot open a missing lib
Probably my question is a stupid question made by a newbie programmer but I'm stuck and don't know how to fix it.

I downloaded a project and tried to compile it. But it gives a LNK1104    cannot open file VirtuosoConsole.lib error, which I know a lib is missing but i don't know if I must compile it from source files or what I have to do. In case I have to build it, what I have to do to do it?

Thx for the help.

I'm using Visual Studio 2015 community.

答:
The cmake project should create the VirtuosoConsole library.

It is a cmake project, so you need to have cmake installed and run cmake on the project to generate the make files for visual studio to use.

Title: Cannot open a missing lib


问:
Using php header Location to exchange messages between pages with POST
I am using already this code:

```<code><?php
// [...]
ELSE IF(isset($_GET['msg'])){
    echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
    <h2 class='panel-title'>Good job!</h2></div>
    <div class='panel-body'><h4>".addslashes(strip_tags(trim(@$_GET[msg])))."</h4></div></div>";
    }
//[...]
?>
</code>```

Which is called from other pages if some operation goes well:

```<code>  if ($result){
      header("Location:index.php?msg=DB updated succesfully");
      exit;
  }
</code>```

BUT as you may imagine, it is not clean. Working, but not the best.

Can anybody tell me if I should move it to a POST request or if this code is "widely" used to exchange status messages between pages?

And, in case of the POST, can someone write down some code or redirect me to a page where this is explained well? I searched already of course, I found THIS from mozilla, THIS with jquery and in general searching "send post php header" on google.
But I just can't understand how to do it.

Thanks a lot guys!

答:
I think i'm going to go with this: PHP. How to pass variable and auto redirect to another PHP file

```<code><?php
 session_start();
 $id = $user_profile['id'];
 $_SESSION['id'] = $id;
 header('Location: checkIfExsists.php');
?>
</code>```

And on the checkIfExsists.php page, retrieve the variable so:

```<code><?php
 session_start();
 $id = $_SESSION['id'];
?>
</code>```

New code

```<code>session_start()
// [...]
ELSE IF(isset($_GET['msg'])){
    echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
    <h2 class='panel-title'>Good job!</h2></div>
    <div class='panel-body'><h4>".addslashes(strip_tags(trim(@$_SESSION['msg'])))."</h4></div></div>";
    }
</code>```

And..

```<code>session_start();
if ($result){
          $_SESSION['msg'] = "DB updated!";
          header("Location:index.php?msg");
          exit;
      }
</code>```

Body:
I am using already this code:

<?php
// [...]
ELSE IF(isset($_GET['msg'])){
    echo "

Good job!

".addslashes(strip_tags(trim(@$_GET[msg])))."

";
    }
//[...]
?>

Which is called from other pages if some operation goes well:

  if ($result){
      header("Location:index.php?msg=DB updated succesfully");
      exit;
  }

BUT as you may imagine, it is not clean. Working, but not the best.

Can anybody tell me if I should move it to a POST request or if this code is "widely" used to exchange status messages between pages?

And, in case of the POST, can someone write down some code or redirect me to a page where this is explained well? I searched already of course, I found THIS from mozilla, THIS with jquery and in general searching "send post php header" on google.
But I just can't understand how to do it.

Thanks a lot guys!

Body:
I think i'm going to go with this: PHP. How to pass variable and auto redirect to another PHP file

<?php
 session_start();
 $id = $user_profile['id'];
 $_SESSION['id'] = $id;
 header('Location: checkIfExsists.php');
?>

And on the checkIfExsists.php page, retrieve the variable so:

<?php
 session_start();
 $id = $_SESSION['id'];
?>

New code

session_start()
// [...]
ELSE IF(isset($_GET['msg'])){
    echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
    <h2 class='panel-title'>Good job!</h2></div>
    <div class='panel-body'><h4>".addslashes(strip_tags(trim(@$_SESSION['msg'])))."</h4></div></div>";
    }

And..

session_start();
if ($result){
          $_SESSION['msg'] = "DB updated!";
          header("Location:index.php?msg");
          exit;
      }


问:
C# how to pass unknown value variable ( user input ) to return method
Good Morning/Afternoon,

I'm would love some clarification on passing by reference and value. The program being posted works if I set the variable value to "0" but does not override after user input. So I believe the issue is passing, however my professor said everything should be static in this program.

Short: How to pass an input variable without the use of void?

I am very new. This is only chapter 3 so any assistance would be wonderful.

```<code>namespace Lesson3
{

class Program
{
    public static void Main(string[] args)
    {

        // declarations
        // 12 inches to a foot
        // 36 inches to a yard
        // 63360 inches per 1 mile
        double userInput= 0; // if "0" is removed the program will not function CS0165 error
        double feet = 12;
        double yards = 36;
        double miles = 63360;
        double ansFeet = userDivFeet(ref feet, ref userInput);
        double ansYards = userDivYards(ref yards, ref userInput);
        double ansMiles = userDivMiles(ref miles, ref userInput);

        Console.WriteLine("Please enter the number of inches to convert: ");
        userInput = Convert.ToInt32(Console.ReadLine());

        // output each calculation and display with console to hold the results
        WriteLine(userInput + " inches converts into " + ansFeet + " feet.");
        WriteLine(userInput + " inches converts into " + ansYards + " yards.");
        WriteLine(userInput + " inches converts into " + ansMiles + " miles.");
        Console.ReadKey();
    }

        public static double userDivFeet(ref double userInput, ref double feet)
    {
        return userInput / feet;
    }
    public static double userDivYards(ref double userInput, ref double yards)
    {
        return userInput / yards;
    }
    public static double userDivMiles(ref double userInput, ref double miles)

    {
        return userInput / miles;
    }

    }
</code>```

}

答:
You're using the variable userInput to call your method before assigning the user input. Accept the input first and then call the call the methods.

Also, you're declaring userInput as double but parsing the actual user input as int. Change it to parse it as double.

using System;

namespace Lesson3
{

```<code>internal class Program
{
    public static void Main(string[] args)
    {

        // declarations
        // 12 inches to a foot
        // 36 inches to a yard
        // 63360 inches per 1 mile
        double userInput=0; // if "0" is removed the program will not function CS0165 error
        double feet = 12;
        double yards = 36;
        double miles = 63360;
        Console.WriteLine("Please enter the number of inches to convert: ");
        userInput = Convert.ToInt32(Console.ReadLine());
        double ansFeet = userDivFeet(ref feet, ref userInput);
        double ansYards = userDivYards(ref yards, ref userInput);
        double ansMiles = userDivMiles(ref miles, ref userInput);

        // output each calculation and display with console to hold the results
        Console.WriteLine(userInput + " inches converts into " + ansFeet + " feet.");

        Console.WriteLine(userInput + " inches converts into " + ansYards + " yards.");
        Console.WriteLine(userInput + " inches converts into " + ansMiles + " miles.");
        Console.ReadKey();
    }

    public static double userDivFeet(ref double userInput, ref double feet)
    {
        return userInput/feet;
    }

    public static double userDivYards(ref double userInput, ref double yards)
    {
        return userInput/yards;
    }

    public static double userDivMiles(ref double userInput, ref double miles)

    {
        return userInput/miles;
    }

}
</code>```

}

Body:
Good Morning/Afternoon,

I'm would love some clarification on passing by reference and value. The program being posted works if I set the variable value to "0" but does not override after user input. So I believe the issue is passing, however my professor said everything should be static in this program.

Short: How to pass an input variable without the use of void?

I am very new. This is only chapter 3 so any assistance would be wonderful.

namespace Lesson3
{

class Program
{
    public static void Main(string[] args)
    {

        // declarations
        // 12 inches to a foot
        // 36 inches to a yard
        // 63360 inches per 1 mile
        double userInput= 0; // if "0" is removed the program will not function CS0165 error
        double feet = 12;
        double yards = 36;
        double miles = 63360;
        double ansFeet = userDivFeet(ref feet, ref userInput);
        double ansYards = userDivYards(ref yards, ref userInput);
        double ansMiles = userDivMiles(ref miles, ref userInput);

        Console.WriteLine("Please enter the number of inches to convert: ");
        userInput = Convert.ToInt32(Console.ReadLine());

        // output each calculation and display with console to hold the results
        WriteLine(userInput + " inches converts into " + ansFeet + " feet.");
        WriteLine(userInput + " inches converts into " + ansYards + " yards.");
        WriteLine(userInput + " inches converts into " + ansMiles + " miles.");
        Console.ReadKey();
    }

        public static double userDivFeet(ref double userInput, ref double feet)
    {
        return userInput / feet;
    }
    public static double userDivYards(ref double userInput, ref double yards)
    {
        return userInput / yards;
    }
    public static double userDivMiles(ref double userInput, ref double miles)

    {
        return userInput / miles;
    }

    }

}

Body:
You're using the variable userInput to call your method before assigning the user input. Accept the input first and then call the call the methods.

Also, you're declaring userInput as double but parsing the actual user input as int. Change it to parse it as double.

using System;

namespace Lesson3
{

internal class Program
{
    public static void Main(string[] args)
    {

        // declarations
        // 12 inches to a foot
        // 36 inches to a yard
        // 63360 inches per 1 mile
        double userInput=0; // if "0" is removed the program will not function CS0165 error
        double feet = 12;
        double yards = 36;
        double miles = 63360;
        Console.WriteLine("Please enter the number of inches to convert: ");
        userInput = Convert.ToInt32(Console.ReadLine());
        double ansFeet = userDivFeet(ref feet, ref userInput);
        double ansYards = userDivYards(ref yards, ref userInput);
        double ansMiles = userDivMiles(ref miles, ref userInput);

        // output each calculation and display with console to hold the results
        Console.WriteLine(userInput + " inches converts into " + ansFeet + " feet.");

        Console.WriteLine(userInput + " inches converts into " + ansYards + " yards.");
        Console.WriteLine(userInput + " inches converts into " + ansMiles + " miles.");
        Console.ReadKey();
    }

    public static double userDivFeet(ref double userInput, ref double feet)
    {
        return userInput/feet;
    }

    public static double userDivYards(ref double userInput, ref double yards)
    {
        return userInput/yards;
    }

    public static double userDivMiles(ref double userInput, ref double miles)

    {
        return userInput/miles;
    }

}

}


问:
How to do a basic contextualization in JavaScript using nlp-compromise?
So I saw this awesome natural language processing in javascript and I wonder how can I do a basic contextualization?

Let's say for example, I want to get the time.

By doing something like this:

```<code>var word = nlp(`What's the time`)

console.log(word.match('time').found)
</code>```

I get a true boolean since the time word is present. But what I wanted to do is for example

nlp('What's the time') and nlp('What time is it') the value will be true but if nlp('Time is gold') the value will be false since the user didn't ask for the time.

Is that possible with this library? Any help would be much appreciated.

答:
yeah, like polm23 said, this feels like a statistical classification problem.

but, if you knew, (or machine-learned) sentence-templates that suggest the intent, you could locate them in compromise with the match syntax

```<code>//what time is..
if(doc.has('#QuestionWord time #Copula')){
  return true
}
//time is fun..
if(doc.has('time #Copula #Adjective')){
  return false
}
</code>```

Body:
So I saw this awesome natural language processing in javascript and I wonder how can I do a basic contextualization?

Let's say for example, I want to get the time.

By doing something like this:

var word = nlp(`What's the time`)

console.log(word.match('time').found)

I get a true boolean since the time word is present. But what I wanted to do is for example

nlp('What's the time') and nlp('What time is it') the value will be true but if nlp('Time is gold') the value will be false since the user didn't ask for the time.

Is that possible with this library? Any help would be much appreciated.

Body:
yeah, like polm23 said, this feels like a statistical classification problem.

but, if you knew, (or machine-learned) sentence-templates that suggest the intent, you could locate them in compromise with the match syntax

//what time is..
if(doc.has('#QuestionWord time #Copula')){
  return true
}
//time is fun..
if(doc.has('time #Copula #Adjective')){
  return false
}


问:
Processing some directives leaving others
I use to go through C code having lot of #ifdef, #if and #endif directive which keep some portion active and some portion inactive depending on some variables are defined or not. I searched for something that can process them to generate final C code. But the preprocessing also does the same for #include and #define. But I want to keep them.

So, is there any thing to preprocess these files or project with some filtering?

答:
There are a series of programs that can do that:

unifdef - the oldest

sunifdef (Son of Unifdef)

coan (Son of sunifdef)

I've used sunifdef extensively on some very contorted code and have never found it to make a mistake.  I'm ready to start using coan now, though it will still be under scrutiny for a while.  Version 4.2.2 was released today, 2010-12-20.

See also: SO 525283

ContentLicense: CC BY-SA 2.5


问:
How do I compare the value of string array?
I have declared a string array and I want to compare with name given by user,

```<code>string[] MasterList = new string[] {
  "Askay", "Puram", "Raman", "Srinivasa",
  "Gopal", "Rajesh", "Anju", "Nagara",
};

string YourName;
Console.WriteLine("Enter your name: ");
YourName = Console.ReadLine();

for(i=0; i<5; i++)
{
    a = String.Compare(MasterList[i], YourName);
    Console.WriteLine("Your name is not among the list")
}
</code>```

The resulting output is not what I am expecting, any ideas how I can go about it?

答:
Why not Contains?

```<code>  string[] MasterList = new string[] {
    "Askay", "Puram", "Raman", "Srinivasa",
    "Gopal", "Rajesh", "Anju", "Nagara",
  };

  Console.WriteLine("Enter your name: ");
  string YourName = Console.ReadLine();

  // StringComparer.OrdinalIgnoreCase if you want to ignore case
  // MasterList.Contains(YourName) if you want case sensitive
  if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
    Console.WriteLine("Your name is not among the list")
</code>```

Body:
I have declared a string array and I want to compare with name given by user,

string[] MasterList = new string[] {
  "Askay", "Puram", "Raman", "Srinivasa",
  "Gopal", "Rajesh", "Anju", "Nagara",
};

string YourName;
Console.WriteLine("Enter your name: ");
YourName = Console.ReadLine();

for(i=0; i<5; i++)
{
    a = String.Compare(MasterList[i], YourName);
    Console.WriteLine("Your name is not among the list")
}

The resulting output is not what I am expecting, any ideas how I can go about it?

Body:
Why not Contains?

  string[] MasterList = new string[] {
    "Askay", "Puram", "Raman", "Srinivasa",
    "Gopal", "Rajesh", "Anju", "Nagara",
  };

  Console.WriteLine("Enter your name: ");
  string YourName = Console.ReadLine();

  // StringComparer.OrdinalIgnoreCase if you want to ignore case
  // MasterList.Contains(YourName) if you want case sensitive
  if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
    Console.WriteLine("Your name is not among the list")


问:
Need help to install yii2 application advanced template
I'm new to Yii2, now I'm trying to install yii2 application advanced template.

I did follow these steps:

1 - Download yii2-app-advanced zip file from https://github.com/yiisoft/yii2-app-advanced

2 - Follow GETTING STARTED guide:

```<code> + I'm using Uniform Zero Server (installed in F disk with the path "F:\Server\UniServerZ\www") ok.
 + I creted new folder with name "yii2" in the "www" directory ("F:\Server\UniServerZ\www\yii2")
 + I extracted zip file yii2-app-advanced into "yii2" folder (Every source of yii2-app-advanced now in "yii2" folder so it is the root directory of yii2-app-advanced)
 + Click init.bat file to run "init" and select (0 - Developer mode) and type "yes" to confirm. Done
 + And then I click the yii.bat file, but nothing happened.
 + I tried use this url : localhost/yii2/backend/web/
   And I get this Error:
   Fatal error: require(): Failed opening required 'F:\Server\UniServerZ\www\yii2\backend\web/../../vendor/autoload.php' (include_path='.;F:/Server/UniServerZ/home/us_pear/PEAR') in F:\Server\UniServerZ\www\yii2\backend\web\index.php on line 5
                   or url : localhost/yii2/frontend/web/
   And I get this Error too:
   Fatal error: require(): Failed opening required 'F:\Server\UniServerZ\www\yii2\frontend\web/../../vendor/autoload.php' (include_path='.;F:/Server/UniServerZ/home/us_pear/PEAR') in F:\Server\UniServerZ\www\yii2\frontend\web\index.php on line 5
</code>```

I checked the "vendor" directory follow this path:
 F:\Server\UniServerZ\www\yii2\vendor
 But it's empty.

So what should I do to fix this error and install yii2 application advanced template?

(My Uniform Server runs PHP5.4)

答:
If you want to install Yii2 advanced template go to http://www.yiiframework.com/download/ and download the Yii 2 with advanced application template. Once you have extracted the archive file in the www folder.
 Then Go to Terminal(For Ubuntu) or cmd(Windows user)

For Ubuntu-
provide root to the extracted folder(advanced) in the Terminal
 cd var/www/html/ashish/advanced

Now give the commond- php init

Now advance template is installed properly

Body:
I'm new to Yii2, now I'm trying to install yii2 application advanced template.

I did follow these steps:

1 - Download yii2-app-advanced zip file from https://github.com/yiisoft/yii2-app-advanced

2 - Follow GETTING STARTED guide:

 + I'm using Uniform Zero Server (installed in F disk with the path "F:\Server\UniServerZ\www") ok.
 + I creted new folder with name "yii2" in the "www" directory ("F:\Server\UniServerZ\www\yii2")
 + I extracted zip file yii2-app-advanced into "yii2" folder (Every source of yii2-app-advanced now in "yii2" folder so it is the root directory of yii2-app-advanced)
 + Click init.bat file to run "init" and select (0 - Developer mode) and type "yes" to confirm. Done
 + And then I click the yii.bat file, but nothing happened.
 + I tried use this url : localhost/yii2/backend/web/
   And I get this Error:
   Fatal error: require(): Failed opening required 'F:\Server\UniServerZ\www\yii2\backend\web/../../vendor/autoload.php' (include_path='.;F:/Server/UniServerZ/home/us_pear/PEAR') in F:\Server\UniServerZ\www\yii2\backend\web\index.php on line 5
                   or url : localhost/yii2/frontend/web/
   And I get this Error too:
   Fatal error: require(): Failed opening required 'F:\Server\UniServerZ\www\yii2\frontend\web/../../vendor/autoload.php' (include_path='.;F:/Server/UniServerZ/home/us_pear/PEAR') in F:\Server\UniServerZ\www\yii2\frontend\web\index.php on line 5

I checked the "vendor" directory follow this path:
 F:\Server\UniServerZ\www\yii2\vendor
 But it's empty.

So what should I do to fix this error and install yii2 application advanced template?

(My Uniform Server runs PHP5.4)


问:
fakeAsync and tick when unit testing code with Promise and Observables
I assume that when testing code with Promises it is required to use fakeAsync/tick combination to guarantee that promises are resolves/rejects. This is because tick drains microtasks queue when invoked.

However, what about Observables? Should we also use fakeAsync/tick to guarantee that subscribe handler is invoked?
Looks like unit tests with Observables are completed fine, with all the subscribed Observer instances notified, without fakeAsync/tick so I'm not sure if this is required or not.

Thank you

答:
Late answer (You might have already figured this out by now). Although would like to mention it if anyone else is having the same doubt.

As explained in below answer, "each observable operator uses the minimum amount of asynchronicity needed to do its work".

Synchronicity in RxJS

So it depends primarily what RxJs Operator we use.

Let's say, we use a Subject/BehaviorSubject to push new values in the stream  while we are running Unit tests (I believe this is one of the ways to mock an Observable based data store implementation), then we do not need to have fakeAsync and tick since subscribe handlers will get called synchronously.


问:
PHP - Convert this string to another date/time format
I'm working with an API that returns timestamps in this format:

```<code>07/23/2017 23:39:21
</code>```

The format is: MM/DD/YYYY HH:MM:SS

I need to covert this string so it displays in this format on my webpage:

23 July 2017, 11:39pm

Is this possible?

答:
You can do this :

```<code>$date = new DateTime('07/23/2017 23:39:21');
echo $date->format('d F o, h:ia');
</code>```

Output :

23 July 2017, 11:39pm

Body:
I'm working with an API that returns timestamps in this format:

07/23/2017 23:39:21

The format is: MM/DD/YYYY HH:MM:SS

I need to covert this string so it displays in this format on my webpage:

23 July 2017, 11:39pm

Is this possible?

Body:
You can do this :

$date = new DateTime('07/23/2017 23:39:21');
echo $date->format('d F o, h:ia');

Output :

23 July 2017, 11:39pm


问:
Accessing a 'Variables' class more than once in arduino
I'm attempting to use classes in Arduino, so far its working successfully however I cannot reference a .H file more than once.

Error compiling for board... "multiple definition of `variable'"

I am basically looking to create a 'variables' class that multiple .cpp files can have access to. Any ideas on how to approach this?

This is different from "What should go into an .h file? " As its not the structure of the .H or .cpp file i necessarily need help with.

In c# I would create a class called for example Variables and then access them from any other class using Variables.Time... Any file can access this class and update the variables. However in Arduino it seems I am only able to access it from 1 file, whereas I need to access it from a library created in tabbed form and from the main .ino

答: Try Adding a #pragma once to the top of your .h file.


问:
Get Row Count of Dbset in DbContext dynamicly
I have a form that pass a instance of my DbContext and a Entity of Table to it as below :

```<code>public frm_foo(DbContext DatabaseContext, DbSet TableEntity)
        {
           InitializeComponent();
           var res =GetRowCount(DatabaseContext,TableEntity);
        }
</code>```

And call form contractor by:

```<code>new frm_foo(dbContext, dbContext.Set<IpRoom>()).ShowDialog();
</code>```

The Context contain a IpRoom table.

I want to get Count of row from in a function that send the DbContext and Dbset instance to it as below :

```<code>public int GetRowCount(DbContext DatabaseContext, DbSet TableEntity)
   {
       var countVal = (from a in DatabaseContext.Set(TableEntity.GetType())
                        select a).Count();
       return countVal;
   }
</code>```

But Got error:

Could not find an implementation of the query pattern for source type
  'DbSet'.  'Select' not found.

While DatabaseContext.Set(TableEntity.GetType()) return a Dbset! Anybody know whats my wrong? Thanks in advance

Ps: I dont want use SqlQuery, Something like:

```<code>var sql = "SELECT COUNT(*) FROM dbo.IpRoom";
var total = context.Database.SqlQuery<int>(sql).Single();
</code>```

答:
DbSet does not implement IQueryable, DbSet<T> does.  eg

```<code>public static int GetRowCount<T>(DbContext DatabaseContext, DbSet<T> TableEntity)
{
    var countVal = TableEntity.Count();
    return countVal;
}
</code>```

Body:
I have a form that pass a instance of my DbContext and a Entity of Table to it as below :

public frm_foo(DbContext DatabaseContext, DbSet TableEntity)
        {
           InitializeComponent();
           var res =GetRowCount(DatabaseContext,TableEntity);
        }

And call form contractor by:

new frm_foo(dbContext, dbContext.Set<IpRoom>()).ShowDialog();

The Context contain a IpRoom table.

I want to get Count of row from in a function that send the DbContext and Dbset instance to it as below :

public int GetRowCount(DbContext DatabaseContext, DbSet TableEntity)
   {
       var countVal = (from a in DatabaseContext.Set(TableEntity.GetType())
                        select a).Count();
       return countVal;
   }

But Got error:

Could not find an implementation of the query pattern for source type
  'DbSet'.  'Select' not found.

While DatabaseContext.Set(TableEntity.GetType()) return a Dbset! Anybody know whats my wrong? Thanks in advance

Ps: I dont want use SqlQuery, Something like:

var sql = "SELECT COUNT(*) FROM dbo.IpRoom";
var total = context.Database.SqlQuery<int>(sql).Single();

Body:
DbSet does not implement IQueryable, DbSet<T> does.  eg

public static int GetRowCount<T>(DbContext DatabaseContext, DbSet<T> TableEntity)
{
    var countVal = TableEntity.Count();
    return countVal;
}


问:
Compare two objects with .equals() and == operator
I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too. Here's what I've done:

```<code>public class MyClass {

    String a;

    public MyClass(String ab) {
        a = ab;
    }

    public boolean equals(Object object2) {
        if(a == object2) {
            return true;
        }
        else return false;
    }

    public boolean equals2(Object object2) {
        if(a.equals(object2)) {
            return true;
        }
        else return false;
    }

    public static void main(String[] args) {

        MyClass object1 = new MyClass("test");
        MyClass object2 = new MyClass("test");

        object1.equals(object2);
        System.out.println(object1.equals(object2));

        object1.equals2(object2);
        System.out.println(object1.equals2(object2));
    }

}
</code>```

After compile it shows two times false as a result. Why is it false if the two objects have the same fields - "test"?

答:
Here the output will be false , false beacuse in first sopln statement you are trying to compare a string type varible of Myclass type to the other MyClass type and it will allow because of both are Object type and you have used "==" oprerator which will check the reference variable value holding the actual memory not the actual contnets inside the memory .
In the second sopln also it is the same as you are again calling a.equals(object2) where a is a varible inside object1 . Do let me know your findings on this .</p>

Body:
I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too. Here's what I've done:

public class MyClass {

    String a;

    public MyClass(String ab) {
        a = ab;
    }

    public boolean equals(Object object2) {
        if(a == object2) {
            return true;
        }
        else return false;
    }

    public boolean equals2(Object object2) {
        if(a.equals(object2)) {
            return true;
        }
        else return false;
    }

    public static void main(String[] args) {

        MyClass object1 = new MyClass("test");
        MyClass object2 = new MyClass("test");

        object1.equals(object2);
        System.out.println(object1.equals(object2));

        object1.equals2(object2);
        System.out.println(object1.equals2(object2));
    }

}

After compile it shows two times false as a result. Why is it false if the two objects have the same fields - "test"?


问:
SQL Server Query too slow missing index?
I'm working with SQL Server 2012 and I have an query for the search purpose but It takes too long to execute.. (30 rows = 6sec)

I have checked up the execution plan but he doesn't suggest to put index and I don't know how i can speed up the query.

Here's my query:

```<code>SELECT
    dbo.tbRV.ID, dbo.tbRV.IDCompagnie,
    dbo.tbPatient.Nom + N', ' + dbo.tbPatient.Prenom AS NomPrenomPatient,
    dbo.tbRV.DateRV, dbo.tbRV.HeureDebut,
    dbo.tbRV.IDRessource,
    coalesce(dbo.tbRessource.Nom ,'') + ' '  + coalesce(dbo.tbRessource.Prenom,'') AS NomPrenomRessource,
    dbo.tbPatient.NoApp,
    dbo.tbPatient.NomEtablissement, dbo.tbPatient.Adresse1,
    tbAdresse.Ville, dbo.tbPatient.TelephoneDomicile,
    dbo.tbPatient.TelephoneTravail,
    dbo.tbPatient.TelephonePortable,
    case
       when DD.id is not null then DD.description
       else dbo.tbRVObjet.IDObjet
    end as idobjet,
    dbo.tbPatient.Nom_SansAccent, dbo.tbPatient.Prenom_SansAccent,
    dbo.tbPatient.Nom, dbo.tbPatient.Prenom,
    dbo.tbRV.IDPatient, dbo.tbPatient.NoAssuranceMaladie,
    dbo.tbPatient.DateNaissance, dbo.tbRV.Transit, dbo.tbRV.Annuler,
    tbAdresse.Pays, tbAdresse.Province, dbo.tbPatient.Adresse2,
    dbo.tbPatient.CodePostal,
    case
       when AA.id is not null and AA.ID = tbrvobjet.ID then 1 else 0 end as onlyFirst
FROM
    tbPatient
INNER JOIN
    tbRV ON tbPatient.ID = tbRV.IDPatient
INNER JOIN
    tbRessource ON (tbRV.IDRessource = tbRessource.ID) AND (tbRV.IDCompagnie = tbRessource.IDCompagnie)
INNER JOIN
    tbRVObjet ON tbRV.ID = tbRVObjet.IDRV
OUTER APPLY
    dbo.fn_GetFirstIDRVObjet(tbrv.id) AA
OUTER APPLY (SELECT A.ID, A.Description
             FROM tbForfaitEntete A
             WHERE A.ID = tbRVObjet.IDForfait
               AND ISNULL(tbRVObjet.IsForfaitEntete, 0) = 1 ) DD
OUTER APPLY (SELECT B.Description
             FROM tbRVObjet A
             JOIN tbForfaitEntete B ON (A.IDForfait  = B.ID AND  ISNULL(A.IsForfaitEntete, 0) = 1)
             WHERE AA.ID = A.id ) BB
OUTER APPLY (SELECT tbPaysISO.Pays, tbProvinceISO.Province, tbVilleISO.Ville
             FROM tbPaysISO
             JOIN tbProvinceISO ON (tbPaysISO.Langue = tbProvinceISO.Langue)
                                AND (tbPatient.ProvinceISOChar = tbProvinceISO.ProvinceISOChar)
             JOIN tbVilleISO ON (tbProvinceISO.Langue = tbVilleISO.Langue)
                             AND (tbPatient.IdVille  = tbVilleISO.IDVille)
             WHERE tbPaysISO.Langue = tbpatient.CodeLangue
               AND tbPaysISO.PaysISOChar3 = tbpatient.PaysISOChar3 ) tbAdresse
</code>```

and here's the execution plan in XML:

EDIT:

Here's my query plan URL: https://www.brentozar.com/pastetheplan/?id=HkVYeasNW

Here's my search query :

```<code>Select
    ID, IDPatient, NomPrenomPatient, DateNaissance, NoAssuranceMaladie,
    NomEtablissement, Adresse1, Adresse2, NoApp, ville, province, pays,
    CodePostal, TelephoneDomicile, TelephoneTravail, TelephonePortable,
    DateRV, HeureDebut, IDObjet, IDRessource, NomPrenomRessource,
    Annuler, Transit
From
    rqAfficheRechercheRV
Where
    IDCompagnie = 1
    And (isnull(NomPrenomRessource, '') + isnull(NoApp, '') + isnull(NomEtablissement, '') + isnull(Adresse1, '') + isnull(Ville, '') + isnull(TelephoneDomicile, '') + isnull(TelephoneTravail, '') + isnull(TelephonePortable, '') + isnull(IDObjet, '') + isnull(Nom_SansAccent, '') + isnull(Prenom_SansAccent, '') + isnull(Nom, '') + isnull(Prenom, '') + isnull(IDPatient, '') + isnull(NoAssuranceMaladie, '') + isnull(convert(varchar, DateNaissance), '') + isnull(Pays, '') + isnull(Province, '') + isnull(Adresse2, '') + isnull(CodePostal, '')) like '%881-1360%'
    And isnull(onlyFirst,0) = 1
Order by
    Nom, Prenom, DateRV DESC, HeureDebut ASC
</code>```

rqAfficheRechercheRV  is the view of the query above

答: Make sure you have indexes on the JOIN ON fields, foreign keys, and on fields in the WHERE clause. You can create a covering index by putting fields in the SELECT in the INCLUDE (leaf level) of the index. Look at existing indexes to make sure you are not creating overlapping indexes. Try adding the following query hints to make sure your system is not CPU bottle-necked: OPTION (MAXDOP 1, RECOMPILE), that will force a serial plan. Sometimes this will give you new index recommendations as well.</p>

Body:
I'm working with SQL Server 2012 and I have an query for the search purpose but It takes too long to execute.. (30 rows = 6sec)

I have checked up the execution plan but he doesn't suggest to put index and I don't know how i can speed up the query.

Here's my query:

SELECT
    dbo.tbRV.ID, dbo.tbRV.IDCompagnie,
    dbo.tbPatient.Nom + N', ' + dbo.tbPatient.Prenom AS NomPrenomPatient,
    dbo.tbRV.DateRV, dbo.tbRV.HeureDebut,
    dbo.tbRV.IDRessource,
    coalesce(dbo.tbRessource.Nom ,'') + ' '  + coalesce(dbo.tbRessource.Prenom,'') AS NomPrenomRessource,
    dbo.tbPatient.NoApp,
    dbo.tbPatient.NomEtablissement, dbo.tbPatient.Adresse1,
    tbAdresse.Ville, dbo.tbPatient.TelephoneDomicile,
    dbo.tbPatient.TelephoneTravail,
    dbo.tbPatient.TelephonePortable,
    case
       when DD.id is not null then DD.description
       else dbo.tbRVObjet.IDObjet
    end as idobjet,
    dbo.tbPatient.Nom_SansAccent, dbo.tbPatient.Prenom_SansAccent,
    dbo.tbPatient.Nom, dbo.tbPatient.Prenom,
    dbo.tbRV.IDPatient, dbo.tbPatient.NoAssuranceMaladie,
    dbo.tbPatient.DateNaissance, dbo.tbRV.Transit, dbo.tbRV.Annuler,
    tbAdresse.Pays, tbAdresse.Province, dbo.tbPatient.Adresse2,
    dbo.tbPatient.CodePostal,
    case
       when AA.id is not null and AA.ID = tbrvobjet.ID then 1 else 0 end as onlyFirst
FROM
    tbPatient
INNER JOIN
    tbRV ON tbPatient.ID = tbRV.IDPatient
INNER JOIN
    tbRessource ON (tbRV.IDRessource = tbRessource.ID) AND (tbRV.IDCompagnie = tbRessource.IDCompagnie)
INNER JOIN
    tbRVObjet ON tbRV.ID = tbRVObjet.IDRV
OUTER APPLY
    dbo.fn_GetFirstIDRVObjet(tbrv.id) AA
OUTER APPLY (SELECT A.ID, A.Description
             FROM tbForfaitEntete A
             WHERE A.ID = tbRVObjet.IDForfait
               AND ISNULL(tbRVObjet.IsForfaitEntete, 0) = 1 ) DD
OUTER APPLY (SELECT B.Description
             FROM tbRVObjet A
             JOIN tbForfaitEntete B ON (A.IDForfait  = B.ID AND  ISNULL(A.IsForfaitEntete, 0) = 1)
             WHERE AA.ID = A.id ) BB
OUTER APPLY (SELECT tbPaysISO.Pays, tbProvinceISO.Province, tbVilleISO.Ville
             FROM tbPaysISO
             JOIN tbProvinceISO ON (tbPaysISO.Langue = tbProvinceISO.Langue)
                                AND (tbPatient.ProvinceISOChar = tbProvinceISO.ProvinceISOChar)
             JOIN tbVilleISO ON (tbProvinceISO.Langue = tbVilleISO.Langue)
                             AND (tbPatient.IdVille  = tbVilleISO.IDVille)
             WHERE tbPaysISO.Langue = tbpatient.CodeLangue
               AND tbPaysISO.PaysISOChar3 = tbpatient.PaysISOChar3 ) tbAdresse

and here's the execution plan in XML:

EDIT:

Here's my query plan URL: https://www.brentozar.com/pastetheplan/?id=HkVYeasNW

Here's my search query :

Select
    ID, IDPatient, NomPrenomPatient, DateNaissance, NoAssuranceMaladie,
    NomEtablissement, Adresse1, Adresse2, NoApp, ville, province, pays,
    CodePostal, TelephoneDomicile, TelephoneTravail, TelephonePortable,
    DateRV, HeureDebut, IDObjet, IDRessource, NomPrenomRessource,
    Annuler, Transit
From
    rqAfficheRechercheRV
Where
    IDCompagnie = 1
    And (isnull(NomPrenomRessource, '') + isnull(NoApp, '') + isnull(NomEtablissement, '') + isnull(Adresse1, '') + isnull(Ville, '') + isnull(TelephoneDomicile, '') + isnull(TelephoneTravail, '') + isnull(TelephonePortable, '') + isnull(IDObjet, '') + isnull(Nom_SansAccent, '') + isnull(Prenom_SansAccent, '') + isnull(Nom, '') + isnull(Prenom, '') + isnull(IDPatient, '') + isnull(NoAssuranceMaladie, '') + isnull(convert(varchar, DateNaissance), '') + isnull(Pays, '') + isnull(Province, '') + isnull(Adresse2, '') + isnull(CodePostal, '')) like '%881-1360%'
    And isnull(onlyFirst,0) = 1
Order by
    Nom, Prenom, DateRV DESC, HeureDebut ASC

rqAfficheRechercheRV  is the view of the query above


答:
Just set the colorspace.

```<code>composite 03wp2.jpg -colorspace srgb  -gravity center background.jpg output.jpg
</code>```

Title: ImageMagick script takes JPG and places on canvas but changes colour of JPG

Body:
I would like to take this logo and place it on a black background.

I am using the below script

convert -size 4000x4000 canvas:#000000 -background \#000000 background.jpg
composite rev.jpg -gravity center background.jpg output.jpg
open output.jpg

Which generates. As you can see the colours have changed and I cannot work out why?

Body:
Just set the colorspace.

composite 03wp2.jpg -colorspace srgb  -gravity center background.jpg output.jpg


答:
Because you prefer to keep your code pure

i just suggest you to do not send the message in GET/POST

just send the status like

```<code>index.php?status=success
</code>```

then check the status in result file

```<code>if(isset($_GET['status']) AND $_GET['status'] == success){
   echo "bla bla";
}elseif(isset($_GET['status']) AND $_GET['status'] == fail){
   echo "bla bla";
}else{
   //do something
}
</code>```

EDIT

If you have many messages, then you can create array

```<code>$message = [
  'success' => 'success message here',
  'fail' => 'failmessage here',
  'notFound' => 'not found message'
];

$status = ( isset($_GET['status']) AND
            isset($message[$_GET['status']]) )?$_GET['status']:'notFound';

echo $message[$status];
</code>```

Title: Using php header Location to exchange messages between pages with POST

Body:
I am using already this code:

<?php
// [...]
ELSE IF(isset($_GET['msg'])){
    echo "

Good job!

".addslashes(strip_tags(trim(@$_GET[msg])))."

";
    }
//[...]
?>

Which is called from other pages if some operation goes well:

  if ($result){
      header("Location:index.php?msg=DB updated succesfully");
      exit;
  }

BUT as you may imagine, it is not clean. Working, but not the best.

Can anybody tell me if I should move it to a POST request or if this code is "widely" used to exchange status messages between pages?

And, in case of the POST, can someone write down some code or redirect me to a page where this is explained well? I searched already of course, I found THIS from mozilla, THIS with jquery and in general searching "send post php header" on google.
But I just can't understand how to do it.

Thanks a lot guys!

Body:
Because you prefer to keep your code pure

i just suggest you to do not send the message in GET/POST

just send the status like

index.php?status=success

then check the status in result file

if(isset($_GET['status']) AND $_GET['status'] == success){
   echo "bla bla";
}elseif(isset($_GET['status']) AND $_GET['status'] == fail){
   echo "bla bla";
}else{
   //do something
}

EDIT

If you have many messages, then you can create array

$message = [
  'success' => 'success message here',
  'fail' => 'failmessage here',
  'notFound' => 'not found message'
];

$status = ( isset($_GET['status']) AND
            isset($message[$_GET['status']]) )?$_GET['status']:'notFound';

echo $message[$status];


问:
Averaging and decreasing the array (vector) C++
I've got an array (actually std::vector) size ~ 7k elements.
If you draw this data, there will be a diagram of the combustion of the fuel. But I want to minimize this vector from 7k elements to 721 (every 0.5 degree) elements or ~ 1200 (every 0.3 degree). Of course I want save diagram the same. How can I do it?
Now I am getting every 9 element from big vector to new and cutting other evenly from front and back of vector to get 721 size.

```<code>QVector <double> newVMTVector;
for(QVector <double>::iterator itv = oldVmtDataVector.begin(); itv < oldVmtDataVector.end() - 9; itv+=9){
    newVMTVector.push_back(*itv);
}
auto useless = newVMTVector.size() - 721;
if(useless%2 == 0){
    newVMTVector.erase(newVMTVector.begin(), newVMTVector.begin() + useless/2);
    newVMTVector.erase(newVMTVector.end() - useless/2, newVMTVector.end());
}
else{
    newVMTVector.erase(newVMTVector.begin(), newVMTVector.begin() + useless/2+1);
    newVMTVector.erase(newVMTVector.end() - useless/2, newVMTVector.end());
}
newVMTVector.squeeze();
oldVmtDataVector.clear();
oldVmtDataVector = newVMTVector;
</code>```

I can swear there is an algorithm that averages and reduces the array.

答:
What you need is an interpolation. There are many libraries providing many types of interpolation. This one is very lightweight and easy to setup and run:

http://kluge.in-chemnitz.de/opensource/spline/

All you need to do is create the second vector that contains the X values, pass both vectors to generate spline, and generate interpolated results every 0.5 degrees or whatever:

```<code>std::vector<double> Y; // Y is your current vector of fuel combustion values with ~7k elements
std::vector<double> X;
X.reserve(Y.size());

double step_x = 360 / (double)Y.size();
for (int i = 0; i < X.size(); ++i)
    X[i] = i*step_x;

tk::spline s;
s.set_points(X, Y);
double interpolation_step = 0.5;

std::vector<double> interpolated_results;
interpolated_results.reserve(std::ceil(360/interpolation_step) + 1);
for (double i = 0.0, int j = 0; i <= 360; i += interpolation_step, ++j) // <= in order to obtain range <0;360>
    interpolated_results[j] = s(i);

if (fmod(360, interpolation_step) != 0.0) // for steps that don't divide 360 evenly, e.g. 0.7 deg, we need to close the range
    interpolated_results.back() = s(360);

// now interpolated_results contain values every 0.5 degrees
</code>```

This should give you and idea how to use this kind of libraries. If you need some other interpolation type, just find the one that suits your needs. The usage should be similar.

Body:
I've got an array (actually std::vector) size ~ 7k elements.
If you draw this data, there will be a diagram of the combustion of the fuel. But I want to minimize this vector from 7k elements to 721 (every 0.5 degree) elements or ~ 1200 (every 0.3 degree). Of course I want save diagram the same. How can I do it?
Now I am getting every 9 element from big vector to new and cutting other evenly from front and back of vector to get 721 size.

QVector <double> newVMTVector;
for(QVector <double>::iterator itv = oldVmtDataVector.begin(); itv < oldVmtDataVector.end() - 9; itv+=9){
    newVMTVector.push_back(*itv);
}
auto useless = newVMTVector.size() - 721;
if(useless%2 == 0){
    newVMTVector.erase(newVMTVector.begin(), newVMTVector.begin() + useless/2);
    newVMTVector.erase(newVMTVector.end() - useless/2, newVMTVector.end());
}
else{
    newVMTVector.erase(newVMTVector.begin(), newVMTVector.begin() + useless/2+1);
    newVMTVector.erase(newVMTVector.end() - useless/2, newVMTVector.end());
}
newVMTVector.squeeze();
oldVmtDataVector.clear();
oldVmtDataVector = newVMTVector;

I can swear there is an algorithm that averages and reduces the array.

Body:
What you need is an interpolation. There are many libraries providing many types of interpolation. This one is very lightweight and easy to setup and run:

http://kluge.in-chemnitz.de/opensource/spline/

All you need to do is create the second vector that contains the X values, pass both vectors to generate spline, and generate interpolated results every 0.5 degrees or whatever:

std::vector<double> Y; // Y is your current vector of fuel combustion values with ~7k elements
std::vector<double> X;
X.reserve(Y.size());

double step_x = 360 / (double)Y.size();
for (int i = 0; i < X.size(); ++i)
    X[i] = i*step_x;

tk::spline s;
s.set_points(X, Y);
double interpolation_step = 0.5;

std::vector<double> interpolated_results;
interpolated_results.reserve(std::ceil(360/interpolation_step) + 1);
for (double i = 0.0, int j = 0; i <= 360; i += interpolation_step, ++j) // <= in order to obtain range <0;360>
    interpolated_results[j] = s(i);

if (fmod(360, interpolation_step) != 0.0) // for steps that don't divide 360 evenly, e.g. 0.7 deg, we need to close the range
    interpolated_results.back() = s(360);

// now interpolated_results contain values every 0.5 degrees

This should give you and idea how to use this kind of libraries. If you need some other interpolation type, just find the one that suits your needs. The usage should be similar.


问:
Robot Framework How to get different timezone and locale for different country?
In robot framework, the current supported keyword to get timezone is:

```<code>${month}  Get Current Date  result_format=%B%Y
</code>```

which will return: July 2017

The question is how to get current date from other country and locale?
as example in Vietnam should return: Tháng Bảy 2017
and Thailand should return : กรกฎาคม พ.ศ. 2560

答:
Unfortunately, python doesn't have good built-in support for formatting dates in locales other than the current one. You can temporarily switch locales, but that's not a great solution.

You can use the the Babel package to format the dates, though it doesn't provide precisely the same value you expect -- the case is slightly different.

For example, you could create a keyword that dates a month, year, and locale, and returns the formatted version.

First, create a python file named CustomKeywords.py with the following contents:

```<code># CustomKeywords.py
import datetime
from babel.dates import format_date

class CustomKeywords:
    def get_date_for_locale(self, locale, year, month=1, day=1):
        d = datetime.date(int(year), int(month), int(day))
        return format_date(d, "MMMM Y", locale=locale)
</code>```

Next, import this library into your test case and then call get date for locale to get the date for a given locale:

```<code>*** Settings ***
Library  CustomKeywords.py

*** Test Case ***
Vietnamese
    ${date}=  get date for locale  vi_VN  2017  7
    Should be equal  ${date}  tháng bảy 2017

Thailand
    ${date}=  get date for locale  th_TH  2017  7
    Should be equal  ${date}  กรกฎาคม 2017
</code>```

Body:
In robot framework, the current supported keyword to get timezone is:

${month}  Get Current Date  result_format=%B%Y

which will return: July 2017

The question is how to get current date from other country and locale?
as example in Vietnam should return: Tháng Bảy 2017
and Thailand should return : กรกฎาคม พ.ศ. 2560

Body:
Unfortunately, python doesn't have good built-in support for formatting dates in locales other than the current one. You can temporarily switch locales, but that's not a great solution.

You can use the the Babel package to format the dates, though it doesn't provide precisely the same value you expect -- the case is slightly different.

For example, you could create a keyword that dates a month, year, and locale, and returns the formatted version.

First, create a python file named CustomKeywords.py with the following contents:

# CustomKeywords.py
import datetime
from babel.dates import format_date

class CustomKeywords:
    def get_date_for_locale(self, locale, year, month=1, day=1):
        d = datetime.date(int(year), int(month), int(day))
        return format_date(d, "MMMM Y", locale=locale)

Next, import this library into your test case and then call get date for locale to get the date for a given locale:

*** Settings ***
Library  CustomKeywords.py

*** Test Case ***
Vietnamese
    ${date}=  get date for locale  vi_VN  2017  7
    Should be equal  ${date}  tháng bảy 2017

Thailand
    ${date}=  get date for locale  th_TH  2017  7
    Should be equal  ${date}  กรกฎาคม 2017


问:
Custom discounts in Commerce Server !
I have to create some custom promotion Discounts which does not fall in the category of DiscountTypes provided out of box from Commerce Server. Is there a way for creating your own Custom Discounts like custom Pipeline Components. Any ideas are helpful.

Thanks!

答: Yes.... You can create a custom pipeline component to override default pricing and discount business logic, you have just to pay attention where to add the custom component in the basket pipeline...</p>

Title: Custom discounts in Commerce Server !


问:
Change foreground of a textblock in a ToggleButton
I'm new to WPF and I'm totaly stuck with a foreground who don't want to update :@

I wan't to make a radiobutton with a togglebutton behavior (that's ok), but i want to wrap the text inside this button.

If the content is defined in the toggleButton, my foreground become white. But if i use a Textblock inside the togglebutton (with a wrap), my foreground don't want to change.

My two buttons in XAML

```<code>        <RadioButton GroupName="line1" Grid.Row="1" Grid.Column="1" Style="{DynamicResource ToggleButtonStyle1}">
        <RadioButton.Content>
            <TextBlock TextWrapping="Wrap" >I can wrap but ...</TextBlock>
        </RadioButton.Content>
    </RadioButton>

    <RadioButton GroupName="line0" Grid.Row="1" Grid.Column="2" Style="{DynamicResource ToggleButtonStyle1}" Content="i can't Wrap and it's not good"/>
</code>```

And my ControlTemplate in app.xaml

```<code> <ControlTemplate TargetType="{x:Type ToggleButton}">
    <Border x:Name="border" BorderThickness="1" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
        <Border.BorderBrush>
            <SolidColorBrush Color="{DynamicResource BleuClair}"/>
        </Border.BorderBrush>
        <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="Button.IsDefaulted" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        </Trigger>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsChecked"  Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
</code>```

I'm not sure if i need to update the ControlTemplate or the ContentPresenter to add "Something" about the textblock or if i need to update the XAML to make a binding to this custom style.

Thank you for your time :)

答:
It sounds like what you're looking for is an event that will toggle the foreground color when clicked. Try setting up your XAML like this:

```<code><RadioButton Click="RadioButton_Clicked" GroupName="line1" Grid.Row="1" Grid.Column="1" Style="{DynamicResource ToggleButtonStyle1}">
     <TextBlock TextWrapping="Wrap" >Text here</TextBlock>
</RadioButton>
</code>```

Now in your code, handle the event with a method

```<code>private void RadioButton_Clicked(object sender, RoutedEventArgs e)
{
    // get an object of the button
    RadioButton button = (RadioButton)sender;

    // access the textblock to change the foreground
    TextBlock text = (TextBlock)button.Child;

    // change the foreground to white
    text.Foreground = Brushes.White;
}
</code>```

Hopefully this helps or is close to what you are looking for!

Body:
I'm new to WPF and I'm totaly stuck with a foreground who don't want to update :@

I wan't to make a radiobutton with a togglebutton behavior (that's ok), but i want to wrap the text inside this button.

If the content is defined in the toggleButton, my foreground become white. But if i use a Textblock inside the togglebutton (with a wrap), my foreground don't want to change.

My two buttons in XAML

        <RadioButton GroupName="line1" Grid.Row="1" Grid.Column="1" Style="{DynamicResource ToggleButtonStyle1}">
        <RadioButton.Content>
            <TextBlock TextWrapping="Wrap" >I can wrap but ...</TextBlock>
        </RadioButton.Content>
    </RadioButton>

    <RadioButton GroupName="line0" Grid.Row="1" Grid.Column="2" Style="{DynamicResource ToggleButtonStyle1}" Content="i can't Wrap and it's not good"/>

And my ControlTemplate in app.xaml

 <ControlTemplate TargetType="{x:Type ToggleButton}">
    <Border x:Name="border" BorderThickness="1" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
        <Border.BorderBrush>
            <SolidColorBrush Color="{DynamicResource BleuClair}"/>
        </Border.BorderBrush>
        <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="Button.IsDefaulted" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        </Trigger>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsChecked"  Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

I'm not sure if i need to update the ControlTemplate or the ContentPresenter to add "Something" about the textblock or if i need to update the XAML to make a binding to this custom style.

Thank you for your time :)

Body:
It sounds like what you're looking for is an event that will toggle the foreground color when clicked. Try setting up your XAML like this:

<RadioButton Click="RadioButton_Clicked" GroupName="line1" Grid.Row="1" Grid.Column="1" Style="{DynamicResource ToggleButtonStyle1}">
     <TextBlock TextWrapping="Wrap" >Text here</TextBlock>
</RadioButton>

Now in your code, handle the event with a method

private void RadioButton_Clicked(object sender, RoutedEventArgs e)
{
    // get an object of the button
    RadioButton button = (RadioButton)sender;

    // access the textblock to change the foreground
    TextBlock text = (TextBlock)button.Child;

    // change the foreground to white
    text.Foreground = Brushes.White;
}

Hopefully this helps or is close to what you are looking for!


问:
php - Google Analytics Measurement Protocol POST request
I have issue when sending POST request from my server to google analytics.

I'm trying to send test (event,order etc.), but then I do not receive anything and when I look to events tracker in browser there is absolutely nothing happening...

PHP code

```<code>$x  =   [
            'v'=>'1',
            't'=>'event',
            'tid'=>'.....',    // here goes my tracking ID
            'cid'=>'555',
            'ec'=>'video'
        ];

echo(google_a($x));

function google_a($x)                           {
    $x  = http_build_query($x);
    $ch = curl_init();
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    curl_setopt($ch,CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_URL,"https://www.google-analytics.com/collect");
    curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
    curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
    curl_setopt($ch,CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$x);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec ($ch);

    curl_close ($ch);
    return($server_output);
}
</code>```

I think that my CURL configuration isn't good. Can you help me with this?

答:
What is the response from google? $server_output

Do this:

```<code>echo "```"
print_r( $server_output )
```

And put here que feedback

Body:
I have issue when sending POST request from my server to google analytics.

I'm trying to send test (event,order etc.), but then I do not receive anything and when I look to events tracker in browser there is absolutely nothing happening...

PHP code

$x  =   [
            'v'=>'1',
            't'=>'event',
            'tid'=>'.....',    // here goes my tracking ID
            'cid'=>'555',
            'ec'=>'video'
        ];

echo(google_a($x));

function google_a($x)                           {
    $x  = http_build_query($x);
    $ch = curl_init();
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    curl_setopt($ch,CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_URL,"https://www.google-analytics.com/collect");
    curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
    curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
    curl_setopt($ch,CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$x);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec ($ch);

    curl_close ($ch);
    return($server_output);
}

I think that my CURL configuration isn't good. Can you help me with this?

Body:
What is the response from google? $server_output

Do this:

echo "<pre>"
print_r( $server_output )

And put here que feedback


答:
```<code>bool found = false;
foreach (string s in MasterList)
{
    if(s == YourName)
    found = true;
}
if(found)
    Console.WriteLine("Your name is among the list");
else
    Console.WriteLine("Your name is not among the list");
</code>```

Title: How do I compare the value of string array?

Body:
I have declared a string array and I want to compare with name given by user,

string[] MasterList = new string[] {
  "Askay", "Puram", "Raman", "Srinivasa",
  "Gopal", "Rajesh", "Anju", "Nagara",
};

string YourName;
Console.WriteLine("Enter your name: ");
YourName = Console.ReadLine();

for(i=0; i<5; i++)
{
    a = String.Compare(MasterList[i], YourName);
    Console.WriteLine("Your name is not among the list")
}

The resulting output is not what I am expecting, any ideas how I can go about it?


问:
Error on Display Estimated Execution Plan with window function
I just wanted to have a look how the execution plan of a query changes, when i add window functions like LAG().

But, when i add a window function to my query like LAG() & click on "Display Estimated Execution Plan" it returns me following error.

```<code>An error occurred while executing batch. Error message is: Error processing execution plan results. The error message is:
There is an error in XML document (1, 12308).
Instance validation error: 'Window Spool' is not a valid value for PhysicalOpType.
</code>```

SQL Server:

```<code>Microsoft SQL Server 2016 (SP1) (KB3182545)
13.0.4001.0 (X64)   Oct 28 2016 18:17:30
Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit)
on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)
</code>```

I never experienced this behavior before. Any ideas why the execution plan can't be estimated?

答:
Solution:

Version of Microsoft SQL Server Management Studio is older than Microsoft SQL Server itself.

In my case:

Microsoft SQL Server Management Studio Version 10.50.1600.1 (for SQL Server 2008 R2)

Microsoft SQL Server 2016

As windowed functions like LAG() have been released with SQL Server 2012, the older Management Studio version is not able to interpret/display the execution plan with windowed functions.

Body:
I just wanted to have a look how the execution plan of a query changes, when i add window functions like LAG().

But, when i add a window function to my query like LAG() & click on "Display Estimated Execution Plan" it returns me following error.

An error occurred while executing batch. Error message is: Error processing execution plan results. The error message is:
There is an error in XML document (1, 12308).
Instance validation error: 'Window Spool' is not a valid value for PhysicalOpType.

SQL Server:

Microsoft SQL Server 2016 (SP1) (KB3182545)
13.0.4001.0 (X64)   Oct 28 2016 18:17:30
Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit)
on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)

I never experienced this behavior before. Any ideas why the execution plan can't be estimated?


问:
How to add nextset of fragments without disturbing current fragments in FragmentPagerAdapter?
Here's the code to add the fragments for first time`

`if(mcursor==null) {
            items = (ArrayList) cnews.getItems();
            mcursor = cnews.getNextPageToken();

```<code>        for (int i = 0; i < items.size(); i++) {

            Fragment cm = ContentFragment.newInstance(i, items.get(i).getTitle(),
                    items.get(i).getImageuri(), items.get(i).getDate(), items.get(i).getPublsher(), items.get(i).getDescription());
            frags.add(cm);

        }
        viewPager.setAdapter(new ContentfragmentAdapter(getSupportFragmentManager(), frags));

    }else{
        items = (ArrayList<News>) cnews.getItems();
        mcursor = cnews.getNextPageToken();
        for (int i = 0; i < items.size(); i++) {

            Fragment cm = ContentFragment.newInstance(i, items.get(i).getTitle(),
                    items.get(i).getImageuri(), items.get(i).getDate(), items.get(i).getPublsher(), items.get(i).getDescription());
            frags.add(cm);

        }
</code>```

In else condition i want to add some more fragments after server call.How can i update the adapter without removing old fragments?

Please help me i am newbie in android development.
Thanks in Adavance.

答:
One of the crucial parts here is that you must call

```<code>notifyDataSetChanged()
</code>```

on the adapter so that the underlying data structures are updated accordingly
including triggering a redraw of the ViewPager.
Also don't forget that getCount() must also return the expected number of elements (ie. no hardcoding values here)

```<code>public class SectionsPagerAdapter extends FragmentPagerAdapter {

    List<String> tagList;

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
        tagList = new ArrayList<>();

    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.

        return PlaceholderFragment.newInstance(tagList.get(position));
    }

    @Override
    public int getCount() {

        return tagList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {

        return "SECTION "+(position+1);
    }

    public void add(int position, String key)
    {
        tagList.add(position, key);
        notifyDataSetChanged();
    }

}
</code>```

Body:
Here's the code to add the fragments for first time`

`if(mcursor==null) {
            items = (ArrayList) cnews.getItems();
            mcursor = cnews.getNextPageToken();

        for (int i = 0; i < items.size(); i++) {

            Fragment cm = ContentFragment.newInstance(i, items.get(i).getTitle(),
                    items.get(i).getImageuri(), items.get(i).getDate(), items.get(i).getPublsher(), items.get(i).getDescription());
            frags.add(cm);

        }
        viewPager.setAdapter(new ContentfragmentAdapter(getSupportFragmentManager(), frags));

    }else{
        items = (ArrayList<News>) cnews.getItems();
        mcursor = cnews.getNextPageToken();
        for (int i = 0; i < items.size(); i++) {

            Fragment cm = ContentFragment.newInstance(i, items.get(i).getTitle(),
                    items.get(i).getImageuri(), items.get(i).getDate(), items.get(i).getPublsher(), items.get(i).getDescription());
            frags.add(cm);

        }

In else condition i want to add some more fragments after server call.How can i update the adapter without removing old fragments?

Please help me i am newbie in android development.
Thanks in Adavance.

Body:
One of the crucial parts here is that you must call

notifyDataSetChanged()

on the adapter so that the underlying data structures are updated accordingly
including triggering a redraw of the ViewPager.
Also don't forget that getCount() must also return the expected number of elements (ie. no hardcoding values here)

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    List<String> tagList;

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
        tagList = new ArrayList<>();

    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.

        return PlaceholderFragment.newInstance(tagList.get(position));
    }

    @Override
    public int getCount() {

        return tagList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {

        return "SECTION "+(position+1);
    }

    public void add(int position, String key)
    {
        tagList.add(position, key);
        notifyDataSetChanged();
    }

}


问:
Combine --user with --prefix error with setup.py install
I was trying to install Python packages a system I recently gained access to. I was trying to take advantage of Python's relatively new per user site-packages directory, and the new option --user. (The option is currently undocumented, however it exists for Python 2.6+; you can see the help by running python setup.py install --help.)

When I tried running

```<code>python setup.py install --user
</code>```

on any package I downloaded, I always got the following error:

```<code>error: can't combine user with with prefix/exec_prefix/home or install_(plat)base
</code>```

The error was extremely perplexing because, as you can see, I wasn't providing the --prefix, --exec-prefix, --install-base, or --install-platbase flags as command line options. I wasted a lot of time trying to figure out what the problem was. I document my answer below, in hopes to spare some other poor soul a few hours of yak shaving.

答:
One time workaround:

```<code>pip install --user --install-option="--prefix=" <package_name>
</code>```

or

```<code>python setup.py install --user --prefix=
</code>```

Note that there is no text (not even whitespace) after the =.

Do not forget the --user flag.

Installing multiple packages:

Create ~/.pydistutils.cfg (or equivalent for your OS/platform) with the following contents:

```<code>[install]
prefix=
</code>```

Note that there is no text (not even whitespace) after the =.

Then run the necessary pip install --user or python setup.py install --user commands. Do not forget the --user flag.

Finally, remove or rename this file. Leaving this file present will cause issues when installing Python packages system-wide (i.e., without --user) as this user with this ~/.pydistutils.cfg.

The cause of this issue

This appears to be an issue with both OpenSUSE and RedHat, which has lead to a bug in virtualenv on these platforms.

The error stems from a system-level distutils configuration file (in my case /usr/lib64/python2.6/distutils/distutils.cfg) where there was this

```<code>[install]
prefix=/usr/local
</code>```

Basically, this is equivalent to always running the install command as install --prefix=/usr/local. You have to override this specification using one of the techniques above.

Body:
I was trying to install Python packages a system I recently gained access to. I was trying to take advantage of Python's relatively new per user site-packages directory, and the new option --user. (The option is currently undocumented, however it exists for Python 2.6+; you can see the help by running python setup.py install --help.)

When I tried running

python setup.py install --user

on any package I downloaded, I always got the following error:

error: can't combine user with with prefix/exec_prefix/home or install_(plat)base

The error was extremely perplexing because, as you can see, I wasn't providing the --prefix, --exec-prefix, --install-base, or --install-platbase flags as command line options. I wasted a lot of time trying to figure out what the problem was. I document my answer below, in hopes to spare some other poor soul a few hours of yak shaving.

Body:
One time workaround:

pip install --user --install-option="--prefix=" <package_name>

or

python setup.py install --user --prefix=

Note that there is no text (not even whitespace) after the =.

Do not forget the --user flag.

Installing multiple packages:

Create ~/.pydistutils.cfg (or equivalent for your OS/platform) with the following contents:

[install]
prefix=

Note that there is no text (not even whitespace) after the =.

Then run the necessary pip install --user or python setup.py install --user commands. Do not forget the --user flag.

Finally, remove or rename this file. Leaving this file present will cause issues when installing Python packages system-wide (i.e., without --user) as this user with this ~/.pydistutils.cfg.

The cause of this issue

This appears to be an issue with both OpenSUSE and RedHat, which has lead to a bug in virtualenv on these platforms.

The error stems from a system-level distutils configuration file (in my case /usr/lib64/python2.6/distutils/distutils.cfg) where there was this

[install]
prefix=/usr/local

Basically, this is equivalent to always running the install command as install --prefix=/usr/local. You have to override this specification using one of the techniques above.


问:
Define global vector using eigen library in c++
I am writing a parallel program using pthreads and eigen library.
My program looks something like this:

```<code>#include <Eigen/...>
#include <pthread.h>
...

typedef Eigen::SparseMatrix<long double> matrizLD;
matrizLD mat;
typedef Eigen::Matrix<long double, Dynamic, 1> VectorLD;
VectorLD v1;
VectorLD v2;

void *power_method(int rank){
    ...
    int from = from_array[rank]
    int length = length_array[rank]
    v1.segment(from,length) = mat.block(from,0,length,size)*v2; //something like this
}

int main(...){
    size = ...; //an input parameter
    matrizLD mat(size,size) = ...;
    VectorLD v1(size) = ...;
    VectorLD v2(size) = ...;
    ...
    pthread_create(..., power_method, ...);
    ...
}
</code>```

I basically need the vectors and the matrix to be global variables to be able to access them in the function.
The program compiles but when I execute it I get the following error:

Assertion failed: (startRow >= 0 && blockRows >= 0 && startRow <= xpr.rows() - blockRows && startCol >= 0 && blockCols >= 0 && startCol <= xpr.cols() - blockCols), function Block, file ...

At first I thought I was trying to access an illegal part of the vector but I then changed the "power_method" function for:

```<code>void *power_method(int rank){
    v1(0); // I can do this from main with no problem
}
</code>```

and I still get the same error.
My guess is that the way that I'm defining the vector and the matrix is incorrect, but I couldn't find anything that says what is the correct way.

答:
You have two v1 variables:

```<code>VectorLD v1; //global

void *power_method(int rank){
    v1.segment(from,length) = mat.block(from,0,length,size)*v2; //something like this
}

int main(...){
    size = ...; //an input parameter
    VectorLD v1(size) = ...; //oops another one
}
</code>```

Your main needs to initialise the global variable. I presume something like

```<code>int main(...){
    size = ...; //an input parameter
    v1 = VectorLD(size);// global one
}
</code>```

Body:
I am writing a parallel program using pthreads and eigen library.
My program looks something like this:

#include <Eigen/...>
#include <pthread.h>
...

typedef Eigen::SparseMatrix<long double> matrizLD;
matrizLD mat;
typedef Eigen::Matrix<long double, Dynamic, 1> VectorLD;
VectorLD v1;
VectorLD v2;

void *power_method(int rank){
    ...
    int from = from_array[rank]
    int length = length_array[rank]
    v1.segment(from,length) = mat.block(from,0,length,size)*v2; //something like this
}

int main(...){
    size = ...; //an input parameter
    matrizLD mat(size,size) = ...;
    VectorLD v1(size) = ...;
    VectorLD v2(size) = ...;
    ...
    pthread_create(..., power_method, ...);
    ...
}

I basically need the vectors and the matrix to be global variables to be able to access them in the function.
The program compiles but when I execute it I get the following error:

Assertion failed: (startRow >= 0 && blockRows >= 0 && startRow <= xpr.rows() - blockRows && startCol >= 0 && blockCols >= 0 && startCol <= xpr.cols() - blockCols), function Block, file ...

At first I thought I was trying to access an illegal part of the vector but I then changed the "power_method" function for:

void *power_method(int rank){
    v1(0); // I can do this from main with no problem
}

and I still get the same error.
My guess is that the way that I'm defining the vector and the matrix is incorrect, but I couldn't find anything that says what is the correct way.

Body:
You have two v1 variables:

VectorLD v1; //global

void *power_method(int rank){
    v1.segment(from,length) = mat.block(from,0,length,size)*v2; //something like this
}

int main(...){
    size = ...; //an input parameter
    VectorLD v1(size) = ...; //oops another one
}

Your main needs to initialise the global variable. I presume something like

int main(...){
    size = ...; //an input parameter
    v1 = VectorLD(size);// global one
}


问:
Error installing IBM Rational Software Architect for MacOs
I'm able to successfully install RSA 9.6 on my MacBook, but when I try to start the application I get the following error written out into my log.  Any help would be gratefully welcomed</p>

```<code>!SESSION Fri Jun 30 08:21:28 CDT 2017 ------------------------------------------
!ENTRY org.eclipse.equinox.launcher 4 0 2017-06-30 08:21:28.394
!MESSAGE Could not find extension: com.ibm.cds
!SESSION 2017-06-30 08:21:28.353 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.7.0_51
java.vendor=Oracle Corporation
BootLoader constants: OS=macosx, ARCH=x86_64, WS=cocoa, NL=en_US
Framework arguments:  -product com.ibm.rational.rsa.product.v90.ide
Command-line arguments:  -os macosx -ws cocoa -arch x86_64 -clean -product com.ibm.rational.rsa.product.v90.ide

!ENTRY org.eclipse.osgi 4 0 2017-06-30 08:21:29.088
!MESSAGE Bundle com.ibm.cds not found.

!ENTRY org.eclipse.equinox.app 0 0 2017-06-30 08:21:29.379
!MESSAGE Product com.ibm.rational.rsa.product.v90.ide could not be found.

!ENTRY org.eclipse.osgi 4 0 2017-06-30 08:21:36.198
!MESSAGE Application error
!STACK 1
java.lang.RuntimeException: No application id has been found.
at org.eclipse.equinox.internal.app.EclipseAppContainer.startDefaultApp(EclipseAppContainer.java:242)
at org.eclipse.equinox.internal.app.MainApplicationLauncher.run(MainApplicationLauncher.java:29)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
</code>```

答:
I found this on https://www.ibm.com/developerworks/community/forums/html/topic?id=9ed43812-9c67-4fd5-921b-f7acb405e12b.  The short answer is edit the following file:

/Applications/IBM/SoftwareDeliveryPlatform/RSA.app/Contents/MacOS/ExecuteScript

And change the one line to specify v9.6 instead of 9.5.  I tried an earlier version of RSA (9.1) and it had a similar problem of pointing to 9.0.  Really sad because this is a very powerful tool.

Change $ECLIPSE_APP -product com.ibm.rational.rsa.product.v95.ide &
to $ECLIPSE_APP -product com.ibm.rational.rsa.product.v96.ide &

https://www.ibm.com/developerworks/community/forums/html/topic?id=9ed43812-9c67-4fd5-921b-f7acb405e12b

Body:
I'm able to successfully install RSA 9.6 on my MacBook, but when I try to start the application I get the following error written out into my log.  Any help would be gratefully welcomed

!SESSION Fri Jun 30 08:21:28 CDT 2017 ------------------------------------------
!ENTRY org.eclipse.equinox.launcher 4 0 2017-06-30 08:21:28.394
!MESSAGE Could not find extension: com.ibm.cds
!SESSION 2017-06-30 08:21:28.353 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.7.0_51
java.vendor=Oracle Corporation
BootLoader constants: OS=macosx, ARCH=x86_64, WS=cocoa, NL=en_US
Framework arguments:  -product com.ibm.rational.rsa.product.v90.ide
Command-line arguments:  -os macosx -ws cocoa -arch x86_64 -clean -product com.ibm.rational.rsa.product.v90.ide

!ENTRY org.eclipse.osgi 4 0 2017-06-30 08:21:29.088
!MESSAGE Bundle com.ibm.cds not found.

!ENTRY org.eclipse.equinox.app 0 0 2017-06-30 08:21:29.379
!MESSAGE Product com.ibm.rational.rsa.product.v90.ide could not be found.

!ENTRY org.eclipse.osgi 4 0 2017-06-30 08:21:36.198
!MESSAGE Application error
!STACK 1
java.lang.RuntimeException: No application id has been found.
at org.eclipse.equinox.internal.app.EclipseAppContainer.startDefaultApp(EclipseAppContainer.java:242)
at org.eclipse.equinox.internal.app.MainApplicationLauncher.run(MainApplicationLauncher.java:29)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)