问:
How to use jQuery to call asp.net asmx web service with parameters to get response
I have written a simple ASMX web service with a method to get some value from the database. My service code is:

```<code>[WebMethod]
public string GetProductStock(string productId, string TerminalId, string CCPId)
{
    ProductsDomain objProduct = new ProductsDomain();
    objProduct.Product_Id = Convert.ToInt32(productId);
    objProduct.TerminalId = Convert.ToInt32(TerminalId);
    objProduct.CCPId = Convert.ToInt32(CCPId);
    DataTable dt = objProduct.GetProductDetail();
    if (dt.Rows.Count > 0)
    {
         return dt.Rows[0]["CurrentQty"].ToString();
    }
    else
    {
        return "0";
    }
}
</code>```

and this is my jquery function:

```<code>function checkStock() {
            var txt_PId = $("#content_body_content_lPId").text();
            var txt_TerminalId = $("#content_body_content_lTerminalId").text();
            var txt_CCPId = $("#content_body_content_lCCPId").text();
            var msg = "{" + String.format("'productId':'{0}', 'TerminalId':'{1}','CCPId':'{2}'", txt_PId, txt_TerminalId, txt_CCPId) + "}"
           // alert(msg);
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "CService.asmx/GetProductStock",
                data: msg,
                dataType: "json",
                success: function (Result) {
                    alert();
                    Result = Result.d;
                   // data = Result
                    //alert(data)
                },
                error: function (Result) {
                    debugger;
                    alert("Error: " + Result.error.toString());
                    return false;
                }
            });
            return false;
        }
</code>```

this jquery method is returning error, and when i debugged the error, error status code is 500.
Error message:

Error: function (){if(h){var d=h.length;!function
  f(b){n.each(b,function(b,c){var
  d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return
  this}

Any one can suggest me a solution to this?

答:
[System.Web.Script.Services.ScriptService] have to be enabled on the class inheriting System.Web.Services.WebService to access its methods via ajax

WebService

```<code>    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class WebServiceFile : System.Web.Services.WebService
    {

        [WebMethod]
        //[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public  string GetProductStock(string productId, string TerminalId, string CCPId)
        {
            ProductsDomain objProduct = new ProductsDomain();
            objProduct.Product_Id = Convert.ToInt32(productId);
            objProduct.TerminalId = Convert.ToInt32(TerminalId);
            objProduct.CCPId = Convert.ToInt32(CCPId);
            DataTable dt = objProduct.GetProductDetail();
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["CurrentQty"].ToString();
            }
            else
            {
                return "0";
            }
        }

        public class ProductsDomain
        {
            public int Product_Id { get; set; }
            public int TerminalId { get; set; }
            public int CCPId { get; set; }
            public DataTable GetProductDetail()
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("CurrentQty");
                DataRow dr = dt.NewRow();
                dr["CurrentQty"] = "Smith";
                dt.Rows.Add(dr);
                DataRow dr1 = dt.NewRow();
                dr1["CurrentQty"] = "John";
                dt.Rows.Add(dr1);
                return dt;

            }
        }

    }
</code>```

Jquery

```<code>function checkStock() {
            var txt_PId = 1;
            var txt_TerminalId = 2;
            var txt_CCPId = 3;
            var msg = '{productId:"' + txt_PId + '",TerminalId:"' + txt_TerminalId + '",CCPId:"' + txt_CCPId + '"}';
            debugger;
            $.ajax({
                type: "POST",
                cache: false,
                contentType: "application/json; charset=utf-8",
                url: "/WebServiceFile.asmx/GetProductStock",
                data: msg,
                dataType: "json",
                success: function (Result) {
                    alert();
                    Result = Result.d;
                    // data = Result
                    alert(Result)
                },
                error: function (Result) {
                    debugger;
                    alert("Error: " + Result.error.toString());
                    return false;
                }
            });
        }
</code>```

Body:
I have written a simple ASMX web service with a method to get some value from the database. My service code is:

[WebMethod]
public string GetProductStock(string productId, string TerminalId, string CCPId)
{
    ProductsDomain objProduct = new ProductsDomain();
    objProduct.Product_Id = Convert.ToInt32(productId);
    objProduct.TerminalId = Convert.ToInt32(TerminalId);
    objProduct.CCPId = Convert.ToInt32(CCPId);
    DataTable dt = objProduct.GetProductDetail();
    if (dt.Rows.Count > 0)
    {
         return dt.Rows[0]["CurrentQty"].ToString();
    }
    else
    {
        return "0";
    }
}

and this is my jquery function:

function checkStock() {
            var txt_PId = $("#content_body_content_lPId").text();
            var txt_TerminalId = $("#content_body_content_lTerminalId").text();
            var txt_CCPId = $("#content_body_content_lCCPId").text();
            var msg = "{" + String.format("'productId':'{0}', 'TerminalId':'{1}','CCPId':'{2}'", txt_PId, txt_TerminalId, txt_CCPId) + "}"
           // alert(msg);
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "CService.asmx/GetProductStock",
                data: msg,
                dataType: "json",
                success: function (Result) {
                    alert();
                    Result = Result.d;
                   // data = Result
                    //alert(data)
                },
                error: function (Result) {
                    debugger;
                    alert("Error: " + Result.error.toString());
                    return false;
                }
            });
            return false;
        }

this jquery method is returning error, and when i debugged the error, error status code is 500.
Error message:

Error: function (){if(h){var d=h.length;!function
  f(b){n.each(b,function(b,c){var
  d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return
  this}

Any one can suggest me a solution to this?

Body:
[System.Web.Script.Services.ScriptService] have to be enabled on the class inheriting System.Web.Services.WebService to access its methods via ajax

WebService

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class WebServiceFile : System.Web.Services.WebService
    {

        [WebMethod]
        //[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public  string GetProductStock(string productId, string TerminalId, string CCPId)
        {
            ProductsDomain objProduct = new ProductsDomain();
            objProduct.Product_Id = Convert.ToInt32(productId);
            objProduct.TerminalId = Convert.ToInt32(TerminalId);
            objProduct.CCPId = Convert.ToInt32(CCPId);
            DataTable dt = objProduct.GetProductDetail();
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["CurrentQty"].ToString();
            }
            else
            {
                return "0";
            }
        }

        public class ProductsDomain
        {
            public int Product_Id { get; set; }
            public int TerminalId { get; set; }
            public int CCPId { get; set; }
            public DataTable GetProductDetail()
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("CurrentQty");
                DataRow dr = dt.NewRow();
                dr["CurrentQty"] = "Smith";
                dt.Rows.Add(dr);
                DataRow dr1 = dt.NewRow();
                dr1["CurrentQty"] = "John";
                dt.Rows.Add(dr1);
                return dt;

            }
        }

    }

Jquery

function checkStock() {
            var txt_PId = 1;
            var txt_TerminalId = 2;
            var txt_CCPId = 3;
            var msg = '{productId:"' + txt_PId + '",TerminalId:"' + txt_TerminalId + '",CCPId:"' + txt_CCPId + '"}';
            debugger;
            $.ajax({
                type: "POST",
                cache: false,
                contentType: "application/json; charset=utf-8",
                url: "/WebServiceFile.asmx/GetProductStock",
                data: msg,
                dataType: "json",
                success: function (Result) {
                    alert();
                    Result = Result.d;
                    // data = Result
                    alert(Result)
                },
                error: function (Result) {
                    debugger;
                    alert("Error: " + Result.error.toString());
                    return false;
                }
            });
        }


来源: stackexchange

问:
How to use goto across multiple functions
I am trying to exit a program without using exit(). I have come up with a very convoluted and dirty solution (I am a Beginner).
I would like to use if statements and if it is true, then I would like to use goto to go the main function and then return 3; and end the program.

Here is a bit of code:

```<code>    FILE *filepointer;

      char * line = NULL;
      size_t len = 0;
      size_t read;
      int linecount = 0;
      filepointer = fopen(filename, "r");
      if (filepointer == NULL)
        {
          printf("[ERR] Could not read file %s.\n",filename );
          goto FILE_ERROR;
        }
    ...
    int main(){
    ...
    FILE_ERROR: return 3;

}
</code>```

This however does not work as I cannot get jump between functions because I get undeclared Label as an error. Is there any way I can exclude exit() from my program and still end it returning a certain value. If there is a better solution, please let me know

答:
goto can't be used to jump across different functions; it can only be used within the same function. To jump between functions, you can look at setjmp() and longjmp() functions.

Having said, since you claim to be a beginner, I am not convinced you really need to use either of the above. You can simply modify your function to return an "error" value. And in main(), check its value and return from main() with the error value.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to exit a program without using exit(). I have come up with a very convoluted and dirty solution (I am a Beginner).
I would like to use if statements and if it is true, then I would like to use goto to go the main function and then return 3; and end the program.

Here is a bit of code:

    FILE *filepointer;

      char * line = NULL;
      size_t len = 0;
      size_t read;
      int linecount = 0;
      filepointer = fopen(filename, "r");
      if (filepointer == NULL)
        {
          printf("[ERR] Could not read file %s.\n",filename );
          goto FILE_ERROR;
        }
    ...
    int main(){
    ...
    FILE_ERROR: return 3;

}

This however does not work as I cannot get jump between functions because I get undeclared Label as an error. Is there any way I can exclude exit() from my program and still end it returning a certain value. If there is a better solution, please let me know


问:
MFMailComposeViewControllerDelegate not working Swift 3
I have been using the mail composer in a few of my apps for awhile now and as of recent the mailComposeDelegate no longer gets call.
I wasn't sure if this was something to do with the new release of Swift.
 So, I thought I would ask and see if anyone else is having similar issues.
I can present the mail composer but it never gets dismissed due to the delegate not working.

Below is an exact copy of the code I have been using:

```<code>func launchFeedback() {
    guard MFMailComposeViewController.canSendMail() else {
        return
    }

    let emailTitle = "Feedback"
    let messageBody = ""
    let toRecipents = ["johnappleseed@icloud.com"]
    mailComposer.mailComposeDelegate = self
    mailComposer.setSubject(emailTitle)
    mailComposer.setMessageBody(messageBody, isHTML: false)
    mailComposer.setToRecipients(toRecipents)
    self.show(mailComposer, sender: self)
}

func mailComposeController(controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    print(error)
    controller.dismiss(animated: true, completion: nil)
}
</code>```

答:
Swift 4, Xcode 9.1.
My issue was that MFMailComposeViewController was working fine but if you click cancel, dismiss, and then trying to open it one more time both cancel and send button will not fire didFinishWith delegate function.
It was happening because I've declared MFMailComposeViewController as lazy variable and solution was to create new instance of MFMailComposeViewController every time you want to open it.

Problem:

```<code>lazy var mailComposeViewController: MFMailComposeViewController = {
    let mailComposeViewController = MFMailComposeViewController()
    mailComposeViewController.mailComposeDelegate = self
    mailComposeViewController.setToRecipients(["example@test.test"])
    mailComposeViewController.setSubject("subject")
    mailComposeViewController.setMessageBody("test body", isHTML: false)
    return mailComposeViewController
}()
</code>```

Solution:

```<code>func createMailComposeViewController() -> MFMailComposeViewController {
    let mailComposeViewController = MFMailComposeViewController()
    mailComposeViewController.mailComposeDelegate = self
    mailComposeViewController.setToRecipients(["example@test.test"])
    mailComposeViewController.setSubject("subject")
    mailComposeViewController.setMessageBody("test body", isHTML: false)
    return mailComposeViewController
}
</code>```

Body:
I have been using the mail composer in a few of my apps for awhile now and as of recent the mailComposeDelegate no longer gets call.
I wasn't sure if this was something to do with the new release of Swift.
 So, I thought I would ask and see if anyone else is having similar issues.
I can present the mail composer but it never gets dismissed due to the delegate not working.

Below is an exact copy of the code I have been using:

func launchFeedback() {
    guard MFMailComposeViewController.canSendMail() else {
        return
    }

    let emailTitle = "Feedback"
    let messageBody = ""
    let toRecipents = ["johnappleseed@icloud.com"]
    mailComposer.mailComposeDelegate = self
    mailComposer.setSubject(emailTitle)
    mailComposer.setMessageBody(messageBody, isHTML: false)
    mailComposer.setToRecipients(toRecipents)
    self.show(mailComposer, sender: self)
}

func mailComposeController(controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    print(error)
    controller.dismiss(animated: true, completion: nil)
}

Body:
Swift 4, Xcode 9.1.
My issue was that MFMailComposeViewController was working fine but if you click cancel, dismiss, and then trying to open it one more time both cancel and send button will not fire didFinishWith delegate function.
It was happening because I've declared MFMailComposeViewController as lazy variable and solution was to create new instance of MFMailComposeViewController every time you want to open it.

Problem:

lazy var mailComposeViewController: MFMailComposeViewController = {
    let mailComposeViewController = MFMailComposeViewController()
    mailComposeViewController.mailComposeDelegate = self
    mailComposeViewController.setToRecipients(["example@test.test"])
    mailComposeViewController.setSubject("subject")
    mailComposeViewController.setMessageBody("test body", isHTML: false)
    return mailComposeViewController
}()

Solution:

func createMailComposeViewController() -> MFMailComposeViewController {
    let mailComposeViewController = MFMailComposeViewController()
    mailComposeViewController.mailComposeDelegate = self
    mailComposeViewController.setToRecipients(["example@test.test"])
    mailComposeViewController.setSubject("subject")
    mailComposeViewController.setMessageBody("test body", isHTML: false)
    return mailComposeViewController
}


问:
How to find the type of an object in Go?
How do I find the type of an object in Go? In Python, I just use typeof to fetch the type of object. Similarly in Go, is there a way to implement the same ?

Here is the container from which I am iterating:

```<code>for e := dlist.Front(); e != nil; e = e.Next() {
    lines := e.Value
    fmt.Printf(reflect.TypeOf(lines))
}
</code>```

I am not able to get the type of the object lines in this case which is an array of strings.

答:
To get the type of fields in struct

```<code>package main

import (
  "fmt"
  "reflect"
)

type testObject struct {
  Name   string
  Age    int
  Height float64
}

func main() {
   tstObj := testObject{Name: "yog prakash", Age: 24, Height: 5.6}
   val := reflect.ValueOf(&tstObj).Elem()
   typeOfTstObj := val.Type()
   for i := 0; i < val.NumField(); i++ {
       fieldType := val.Field(i)
       fmt.Printf("object field %d key=%s value=%v type=%s \n",
          i, typeOfTstObj.Field(i).Name, fieldType.Interface(),
          fieldType.Type())
   }
}
</code>```

Output

```<code>object field 0 key=Name value=yog prakash type=string
object field 1 key=Age value=24 type=int
object field 2 key=Height value=5.6 type=float64
</code>```

See in IDE https://play.golang.org/p/bwIpYnBQiE

ContentLicense: CC BY-SA 4.0

Body:
How do I find the type of an object in Go? In Python, I just use typeof to fetch the type of object. Similarly in Go, is there a way to implement the same ?

Here is the container from which I am iterating:

for e := dlist.Front(); e != nil; e = e.Next() {
    lines := e.Value
    fmt.Printf(reflect.TypeOf(lines))
}

I am not able to get the type of the object lines in this case which is an array of strings.

Body:
To get the type of fields in struct

package main

import (
  "fmt"
  "reflect"
)

type testObject struct {
  Name   string
  Age    int
  Height float64
}

func main() {
   tstObj := testObject{Name: "yog prakash", Age: 24, Height: 5.6}
   val := reflect.ValueOf(&tstObj).Elem()
   typeOfTstObj := val.Type()
   for i := 0; i < val.NumField(); i++ {
       fieldType := val.Field(i)
       fmt.Printf("object field %d key=%s value=%v type=%s \n",
          i, typeOfTstObj.Field(i).Name, fieldType.Interface(),
          fieldType.Type())
   }
}

Output

object field 0 key=Name value=yog prakash type=string
object field 1 key=Age value=24 type=int
object field 2 key=Height value=5.6 type=float64

See in IDE https://play.golang.org/p/bwIpYnBQiE


问:
How can I test a change made to Jenkinsfile locally?
When writing jenkins pipelines it seems to be very inconvenient to commit each new change in order to see if it works.

Is there a way to execute these locally without committing the code?

答:
I have a solution that works well for me. It consists of a local jenkins running in docker and a git web hook to trigger the pipeline in the local jenkins on every commit. You no longer need to push to your github or bitbucket repository to test the pipeline.

This has only been tested in a linux environment.

It is fairly simple to make this work although this instruction is a tad long. Most steps are there.

This is what you need

Docker installed and working. This is not part of this instruction.

A Jenkins running in docker locally. Explained how below.

The proper rights (ssh access key) for your local Jenkins docker user to pull from your local git repo.  Explained how below.

A Jenkins pipeline project that pulls from your local git repository. Explained below.

A git user in your local Jenkins with minimal rights. Explained below.

A git project with a post-commit web hook that triggers the pipeline project. Explained below.

This is how you do it

Jenkins Docker

Create a file called Dockerfile in place of your choosing. I'm placing it in /opt/docker/jenkins/Dockerfile fill it with this:

```<code>FROM jenkins/jenkins:lts
USER root
RUN apt-get -y update && apt-get -y upgrade
# Your needed installations goes here
USER jenkins
</code>```

Build the local_jenkins image

This you will need to do only once or after you have added something to the Dockerfile.

```<code>$ docker build -t local_jenkins /opt/docker/jenkins/
</code>```

Start and restart local_jenkins

From time to time you want to start and restart jenkins easily. E.g. after a reboot of your machine. For this I made an alias that I put in .bash_aliases in my home folder.

```<code>$ echo "alias localjenkinsrestart='docker stop jenkins;docker rm jenkins;docker run --name jenkins -i -d -p 8787:8080 -p 50000:50000 -v /opt/docker/jenkins/jenkins_home:/var/jenkins_home:rw local_jenkins'" >> ~/.bash_aliases
$ source .bash_aliases  # To make it work
</code>```

Make sure the /opt/docker/jenkins/jenkins_home folder exists and that you have user read and write rights to it.

To start or restart your jenkins just type:

```<code>$ localjenkinsrestart
</code>```

Everything you do in your local jenkins will be stored in the folder /opt/docker/jenkins/jenkins_home and preserved between restarts.

Create a ssh access key in your docker jenkins

This is a very important part for this to work. First we start the docker container and create a bash shell to it:

```<code>$ localjenkinsrestart
$ docker exec -it jenkins /bin/bash
</code>```

You have now entered into the docker container, this you can see by something like jenkins@e7b23bad10aa:/$ in your terminal. The hash after the @ will for sure differ.

Create the key

```<code>jenkins@e7b23bad10aa:/$ ssh-keygen
</code>```

Press enter on all questions until you get the prompt back

Copy the key to your computer. From within the docker container your computer is 172.17.0.1 should you wonder.

```<code>jenkins@e7b23bad10aa:/$ ssh-copy-id user@172.17.0.1
</code>```

user = your username and 172.17.0.1 is the ip address to your computer from within the docker container.

You will have to type your password at this point.

Now lets try to complete the loop by ssh-ing to your computer from within the docker container.

```<code>jenkins@e7b23bad10aa:/$ ssh user@172.17.0.1
</code>```

This time you should not need to enter you password. If you do, something went wrong and you have to try again.

You will now be in your computers home folder. Try ls and have a look.

Do not stop here since we have a chain of ssh shells that we need to get out of.

```<code>$ exit
jenkins@e7b23bad10aa:/$ exit
</code>```

Right! Now we are back and ready to continue.

Install your Jenkins

You will find your local Jenkins in your browser at http://localhost:8787.

First time you point your browser to your local Jenkins your will be greated with a Installation Wizard.
Defaults are fine, do make sure you install the pipeline plugin during the setup though.

Setup your jenkins

It is very important that you activate matrix based security on http://localhost:8787/configureSecurity and give yourself all rights by adding yourself to the matrix and tick all the boxes. (There is a tick-all-boxes icon on the far right)

Select Jenkins’ own user database as the Security Realm

Select Matrix-based security in the Authorization section

Write your username in the field User/group to add: and click on the [ Add ] button

In the table above your username should pop up with a people icon next to it. If it is crossed over you typed your username incorrectly.

Go to the far right of the table and click on the tick-all-button or manually tick all the boxes in your row.

Please verify that the checkbox Prevent Cross Site Request Forgery exploits is unchecked. (Since this Jenkins is only reachable from your computer this isn't such a big deal)

Click on [ Save ] and log out of Jenkins and in again just to make sure it works.
If it doesn't you have to start over from the beginning and emptying the /opt/docker/jenkins/jenkins_home folder before restarting

Add the git user

We need to allow our git hook to login to our local Jenkins with minimal rights. Just to see and build jobs is sufficient. Therefore we create a user called git with password login.

Direct your browser to http://localhost:8787/securityRealm/addUser and add git as username and login as password.
Click on [ Create User ].

Add the rights to the git user

Go to the http://localhost:8787/configureSecurity page in your browser. Add the git user to the matrix:

Write git in the field User/group to add: and click on [ Add ]

Now it is time to check the boxes for minimal rights to the git user. Only these are needed:

overall:read

job:build

job:discover

job:read

Make sure that the Prevent Cross Site Request Forgery exploits checkbox is unchecked and click on [ Save ]

Create the pipeline project

We assume we have the username user and our git enabled project with the Jenkinsfile in it is called project and is located at /home/user/projects/project

In your http://localhost:8787 Jenkins add a new pipeline project. I named it hookpipeline for reference.

Click on New Item in the Jenkins menu

Name the project hookpipeline

Click on Pipeline

Click [ OK ]

Tick the checkbox Poll SCM in the Build Triggers section. Leave the Schedule empty.

In the Pipeline section:

select Pipeline script from SCM

in the Repository URL field enter user@172.17.0.1:projects/project/.git

in the Script Path field enter Jenkinsfile

Save the hookpipeline project

Build the hookpipeline manually once, this is needed for the Poll SCM to start working.

Create the git hook

Go to the /home/user/projects/project/.git/hooks folder and create a file called post-commit that contains this:

```<code>#!/bin/sh
BRANCHNAME=$(git rev-parse --abbrev-ref HEAD)
MASTERBRANCH='master'

curl -XPOST -u git:login http://localhost:8787/job/hookpipeline/build
echo "Build triggered successfully on branch: $BRANCHNAME"
</code>```

Make this file executable:

```<code>$ docker build -t local_jenkins /opt/docker/jenkins/
</code>```0

Test the post-commit hook:

```<code>$ docker build -t local_jenkins /opt/docker/jenkins/
</code>```1

Check in Jenkins if your hookpipeline project was triggered.

Finally make some arbitrary change to your project, add the changes and do a commit. This will now trigger the pipeline in your local Jenkins.

Happy Days!

Body:
I have a solution that works well for me. It consists of a local jenkins running in docker and a git web hook to trigger the pipeline in the local jenkins on every commit. You no longer need to push to your github or bitbucket repository to test the pipeline.

This has only been tested in a linux environment.

It is fairly simple to make this work although this instruction is a tad long. Most steps are there.

This is what you need

Docker installed and working. This is not part of this instruction.

A Jenkins running in docker locally. Explained how below.

The proper rights (ssh access key) for your local Jenkins docker user to pull from your local git repo.  Explained how below.

A Jenkins pipeline project that pulls from your local git repository. Explained below.

A git user in your local Jenkins with minimal rights. Explained below.

A git project with a post-commit web hook that triggers the pipeline project. Explained below.

This is how you do it

Jenkins Docker

Create a file called Dockerfile in place of your choosing. I'm placing it in /opt/docker/jenkins/Dockerfile fill it with this:

FROM jenkins/jenkins:lts
USER root
RUN apt-get -y update && apt-get -y upgrade
# Your needed installations goes here
USER jenkins

Build the local_jenkins image

This you will need to do only once or after you have added something to the Dockerfile.

$ docker build -t local_jenkins /opt/docker/jenkins/

Start and restart local_jenkins

From time to time you want to start and restart jenkins easily. E.g. after a reboot of your machine. For this I made an alias that I put in .bash_aliases in my home folder.

$ echo "alias localjenkinsrestart='docker stop jenkins;docker rm jenkins;docker run --name jenkins -i -d -p 8787:8080 -p 50000:50000 -v /opt/docker/jenkins/jenkins_home:/var/jenkins_home:rw local_jenkins'" >> ~/.bash_aliases
$ source .bash_aliases  # To make it work

Make sure the /opt/docker/jenkins/jenkins_home folder exists and that you have user read and write rights to it.

To start or restart your jenkins just type:

$ localjenkinsrestart

Everything you do in your local jenkins will be stored in the folder /opt/docker/jenkins/jenkins_home and preserved between restarts.

Create a ssh access key in your docker jenkins

This is a very important part for this to work. First we start the docker container and create a bash shell to it:

$ localjenkinsrestart
$ docker exec -it jenkins /bin/bash

You have now entered into the docker container, this you can see by something like jenkins@e7b23bad10aa:/$ in your terminal. The hash after the @ will for sure differ.

Create the key

jenkins@e7b23bad10aa:/$ ssh-keygen

Press enter on all questions until you get the prompt back

Copy the key to your computer. From within the docker container your computer is 172.17.0.1 should you wonder.

jenkins@e7b23bad10aa:/$ ssh-copy-id user@172.17.0.1

user = your username and 172.17.0.1 is the ip address to your computer from within the docker container.

You will have to type your password at this point.

Now lets try to complete the loop by ssh-ing to your computer from within the docker container.

jenkins@e7b23bad10aa:/$ ssh user@172.17.0.1

This time you should not need to enter you password. If you do, something went wrong and you have to try again.

You will now be in your computers home folder. Try ls and have a look.

Do not stop here since we have a chain of ssh shells that we need to get out of.

$ exit
jenkins@e7b23bad10aa:/$ exit

Right! Now we are back and ready to continue.

Install your Jenkins

You will find your local Jenkins in your browser at http://localhost:8787.

First time you point your browser to your local Jenkins your will be greated with a Installation Wizard.
Defaults are fine, do make sure you install the pipeline plugin during the setup though.

Setup your jenkins

It is very important that you activate matrix based security on http://localhost:8787/configureSecurity and give yourself all rights by adding yourself to the matrix and tick all the boxes. (There is a tick-all-boxes icon on the far right)

Select Jenkins’ own user database as the Security Realm

Select Matrix-based security in the Authorization section

Write your username in the field User/group to add: and click on the [ Add ] button

In the table above your username should pop up with a people icon next to it. If it is crossed over you typed your username incorrectly.

Go to the far right of the table and click on the tick-all-button or manually tick all the boxes in your row.

Please verify that the checkbox Prevent Cross Site Request Forgery exploits is unchecked. (Since this Jenkins is only reachable from your computer this isn't such a big deal)

Click on [ Save ] and log out of Jenkins and in again just to make sure it works.
If it doesn't you have to start over from the beginning and emptying the /opt/docker/jenkins/jenkins_home folder before restarting

Add the git user

We need to allow our git hook to login to our local Jenkins with minimal rights. Just to see and build jobs is sufficient. Therefore we create a user called git with password login.

Direct your browser to http://localhost:8787/securityRealm/addUser and add git as username and login as password.
Click on [ Create User ].

Add the rights to the git user

Go to the http://localhost:8787/configureSecurity page in your browser. Add the git user to the matrix:

Write git in the field User/group to add: and click on [ Add ]

Now it is time to check the boxes for minimal rights to the git user. Only these are needed:

overall:read

job:build

job:discover

job:read

Make sure that the Prevent Cross Site Request Forgery exploits checkbox is unchecked and click on [ Save ]

Create the pipeline project

We assume we have the username user and our git enabled project with the Jenkinsfile in it is called project and is located at /home/user/projects/project

In your http://localhost:8787 Jenkins add a new pipeline project. I named it hookpipeline for reference.

Click on New Item in the Jenkins menu

Name the project hookpipeline

Click on Pipeline

Click [ OK ]

Tick the checkbox Poll SCM in the Build Triggers section. Leave the Schedule empty.

In the Pipeline section:

select Pipeline script from SCM

in the Repository URL field enter user@172.17.0.1:projects/project/.git

in the Script Path field enter Jenkinsfile

Save the hookpipeline project

Build the hookpipeline manually once, this is needed for the Poll SCM to start working.

Create the git hook

Go to the /home/user/projects/project/.git/hooks folder and create a file called post-commit that contains this:

#!/bin/sh
BRANCHNAME=$(git rev-parse --abbrev-ref HEAD)
MASTERBRANCH='master'

curl -XPOST -u git:login http://localhost:8787/job/hookpipeline/build
echo "Build triggered successfully on branch: $BRANCHNAME"

Make this file executable:

$ chmod +x /home/user/projects/project/.git/hooks/post-commit

Test the post-commit hook:

$ /home/user/projects/project/.git/hooks/post-commit

Check in Jenkins if your hookpipeline project was triggered.

Finally make some arbitrary change to your project, add the changes and do a commit. This will now trigger the pipeline in your local Jenkins.

Happy Days!


问:
No value given for one or more required parameters vb.net
Hi all Iam trying to reduce a stock using this code below but Iam getting error, can any one help me pleaseee????`</p>

```<code>Public Sub UpdateDecreaseQuantity()
    Try
        Dim cb As String = "Update Dish SET Quantity = stocksOnHand - '" & DataGridView1.CurrentRow.Cells(2).Value & "' "
        con.Open()
        cmd = New OleDbCommand(cb, con)
        cmd.ExecuteNonQuery()

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        cmd.Dispose()
        con.Close()
    End Try

End Sub
</code>```

答:
Firstly, If DataGridView1.CurrentRow.Cells(2).Value is 0 length string or Nothing value you will get this error.

Please check using:

Not String.IsNullOrEmpty(DataGridView1.CurrentRow.Cells(2).Value).

Secondly, you have added quotes around the Cell value in the query

'" & DataGridView1.CurrentRow.Cells(2).Value & "' "

Numeric value should not have quotes around.

Thirdly, this query is prone to SQL injection attack. Please try to parameterize the query.

Example:

```<code>Dim OtherValue as Integer = 0
Dim cb As String = "Update Dish SET Quantity = stocksOnHand - @OtherValue"
con.Open()
cmd = New OleDbCommand(cb, con)
Int32.TryParse(DataGridView1.CurrentRow.Cells(2).Value, OtherValue)
cmd.Parameters.Add("@OtherValue", SqlDbType.Int).Value = OtherValue
cmd.ExecuteNonQuery()
</code>```

Body:
Hi all Iam trying to reduce a stock using this code below but Iam getting error, can any one help me pleaseee????`

Public Sub UpdateDecreaseQuantity()
    Try
        Dim cb As String = "Update Dish SET Quantity = stocksOnHand - '" & DataGridView1.CurrentRow.Cells(2).Value & "' "
        con.Open()
        cmd = New OleDbCommand(cb, con)
        cmd.ExecuteNonQuery()

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        cmd.Dispose()
        con.Close()
    End Try

End Sub

Body:
Firstly, If DataGridView1.CurrentRow.Cells(2).Value is 0 length string or Nothing value you will get this error.

Please check using:

Not String.IsNullOrEmpty(DataGridView1.CurrentRow.Cells(2).Value).

Secondly, you have added quotes around the Cell value in the query

'" & DataGridView1.CurrentRow.Cells(2).Value & "' "

Numeric value should not have quotes around.

Thirdly, this query is prone to SQL injection attack. Please try to parameterize the query.

Example:

Dim OtherValue as Integer = 0
Dim cb As String = "Update Dish SET Quantity = stocksOnHand - @OtherValue"
con.Open()
cmd = New OleDbCommand(cb, con)
Int32.TryParse(DataGridView1.CurrentRow.Cells(2).Value, OtherValue)
cmd.Parameters.Add("@OtherValue", SqlDbType.Int).Value = OtherValue
cmd.ExecuteNonQuery()


问:
CMD: Can't add 1 to 08 using += operator
I am using CMD commands to work on some variables. I can add 1 to a variable but if that variable is 08 or 09, the result comes out to be 1,rather than 9 or 10. Here's the code:

```<code>setlocal EnableDelayedExpansion
set day=08
echo Day:%day%
set /a day+=1
echo Day:% day%
</code>```

This works for numbers 1-7, and after 10. I need to add a leading zero to digits less than 10 because otherwise somehow the variable is not written to a text file (which I perform later) despite showing the correct value in other parts of the code.

答:
Help for command SET can be read by running in a command prompt window set /?. It explains that numbers with a leading 0 are interpreted as octal numbers, see function strtol with base being 0 (automatic detection) as used internally by Windows command interpreter.

08 and 09 are invalid in octal number system and are therefore interpreted with value 0.

One solution for this case is using first a string concatenation during preprocessing state to change the string 08 to 108 and subtract 99 from 108 converted to an integer number to get 08 and 09 as well as 01 to 31 incremented by 1.

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "day=08"
echo Day: %day%
set /A day=1%day% - 99
echo Day: %day%
endlocal
</code>```

The output of above batch file is:

```<code>Day: 08
Day: 9
</code>```

Delayed environment variable expansion is not needed here and in general not needed at all in an arithmetic expression as also explained by help of command SET. There are of course exceptions like a string concatenation must be done first before executing the arithmetic expression within a command block on which the environment variable was defined or modified before in the command block. But those use cases are really rare.

When the result should be again with a leading 0 for numbers with less than two digits, it is best not subtracting 99, but adding 1 and assign to the environment variable in next step just the last two digits from the string with always 3 digits after evaluation of arithmetic expression.

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "day=08"
echo Day: %day%
set /A day=1%day% + 1
set "day=%day:~-2%"
echo Day: %day%
endlocal
</code>```

The output of above batch file is:

```<code>Day: 08
Day: 09
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

endlocal /?

set /?

setlocal /?

Body:
I am using CMD commands to work on some variables. I can add 1 to a variable but if that variable is 08 or 09, the result comes out to be 1,rather than 9 or 10. Here's the code:

setlocal EnableDelayedExpansion
set day=08
echo Day:%day%
set /a day+=1
echo Day:% day%

This works for numbers 1-7, and after 10. I need to add a leading zero to digits less than 10 because otherwise somehow the variable is not written to a text file (which I perform later) despite showing the correct value in other parts of the code.

Body:
Help for command SET can be read by running in a command prompt window set /?. It explains that numbers with a leading 0 are interpreted as octal numbers, see function strtol with base being 0 (automatic detection) as used internally by Windows command interpreter.

08 and 09 are invalid in octal number system and are therefore interpreted with value 0.

One solution for this case is using first a string concatenation during preprocessing state to change the string 08 to 108 and subtract 99 from 108 converted to an integer number to get 08 and 09 as well as 01 to 31 incremented by 1.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "day=08"
echo Day: %day%
set /A day=1%day% - 99
echo Day: %day%
endlocal

The output of above batch file is:

Day: 08
Day: 9

Delayed environment variable expansion is not needed here and in general not needed at all in an arithmetic expression as also explained by help of command SET. There are of course exceptions like a string concatenation must be done first before executing the arithmetic expression within a command block on which the environment variable was defined or modified before in the command block. But those use cases are really rare.

When the result should be again with a leading 0 for numbers with less than two digits, it is best not subtracting 99, but adding 1 and assign to the environment variable in next step just the last two digits from the string with always 3 digits after evaluation of arithmetic expression.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "day=08"
echo Day: %day%
set /A day=1%day% + 1
set "day=%day:~-2%"
echo Day: %day%
endlocal

The output of above batch file is:

Day: 08
Day: 09

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

endlocal /?

set /?

setlocal /?


答:
The only good answer to this question is: don't do it. gotos used in this way make your code very hard to reason about.

Refactor your code so that you have a clear structure and hierarchy of calls. Use return values to propagate success/failure throughout the call stack.

Title: How to use goto across multiple functions


问:
Why does this code compile? (C++ template question)
I am writing a generalized container using a class template, with a restriction (policy) that the items stored in the container should derive from a specific base class.

Here is the definition of the class template

```<code>// GenericContainer.hpp
// --------------------------------------
class ContainerItem
{
protected:
    virtual ContainerItem& getInvalid() = 0;

public:
    virtual ~ContainerItem();
    bool isValid() const;
};

template<typename D, typename B>
class IsDerivedFrom
{
    static void Constraints(D* p)
    {
        B* pb = p; // this line only works if 'D' inherits 'B'
        pb = p; // suppress warnings about unused variables
    }

protected:
    void IsDerivedFrom2() { void(*p)(D*) = Constraints; }
};

// Force it to fail in the case where B is void
template<typename D>
class IsDerivedFrom<D, void>
{
    void IsDerivedFrom2() { char* p = (int*)0; /* error */ }
};

template <class T>
class GenericContainer : public IsDerivedFrom<T, ContainerItem>
{
private:
    typedef std::vector<T> TypeVect;
    void addElement(const T& elem);

    TypeVect m_elems;

public:
    unsigned int size() const;
    T& elementAt(const unsigned int pos);
    const T& elementAt(const unsigned int pos) const;
};

template <class T>
void GenericContainer<T>::addElement(const T& elem)
{
    m_elems.push_back(elem);
}

template <class T>
unsigned int GenericContainer<T>::size() const
{
    return m_elems.size();
}

template <class T>
T& GenericContainer<T>::elementAt(const unsigned int pos)
{
    unsigned int maxpos = m_elems.size();
    if (pos < maxpos)
        return m_elems[pos];
    return T::getInvalid();
}

template <class T>
const T& GenericContainer<T>::elementAt(const unsigned int pos) const
{
    unsigned int maxpos = m_elems.size();
    if (pos < maxpos)
        return m_elems[pos];
    return T::getInvalid();
}

// Class to be contained (PURPOSELY, does not derive from ContainerItem)
// Data.hpp
//----------------------------------------------------------------

class Data
{ /* implem details */};

// Container for Data items
// Dataset.h
// ----------------------------------------------------------------------------

#include "GenericContainer.hpp"
#include "Data.hpp"

class Dataset: public GenericContainer<Data>
{
public:
   Data& getInvalid();
};

// C++ source
// -----------------------------------------------------------
#include "Dataset.hpp"

Dataset ds;
</code>```

Can anyone explain why the code above compiles?.

[Edit]

The code above should NOT compile for two reasons:

The class 'Data' does NOT derive from ContainerItem, and yet it can be stored in GenericContainer (as illustrated by the class Dataset). Incidentally, this issue has now been resolved thanks to the answer given by Omifarious and jdv

The class 'Data' does NOT implement the pure virtual method declared in the ABC ContainerItem - using the fixes recommended in the answers below, the first issue (enforcement of policy) is resolved, however the compiler fails to notice that Data does not implement the getInvalid() method of the ContainerItem 'interface'. Why is the compiler missing this glaring mistake?

BTW, compiler and OS details are:
g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3

答:
Change IsDerivedFrom2 to IsDerivedFrom and it fails to compile in just the expected manner.

The problem is that a method from a template class is never instantiated if it isn't called. Changing the name makes it a constructor, so it then ends up being called by the constructors of classes derived from IsDerivedFrom. It will still compile to empty code. The compiler will optimize it away the dead assignment.

I would recommend you not write template code like this yourself if you can manage to use Boost, particularly is_base_of from the Boost type traits library.

In particular, your GenericContainer template can be more simply and easily implemented this way using Boost:

```<code>#include <boost/static_assert.hpp>
#include <boost/type_traits/is_base_of.hpp>

template <class T>
class GenericContainer
{
private:
    typedef std::vector<T> TypeVect;
    void addElement(const T& elem);

    TypeVect m_elems;

public:
    unsigned int size() const;
    T& elementAt(const unsigned int pos);
    const T& elementAt(const unsigned int pos) const;

    GenericContainer() {
       BOOST_STATIC_ASSERT( (::boost::is_base_of<ContainerItem, T>::value) );
    }
};

template <class T>
void GenericContainer<T>::addElement(const T& elem)
{
    m_elems.push_back(elem);
}

template <class T>
unsigned int GenericContainer<T>::size() const
{
    return m_elems.size();
}

template <class T>
T& GenericContainer<T>::elementAt(const unsigned int pos)
{
    unsigned int maxpos = m_elems.size();
    if (pos < maxpos)
        return m_elems[pos];
    return T::getInvalid();
}

template <class T>
const T& GenericContainer<T>::elementAt(const unsigned int pos) const
{
    unsigned int maxpos = m_elems.size();
    if (pos < maxpos)
        return m_elems[pos];
    return T::getInvalid();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am writing a generalized container using a class template, with a restriction (policy) that the items stored in the container should derive from a specific base class.

Here is the definition of the class template

// GenericContainer.hpp
// --------------------------------------
class ContainerItem
{
protected:
    virtual ContainerItem& getInvalid() = 0;

public:
    virtual ~ContainerItem();
    bool isValid() const;
};

template<typename D, typename B>
class IsDerivedFrom
{
    static void Constraints(D* p)
    {
        B* pb = p; // this line only works if 'D' inherits 'B'
        pb = p; // suppress warnings about unused variables
    }

protected:
    void IsDerivedFrom2() { void(*p)(D*) = Constraints; }
};

// Force it to fail in the case where B is void
template<typename D>
class IsDerivedFrom<D, void>
{
    void IsDerivedFrom2() { char* p = (int*)0; /* error */ }
};

template <class T>
class GenericContainer : public IsDerivedFrom<T, ContainerItem>
{
private:
    typedef std::vector<T> TypeVect;
    void addElement(const T& elem);

    TypeVect m_elems;

public:
    unsigned int size() const;
    T& elementAt(const unsigned int pos);
    const T& elementAt(const unsigned int pos) const;
};

template <class T>
void GenericContainer<T>::addElement(const T& elem)
{
    m_elems.push_back(elem);
}

template <class T>
unsigned int GenericContainer<T>::size() const
{
    return m_elems.size();
}

template <class T>
T& GenericContainer<T>::elementAt(const unsigned int pos)
{
    unsigned int maxpos = m_elems.size();
    if (pos < maxpos)
        return m_elems[pos];
    return T::getInvalid();
}

template <class T>
const T& GenericContainer<T>::elementAt(const unsigned int pos) const
{
    unsigned int maxpos = m_elems.size();
    if (pos < maxpos)
        return m_elems[pos];
    return T::getInvalid();
}

// Class to be contained (PURPOSELY, does not derive from ContainerItem)
// Data.hpp
//----------------------------------------------------------------

class Data
{ /* implem details */};

// Container for Data items
// Dataset.h
// ----------------------------------------------------------------------------

#include "GenericContainer.hpp"
#include "Data.hpp"

class Dataset: public GenericContainer<Data>
{
public:
   Data& getInvalid();
};

// C++ source
// -----------------------------------------------------------
#include "Dataset.hpp"

Dataset ds;

Can anyone explain why the code above compiles?.

[Edit]

The code above should NOT compile for two reasons:

The class 'Data' does NOT derive from ContainerItem, and yet it can be stored in GenericContainer (as illustrated by the class Dataset). Incidentally, this issue has now been resolved thanks to the answer given by Omifarious and jdv

The class 'Data' does NOT implement the pure virtual method declared in the ABC ContainerItem - using the fixes recommended in the answers below, the first issue (enforcement of policy) is resolved, however the compiler fails to notice that Data does not implement the getInvalid() method of the ContainerItem 'interface'. Why is the compiler missing this glaring mistake?

BTW, compiler and OS details are:
g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3

Body:
Change IsDerivedFrom2 to IsDerivedFrom and it fails to compile in just the expected manner.

The problem is that a method from a template class is never instantiated if it isn't called. Changing the name makes it a constructor, so it then ends up being called by the constructors of classes derived from IsDerivedFrom. It will still compile to empty code. The compiler will optimize it away the dead assignment.

I would recommend you not write template code like this yourself if you can manage to use Boost, particularly is_base_of from the Boost type traits library.

In particular, your GenericContainer template can be more simply and easily implemented this way using Boost:

#include <boost/static_assert.hpp>
#include <boost/type_traits/is_base_of.hpp>

template <class T>
class GenericContainer
{
private:
    typedef std::vector<T> TypeVect;
    void addElement(const T& elem);

    TypeVect m_elems;

public:
    unsigned int size() const;
    T& elementAt(const unsigned int pos);
    const T& elementAt(const unsigned int pos) const;

    GenericContainer() {
       BOOST_STATIC_ASSERT( (::boost::is_base_of<ContainerItem, T>::value) );
    }
};

template <class T>
void GenericContainer<T>::addElement(const T& elem)
{
    m_elems.push_back(elem);
}

template <class T>
unsigned int GenericContainer<T>::size() const
{
    return m_elems.size();
}

template <class T>
T& GenericContainer<T>::elementAt(const unsigned int pos)
{
    unsigned int maxpos = m_elems.size();
    if (pos < maxpos)
        return m_elems[pos];
    return T::getInvalid();
}

template <class T>
const T& GenericContainer<T>::elementAt(const unsigned int pos) const
{
    unsigned int maxpos = m_elems.size();
    if (pos < maxpos)
        return m_elems[pos];
    return T::getInvalid();
}


问:
loop over columns and display results
I want to loop over a table in oracle, find the null values in each column, and then update those values,
for now I am trying to just output the number of null values in each column, but i'm getting an error message :

```<code>SET FEEDBACK OFF;
SET SERVEROUTPUT ON;

DECLARE
   N_NULLS       NUMBER;
   BEGIN
   FOR I IN (SELECT COLUMN_NAME
               FROM ALL_TAB_COLUMNS
              WHERE TABLE_NAME = 'my_table')
   LOOP
          SELECT SUM (CASE WHEN I IS NULL THEN 1 ELSE 0 END)
        INTO N_NULLS
        FROM my_table
       WHERE COLUMN_ITEM IS NULL;

      DBMS_OUTPUT.PUT_LINE ('NUMBER OF NULLS IN'|| I ||' IS ' || N_NULLS);
   END LOOP;
END;
/
</code>```

I get the following errors :

```<code>Error at line 10
ORA-06550: line 9, column 23:
PLS-00382: expression is of wrong type
ORA-06550: line 9, column 8:
PL/SQL: Statement ignored
ORA-06550: line 10, column 29:
PLS-00382: expression is of wrong type
</code>```

答:
@a_horse_with_no_name is correct, you can try the below code to find empty rows in columns of a particular table.</p>

```<code>SET SERVEROUTPUT ON

DECLARE
    l_sql     VARCHAR2(4000);
    n_nulls   NUMBER;
BEGIN
    FOR i IN (
        SELECT
            column_name
        FROM
            all_tab_columns
        WHERE
            table_name = 'my_table'
    ) LOOP
        l_sql := ' SELECT SUM (CASE WHEN '
         || i.column_name
         || ' IS NULL THEN 1 ELSE 0 END)
        FROM my_table
       WHERE '
         || i.column_name
         || ' IS NULL';

        EXECUTE IMMEDIATE l_sql INTO
            n_nulls;
        dbms_output.put_line('NUMBER OF NULLS IN'
         || i.column_name
         || ' IS '
         || n_nulls);
    END LOOP;
END;
/
</code>```

Title: loop over columns and display results

Body:
I want to loop over a table in oracle, find the null values in each column, and then update those values,
for now I am trying to just output the number of null values in each column, but i'm getting an error message :

SET FEEDBACK OFF;
SET SERVEROUTPUT ON;

DECLARE
   N_NULLS       NUMBER;
   BEGIN
   FOR I IN (SELECT COLUMN_NAME
               FROM ALL_TAB_COLUMNS
              WHERE TABLE_NAME = 'my_table')
   LOOP
          SELECT SUM (CASE WHEN I IS NULL THEN 1 ELSE 0 END)
        INTO N_NULLS
        FROM my_table
       WHERE COLUMN_ITEM IS NULL;

      DBMS_OUTPUT.PUT_LINE ('NUMBER OF NULLS IN'|| I ||' IS ' || N_NULLS);
   END LOOP;
END;
/

I get the following errors :

Error at line 10
ORA-06550: line 9, column 23:
PLS-00382: expression is of wrong type
ORA-06550: line 9, column 8:
PL/SQL: Statement ignored
ORA-06550: line 10, column 29:
PLS-00382: expression is of wrong type

Body:
@a_horse_with_no_name is correct, you can try the below code to find empty rows in columns of a particular table.

SET SERVEROUTPUT ON

DECLARE
    l_sql     VARCHAR2(4000);
    n_nulls   NUMBER;
BEGIN
    FOR i IN (
        SELECT
            column_name
        FROM
            all_tab_columns
        WHERE
            table_name = 'my_table'
    ) LOOP
        l_sql := ' SELECT SUM (CASE WHEN '
         || i.column_name
         || ' IS NULL THEN 1 ELSE 0 END)
        FROM my_table
       WHERE '
         || i.column_name
         || ' IS NULL';

        EXECUTE IMMEDIATE l_sql INTO
            n_nulls;
        dbms_output.put_line('NUMBER OF NULLS IN'
         || i.column_name
         || ' IS '
         || n_nulls);
    END LOOP;
END;
/


问:
Running an exe file on premises from azure scheduler?
I want to be able to run an exe file in an on premises server from Azure, using a Logic app or maybe azure scheduler.

Is this possible, if so how?

Even doing this via Azure function could be an option. Do i need something like on premises data gateway or maybe even hybrid connections?

答:
As I known, Azure Scheduler and Logic App don't support .exe file.

For Cloud service, I think you can use worker role to meet your requirement. Worker role could handle background processor. Also, you can use the startup task to run your exe.

You can see a example in this document.


答:
Just as you use double quotes to signify a String in VB but do not put them around numbers, so single quotes denote a string in SQL.  If you are subtracting two numbers then they must both be numbers, not a one number and a string.

```<code>Dim cb As String = "Update Dish SET Quantity = stocksOnHand - " & DataGridView1.CurrentRow.Cells(2).Value.ToString()
</code>```

Even better would be to learn how to insert values into SQL properly and use parameters.

Title: No value given for one or more required parameters vb.net

Body:
Just as you use double quotes to signify a String in VB but do not put them around numbers, so single quotes denote a string in SQL.  If you are subtracting two numbers then they must both be numbers, not a one number and a string.

Dim cb As String = "Update Dish SET Quantity = stocksOnHand - " & DataGridView1.CurrentRow.Cells(2).Value.ToString()

Even better would be to learn how to insert values into SQL properly and use parameters.


问:
Microsoft Authentication in ASP.NET Core 2 and Azure App Services
I have the following application at GitHub and have deployed it to https://stratml.services on an Azure App Service with Authentication defined as Microsoft Account with anymous requests requiring a Microsoft Account sign in. In "prod" this challenge occurs, however https://stratml.services/Home/IdentityName returns no content.

I have been following this and this however I do not want to use EntityFramework and from the latter's description it seems to imply if I configure my Authentication scheme correctly I do not have to.

This following code is in my Start class:

```<code>        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
        }).AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:AppId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Key"];
            microsoftOptions.CallbackPath = new PathString("/.auth/login/microsoftaccount/callback");

        });
</code>```

Update: Thanks to the first answer I was able to get, it now authorizes to Microsoft and attempts to feedback to my application however I receive the following error:

```<code>InvalidOperationException: No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Cookies
</code>```

Please visit https://stratml.services/Home/IdentityName and the GitHub has been updated.

```<code>        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
        }).AddCookie(option =>
        {
            option.Cookie.Name = ".myAuth"; //optional setting
        }).AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:AppId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Key"];

        });
</code>```

答:
If you are using App Service Authentication (EasyAuth), according to Microsoft documentation page:

App Service passes some user information to your application by using special headers. External requests prohibit these headers and will only be present if set by App Service Authentication / Authorization. Some example headers include:

X-MS-CLIENT-PRINCIPAL-NAME

X-MS-CLIENT-PRINCIPAL-ID

X-MS-TOKEN-FACEBOOK-ACCESS-TOKEN

X-MS-TOKEN-FACEBOOK-EXPIRES-ON

Code that is written in any language or framework can get the information that it needs from these headers. For ASP.NET 4.6 apps, the ClaimsPrincipal is automatically set with the appropriate values.

So basically, if you are using ASP.NET Core 2.0, you need to set the ClaimPrincipal manually. What you need to use in order to fetch this headers and set the ClaimsPrincipal is AuthenticationHandler

```<code>public class AppServiceAuthenticationOptions : AuthenticationSchemeOptions
{
    public AppServiceAuthenticationOptions()
    {
    }
}

internal class AppServiceAuthenticationHandler : AuthenticationHandler<AppServiceAuthenticationOptions>
{
    public AppServiceAuthenticationHandler(
        IOptionsMonitor<AppServiceAuthenticationOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        return Task.FromResult(FetchAuthDetailsFromHeaders());
    }

    private AuthenticateResult FetchAuthDetailsFromHeaders()
    {
        Logger.LogInformation("starting authentication handler for app service authentication");

        if (Context.User == null || Context.User.Identity == null || Context.User.Identity.IsAuthenticated == false)
        {
            Logger.LogDebug("identity not found, attempting to fetch from the request headers");

            if (Context.Request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL-ID"))
            {
                var headerId = Context.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"][0];
                var headerName = Context.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"][0];

                var claims = new Claim[] {
                    new Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", headerId),
                    new Claim("name", headerName)
                };
                Logger.LogDebug($"Populating claims with id: {headerId} | name: {headerName}");

                var identity = new GenericIdentity(headerName);
                identity.AddClaims(claims);

                var principal = new GenericPrincipal(identity, null);
                var ticket = new AuthenticationTicket(principal,
                    new AuthenticationProperties(),
                    Scheme.Name);

                Context.User = principal;
                return AuthenticateResult.Success(ticket);
            }
            else
            {
                return AuthenticateResult.Fail("Could not found the X-MS-CLIENT-PRINCIPAL-ID key in the headers");
            }
        }

        Logger.LogInformation("identity already set, skipping middleware");
        return AuthenticateResult.NoResult();
    }
}
</code>```

You can then write an extension method for the middleware

```<code>public static class AppServiceAuthExtensions
{
    public static AuthenticationBuilder AddAppServiceAuthentication(this AuthenticationBuilder builder, Action<AppServiceAuthenticationOptions> configureOptions)
    {
        return builder.AddScheme<AppServiceAuthenticationOptions, AppServiceAuthenticationHandler>("AppServiceAuth", "Azure App Service EasyAuth", configureOptions);
    }
}
</code>```

And add app.UseAuthentication(); in the Configure() method and put following in the ConfigureServices() method of your startup class.

```<code>services
    .AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "AppServiceAuth";
        options.DefaultChallengeScheme = "AppServiceAuth";
    })
    .AddAppServiceAuthentication(o => { });
</code>```

If you need full claims details, you can retrieve it on the AuthenticationHandler by making request to /.auth/me and use the same cookies that you've received on the request.

Body:
I have the following application at GitHub and have deployed it to https://stratml.services on an Azure App Service with Authentication defined as Microsoft Account with anymous requests requiring a Microsoft Account sign in. In "prod" this challenge occurs, however https://stratml.services/Home/IdentityName returns no content.

I have been following this and this however I do not want to use EntityFramework and from the latter's description it seems to imply if I configure my Authentication scheme correctly I do not have to.

This following code is in my Start class:

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
        }).AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:AppId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Key"];
            microsoftOptions.CallbackPath = new PathString("/.auth/login/microsoftaccount/callback");

        });

Update: Thanks to the first answer I was able to get, it now authorizes to Microsoft and attempts to feedback to my application however I receive the following error:

InvalidOperationException: No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Cookies

Please visit https://stratml.services/Home/IdentityName and the GitHub has been updated.

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
        }).AddCookie(option =>
        {
            option.Cookie.Name = ".myAuth"; //optional setting
        }).AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:AppId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Key"];

        });

Body:
If you are using App Service Authentication (EasyAuth), according to Microsoft documentation page:

App Service passes some user information to your application by using special headers. External requests prohibit these headers and will only be present if set by App Service Authentication / Authorization. Some example headers include:

X-MS-CLIENT-PRINCIPAL-NAME

X-MS-CLIENT-PRINCIPAL-ID

X-MS-TOKEN-FACEBOOK-ACCESS-TOKEN

X-MS-TOKEN-FACEBOOK-EXPIRES-ON

Code that is written in any language or framework can get the information that it needs from these headers. For ASP.NET 4.6 apps, the ClaimsPrincipal is automatically set with the appropriate values.

So basically, if you are using ASP.NET Core 2.0, you need to set the ClaimPrincipal manually. What you need to use in order to fetch this headers and set the ClaimsPrincipal is AuthenticationHandler

public class AppServiceAuthenticationOptions : AuthenticationSchemeOptions
{
    public AppServiceAuthenticationOptions()
    {
    }
}

internal class AppServiceAuthenticationHandler : AuthenticationHandler<AppServiceAuthenticationOptions>
{
    public AppServiceAuthenticationHandler(
        IOptionsMonitor<AppServiceAuthenticationOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        return Task.FromResult(FetchAuthDetailsFromHeaders());
    }

    private AuthenticateResult FetchAuthDetailsFromHeaders()
    {
        Logger.LogInformation("starting authentication handler for app service authentication");

        if (Context.User == null || Context.User.Identity == null || Context.User.Identity.IsAuthenticated == false)
        {
            Logger.LogDebug("identity not found, attempting to fetch from the request headers");

            if (Context.Request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL-ID"))
            {
                var headerId = Context.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"][0];
                var headerName = Context.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"][0];

                var claims = new Claim[] {
                    new Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", headerId),
                    new Claim("name", headerName)
                };
                Logger.LogDebug($"Populating claims with id: {headerId} | name: {headerName}");

                var identity = new GenericIdentity(headerName);
                identity.AddClaims(claims);

                var principal = new GenericPrincipal(identity, null);
                var ticket = new AuthenticationTicket(principal,
                    new AuthenticationProperties(),
                    Scheme.Name);

                Context.User = principal;
                return AuthenticateResult.Success(ticket);
            }
            else
            {
                return AuthenticateResult.Fail("Could not found the X-MS-CLIENT-PRINCIPAL-ID key in the headers");
            }
        }

        Logger.LogInformation("identity already set, skipping middleware");
        return AuthenticateResult.NoResult();
    }
}

You can then write an extension method for the middleware

public static class AppServiceAuthExtensions
{
    public static AuthenticationBuilder AddAppServiceAuthentication(this AuthenticationBuilder builder, Action<AppServiceAuthenticationOptions> configureOptions)
    {
        return builder.AddScheme<AppServiceAuthenticationOptions, AppServiceAuthenticationHandler>("AppServiceAuth", "Azure App Service EasyAuth", configureOptions);
    }
}

And add app.UseAuthentication(); in the Configure() method and put following in the ConfigureServices() method of your startup class.

services
    .AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "AppServiceAuth";
        options.DefaultChallengeScheme = "AppServiceAuth";
    })
    .AddAppServiceAuthentication(o => { });

If you need full claims details, you can retrieve it on the AuthenticationHandler by making request to /.auth/me and use the same cookies that you've received on the request.


问:
how to deep _sumBy using lodash?
```<code>var data= [{
        "item_name": "Jumbo Combo",
        "item_key": "9lazhy15tp2fgo72",
        "item_price": 25,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }, {
        "item_name": "Swiss & Mushroom Combo",
        "item_key": "e1vdfos6s50d5kej",
        "item_price": 22,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }]
</code>```

i want to sum the item_price as well as "ingredients":[{"price":3}] using loadash how to deep sumBy

i tryed item_price

```<code>_.sumBy(data, 'item_price')
</code>```

this can get the total price of item price in an array, but how to get sum of price of ingredients and item_price

答:
Sum of elements with the price of the ingredients

Besides passing the name of an attribute as a string to the _sumBy function, you can also pass a function that determines what function to apply the items to obtain values that can be summed up. So we can replace the query with:

```<code>_.sumBy(data, <b>x => x.item_price</b>)</code>```

But now we still need to sum up the ingredients. How will we do that? Use another _.sumBy of course!

```<code>_.sumBy(data, x => x.item_price + <b>_.sumBy(x.ingredients, 'price')</b>)</code>```

(this yields 53).

Multiply with the quantity

We can immediately multiply these values with the quantity attribute as well:

```<code>_.sumBy(data, x => <b>x.quantity * (</b>x.item_price + _.sumBy(x.ingredients, 'price')<b>)</b>)</code>```

(this yields again 53, since all quantities are 1).

Title: how to deep _sumBy using lodash?

Body:
var data= [{
        "item_name": "Jumbo Combo",
        "item_key": "9lazhy15tp2fgo72",
        "item_price": 25,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }, {
        "item_name": "Swiss & Mushroom Combo",
        "item_key": "e1vdfos6s50d5kej",
        "item_price": 22,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }]

i want to sum the item_price as well as "ingredients":[{"price":3}] using loadash how to deep sumBy

i tryed item_price

_.sumBy(data, 'item_price')

this can get the total price of item price in an array, but how to get sum of price of ingredients and item_price

Body:
Sum of elements with the price of the ingredients

Besides passing the name of an attribute as a string to the _sumBy function, you can also pass a function that determines what function to apply the items to obtain values that can be summed up. So we can replace the query with:

_.sumBy(data, x => x.item_price)

But now we still need to sum up the ingredients. How will we do that? Use another _.sumBy of course!

_.sumBy(data, x => x.item_price + _.sumBy(x.ingredients, 'price'))

(this yields 53).

Multiply with the quantity

We can immediately multiply these values with the quantity attribute as well:

_.sumBy(data, x => x.quantity * (x.item_price + _.sumBy(x.ingredients, 'price')))

(this yields again 53, since all quantities are 1).


问:
Elements form array.map don't render
I am trying to render elements from my state (array) but they don't want render on the screen. If I perform console.log(b.name) it logs my names in console.

```<code>renderAllElements() {
    this.state.myData.map(b => {
        return(
            <div>
                <h4>{b.name}</h4>
            </div>
        )
    })
}

render() {
    return (
        <div>
            {this.renderAllElements()}
        </div>
    )
}
</code>```

答:
You are correctly invoking your renderAllElements() function in your render method. You also seem to correctly map through your array variable, but the function doesn't return anything back to render once finished mapping.

Simply add a return for your map function and it should work:

```<code>renderAllElements() {
  return this.state.myData.map(b => {
      return(
        <div>
            <h4>{b.name}</h4>
        </div>
     )
  })
}
</code>```

One-liner alternative:

```<code>renderAllElements() {
  return this.state.myData.map(b => <div><h4>{b.name}</h4></div>);
}
</code>```

Title: Elements form array.map don't render

Body:
I am trying to render elements from my state (array) but they don't want render on the screen. If I perform console.log(b.name) it logs my names in console.

renderAllElements() {
    this.state.myData.map(b => {
        return(

{b.name}

        )
    })
}

render() {
    return (

            {this.renderAllElements()}

    )
}

Body:
You are correctly invoking your renderAllElements() function in your render method. You also seem to correctly map through your array variable, but the function doesn't return anything back to render once finished mapping.

Simply add a return for your map function and it should work:

renderAllElements() {
  return this.state.myData.map(b => {
      return(
        <div>
            <h4>{b.name}</h4>
        </div>
     )
  })
}

One-liner alternative:

renderAllElements() {
  return this.state.myData.map(b => <div><h4>{b.name}</h4></div>);
}


问:
SKProductRequest returning SSErrorHTTPStatusCodeKey 404
I am making a SKProductRequest using MKStoreKit (v5). I am making an SKProductRequest for a product that has already been approved in the app store, but I am getting an error. Specifically:

```<code>Error Domain=SSErrorDomain Code=109 "Cannot connect to iTunes Store" UserInfo=0x171262140 {NSLocalizedDescription=Cannot connect to iTunes Store, SSErrorHTTPStatusCodeKey=404
</code>```

What's confusing me the most is the SSErrorHTTPStatusCodeKey 404. The product/IAP has been created in itunes connect. I also have logged out of my personal itunes store account. I'm fairly certain it is making the request to sandbox itunes because I have MITM'd and it makes the request there. However, the request fails because of SSL issues when MITM'd.

EDIT: The product identifiers made using the SKProductsRequest are definitely approved and definitely match the product identifiers in iTunes Connect

答:
I just experimented this issue. My app was accepted and available on the AppStore, but In App Purchase were missing

When running on Xcode, I was gettings the error SSErrorHTTPStatusCodeKey 404 since my app was accepted (not before)

After investigation I think I found the solution: for first IAP, the in-app purchase should be added on the Application page (iTunes Connect > My App > App version > and then "In app purchases" in the right panel (just under "General Informations")

I'm currently posting the app, I'll post an edit here if it worked.

Body:
I am making a SKProductRequest using MKStoreKit (v5). I am making an SKProductRequest for a product that has already been approved in the app store, but I am getting an error. Specifically:

Error Domain=SSErrorDomain Code=109 "Cannot connect to iTunes Store" UserInfo=0x171262140 {NSLocalizedDescription=Cannot connect to iTunes Store, SSErrorHTTPStatusCodeKey=404

What's confusing me the most is the SSErrorHTTPStatusCodeKey 404. The product/IAP has been created in itunes connect. I also have logged out of my personal itunes store account. I'm fairly certain it is making the request to sandbox itunes because I have MITM'd and it makes the request there. However, the request fails because of SSL issues when MITM'd.

EDIT: The product identifiers made using the SKProductsRequest are definitely approved and definitely match the product identifiers in iTunes Connect


问:
iterate over Dataframe row by index value and find max
I need to iterate over df rows based on its index. I need to find the max in the column p1 and fill it in the output dataframe (along with the max p1), the same for the column p2. In each range of my row indexes (sub_1_ica_1---> sub_1_ica_n), there must be only one 1 and one 2 and I need to fill the remaining with zeros. That's why I need to do the operation range by range.

I tried to split the index name and make a counter for each subject to be used to iterate over the rows, but I feel that I am in the wrong way!

```<code>    from collections import Counter
    a = df.id.tolist()
    indlist = []
    for x in a:
    i = x.split('_')
    b = int(i[1])
    indlist.insert(-1,b)
    c=Counter(indlist)
    keyInd = c.keys()
</code>```

Any ideas?

EDIT: according to Jerazel example my desired output would look like this.
First I find the max for p1 and p2 columns which will be translated in the new df into 1 and 2, and the remaining fields will be zeros

答:
I think you need numpy.argmax with max, also if need columns names use idxmax:

```<code>idx = ['sub_1_ICA_0','sub_1_ICA_1','sub_1_ICA_2','sub_2_ICA_0','sub_2_ICA_1','sub_2_ICA_2']
df = pd.DataFrame({'p0':[7,8,9,4,2,3],
                   'p1':[1,3,5,7,1,0],
                   'p2':[5,9,6,1,2,4]}, index=idx)

print (df)

cols = ['p0','p1','p2']
df['a'] = df[cols].values.argmax(axis=1)
df['b'] = df[cols].max(axis=1)
df['c'] = df[cols].idxmax(axis=1)
print (df)
             p0  p1  p2  a  b   c
sub_1_ICA_0   7   1   5  0  7  p0
sub_1_ICA_1   8   3   9  2  9  p2
sub_1_ICA_2   9   5   6  0  9  p0
sub_2_ICA_0   4   7   1  1  7  p1
sub_2_ICA_1   2   1   2  0  2  p0
sub_2_ICA_2   3   0   4  2  4  p2
</code>```

Body:
I need to iterate over df rows based on its index. I need to find the max in the column p1 and fill it in the output dataframe (along with the max p1), the same for the column p2. In each range of my row indexes (sub_1_ica_1---> sub_1_ica_n), there must be only one 1 and one 2 and I need to fill the remaining with zeros. That's why I need to do the operation range by range.

I tried to split the index name and make a counter for each subject to be used to iterate over the rows, but I feel that I am in the wrong way!

    from collections import Counter
    a = df.id.tolist()
    indlist = []
    for x in a:
    i = x.split('_')
    b = int(i[1])
    indlist.insert(-1,b)
    c=Counter(indlist)
    keyInd = c.keys()

Any ideas?

EDIT: according to Jerazel example my desired output would look like this.
First I find the max for p1 and p2 columns which will be translated in the new df into 1 and 2, and the remaining fields will be zeros

Body:
I think you need numpy.argmax with max, also if need columns names use idxmax:

idx = ['sub_1_ICA_0','sub_1_ICA_1','sub_1_ICA_2','sub_2_ICA_0','sub_2_ICA_1','sub_2_ICA_2']
df = pd.DataFrame({'p0':[7,8,9,4,2,3],
                   'p1':[1,3,5,7,1,0],
                   'p2':[5,9,6,1,2,4]}, index=idx)

print (df)

cols = ['p0','p1','p2']
df['a'] = df[cols].values.argmax(axis=1)
df['b'] = df[cols].max(axis=1)
df['c'] = df[cols].idxmax(axis=1)
print (df)
             p0  p1  p2  a  b   c
sub_1_ICA_0   7   1   5  0  7  p0
sub_1_ICA_1   8   3   9  2  9  p2
sub_1_ICA_2   9   5   6  0  9  p0
sub_2_ICA_0   4   7   1  1  7  p1
sub_2_ICA_1   2   1   2  0  2  p0
sub_2_ICA_2   3   0   4  2  4  p2


答: The Constraints function is not generated because IsDerivedFrom2 is never referenced. This is required behavior for C++.  Maybe it helps to call it from the constructor. Otherwise, check the boost library for functionality like this.

Title: Why does this code compile? (C++ template question)


问:
Eclipse Jar-in-Jar fails to find a joda.time class
Eclipse has 3 runnable JAR export methods. One of them does not work in my case. I want to stop using the export method that makes a library sub-folder and switch to a single JAR.

In all cases my invocation is in a script, with a few script variables such as $MEMORYOPTIONS

java $MEMORYOPTIONS -enableassertions -classpath VARIOUS-SHOWN-BELOW topLevelDomain.domain.packageName.className $1 $2 $3

Firstly...

I have success with the following export method and the class path as shown.

export > runnable jar > extract required libraries

-classpath /home/user/workspace/project/project1.jar

I have a reason for not wanting to use this single JAR. (It is because unpackaged third party packages expose files with duplicate names so I get annoying warnings. Example: A file called License.txt is in several packages.)

Secondly...

As already mentioned I also have success with the following "library sub-folder" export method and class path as shown.

export > runnable jar > copy required libraries into a sub-folder

-classpath /home/user/workspace/project/project1.jar:/home/user/workspace/project/project1_lib/*

(Edit: As it turns out the JAR has a manifest that points to the project1_lib subfolder so the class path can be simplified to omit that. Just delete the part after the colon (:) separator from the class path.)

Thirdly...

I interpret "package required libraries" to mean a JAR-in-JAR export. Invoked with the class path shown, this export results in a failure to find the class.

export > runnable jar > package required libraries

-classpath /home/user/workspace/project/project1.jar

The error is:

Exception in thread "main" java.lang.NoClassDefFoundError: org/joda/time/ReadablePartial

How do I get this particular type of Eclipse export to work? I have already uninstalled Eclipse (Mars) and reinstalled. I have also
removed the org.joda.time package and added it back. The problem persists.

答:
You need to call the bundled JarRsrcLoader with your class as an argument:

```<code>java $MEMORYOPTIONS -enableassertions
-classpath /home/user/workspace/project/project1.jar
org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
topLevelDomain.domain.packageName.className
</code>```

However, this doesn't allow you to pass arguments ($1 $2 $3) to the called class.

Body:
You need to call the bundled JarRsrcLoader with your class as an argument:

java $MEMORYOPTIONS -enableassertions
-classpath /home/user/workspace/project/project1.jar
org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
topLevelDomain.domain.packageName.className

However, this doesn't allow you to pass arguments ($1 $2 $3) to the called class.


问:
numpy boolean indexing selecting and setting
I'm not very familiar with python. I reading the book 'Python for Data Analysis' recently, and I'm a bit confused about the numpy boolean indexing and setting.
The book said:

Selecting data from an array by boolean indexing always creates a copy of the data, even if the returned array is unchanged.

Setting values with boolean arrays works in a common-sense way.

And I have tried it as the follow code:

First:

```<code>data = np.random.randn(7, 4)
data[data < 0] = 0 # this could change the `data`
</code>```

Second:

```<code>data = np.random.randn(7, 4)
copied = data[data < 0]
copied[1] = 1  # this couldn't change the `data`
</code>```

I do not quite understand here, anyone can explain it. In my understanding, copied should be pointer to the data[data < 0] slices.

答:
While data[data < 0] = 0 sorta looks like a view being set to 0, that's not what's actually happening.  In reality, an ndarray followed by = calls __setitem__ which handles the piecewise assingment.

When the ndarray is on the other side of the =, __setitem__ isn't called and you assign a copy (as boolean indexing always does), which is independent of the original array.

Essentially:

```<code>foo[foo != bar] = bar                # calls __setitem__
foo[:2]         = bar                # calls __setitem__
bar             = foo[foo != bar]    # makes a copy
bar             = foo[:2]            # makes a view
</code>```

Body:
I'm not very familiar with python. I reading the book 'Python for Data Analysis' recently, and I'm a bit confused about the numpy boolean indexing and setting.
The book said:

Selecting data from an array by boolean indexing always creates a copy of the data, even if the returned array is unchanged.

Setting values with boolean arrays works in a common-sense way.

And I have tried it as the follow code:

First:

data = np.random.randn(7, 4)
data[data < 0] = 0 # this could change the `data`

Second:

data = np.random.randn(7, 4)
copied = data[data < 0]
copied[1] = 1  # this couldn't change the `data`

I do not quite understand here, anyone can explain it. In my understanding, copied should be pointer to the data[data < 0] slices.

Body:
While data[data < 0] = 0 sorta looks like a view being set to 0, that's not what's actually happening.  In reality, an ndarray followed by = calls __setitem__ which handles the piecewise assingment.

When the ndarray is on the other side of the =, __setitem__ isn't called and you assign a copy (as boolean indexing always does), which is independent of the original array.

Essentially:

foo[foo != bar] = bar                # calls __setitem__
foo[:2]         = bar                # calls __setitem__
bar             = foo[foo != bar]    # makes a copy
bar             = foo[:2]            # makes a view


问:
Not getting keycode in keyup function
I'm trying to add a keyup function to an input field which is added to DOM using jquery.

```<code>$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(this)'>");
</code>```

I want to do some operations once user enters value in testTextbox and enter key is pressed.

The keyup function is like:

```<code>function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}
</code>```

The e.keyCode and e.which is returning undefined.

How can I get the keycode in keyup function? Can anyone help me to fix this? Thanks in advance.

答:
I guess, you are mixing different things: pure js and jquery. Using only jquery, you can achieve what you want with the snippet below.

$("#testTextbox").on("keyup", function(e){
alert(e.keyCode+" : "+e.which);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='testTextbox' name='testTextbox' type='text' ></code>```

Using only pure Js

function testKeyUp(e){
  alert(e.keyCode+" : "+e.which);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(event)'></code>```

Title: Not getting keycode in keyup function

Body:
I'm trying to add a keyup function to an input field which is added to DOM using jquery.

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(this)'>");

I want to do some operations once user enters value in testTextbox and enter key is pressed.

The keyup function is like:

function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}

The e.keyCode and e.which is returning undefined.

How can I get the keycode in keyup function? Can anyone help me to fix this? Thanks in advance.

Body:
I guess, you are mixing different things: pure js and jquery. Using only jquery, you can achieve what you want with the snippet below.

$("#testTextbox").on("keyup", function(e){
alert(e.keyCode+" : "+e.which);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='testTextbox' name='testTextbox' type='text' >

Using only pure Js

function testKeyUp(e){
  alert(e.keyCode+" : "+e.which);
}

<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(event)'>


问:
When is memory allocated by malloc garbage collected?
I am guessing (hoping) the answer is never.
That such memory must be explicitly freed.

For example if if I wrote:

```<code>julia> x = Libc.malloc(1_000_000)
Ptr{Void} @0x0000000002f6bd80

julia> x = nothing
</code>```

have I just leaked ~1MB of memory?

However I am not 100% certain this is true,
because the docs don't mention it at all.

help?> Libc.malloc(3)

         malloc(size::Integer) -> Ptr{Void}

Call malloc from the C standard library.

答:
Yes, you are correct.

Julia is designed to seamlessly interoperate with C on a low level, so when you use the C wrapper libraries, you you get C semantics and no garbage collection.

The docs for Libc.malloc is not written to teach C, but could be improved to mention Libc.free, in case anyone gets confused.

Body:
I am guessing (hoping) the answer is never.
That such memory must be explicitly freed.

For example if if I wrote:

julia> x = Libc.malloc(1_000_000)
Ptr{Void} @0x0000000002f6bd80

julia> x = nothing

have I just leaked ~1MB of memory?

However I am not 100% certain this is true,
because the docs don't mention it at all.

help?> Libc.malloc(3)

         malloc(size::Integer) -> Ptr{Void}

Call malloc from the C standard library.


问:
SqlConnection error vs2015 with C#
I work with VS 2012 and SQL Server 2012. When I changed to VS 2015 & SQL Server 2014, my SqlConnection didn't work and causing errors that the servers could not be found.

My code:

```<code>SqlConnection cn = new SqlConnection(@"Data Source=(local); Initial Catalog=jood; Integrated Security=true;MultipleActiveResultSets=true");

public Form1()
{
    cn.Open();
    cn.Close();
    InitializeComponent();
}
</code>```

Error

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

  Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

答:
Check to be sure that "Initial Catalog=jood; is the same as on your sql DB.
The error basically means it can't find that DB you're trying to connect to.</p>

Title: SqlConnection error vs2015 with C#

Body:
I work with VS 2012 and SQL Server 2012. When I changed to VS 2015 & SQL Server 2014, my SqlConnection didn't work and causing errors that the servers could not be found.

My code:

SqlConnection cn = new SqlConnection(@"Data Source=(local); Initial Catalog=jood; Integrated Security=true;MultipleActiveResultSets=true");

public Form1()
{
    cn.Open();
    cn.Close();
    InitializeComponent();
}

Error

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

  Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)


问:
SQL Server Full Text Search to find containing characters
I have a table with a column Document that is FullText Index.
Let say I have this in this table:

```<code>| ID | Document                    |
| 1  | WINTER  SUMMER SPRING OTHER |
</code>```

My requirement is to find rows that contains 'ER'.

For this I am querying like this:

```<code>SELECT TOP 100
    [FullTextSearch].[Document], [FullTextSearch].[ID]
FROM
    [FullTextSearch]
WHERE
    CONTAINS(Document, '"*ER*"')
</code>```

But this is not working.

Please suggest what should be best way to do this using FullTextSearch.

I am expecting id 1 should be returned.

答:
You can user LIKE operator to find the value.

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards used in conjunction with the LIKE operator:

% - The percent sign represents zero, one, or multiple characters
_ - The underscore represents a single character

Syntax,

SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

This query can help to find the result.

SELECT Document,ID FROM FullTextSearch
WHERE Document LIKE '%ER%';

Body:
I have a table with a column Document that is FullText Index.
Let say I have this in this table:

| ID | Document                    |
| 1  | WINTER  SUMMER SPRING OTHER |

My requirement is to find rows that contains 'ER'.

For this I am querying like this:

SELECT TOP 100
    [FullTextSearch].[Document], [FullTextSearch].[ID]
FROM
    [FullTextSearch]
WHERE
    CONTAINS(Document, '"*ER*"')

But this is not working.

Please suggest what should be best way to do this using FullTextSearch.

I am expecting id 1 should be returned.