问:
Get access to a ChildModel in Controller and View via a ParentModel
I am not able to give Values to the ChildModel via the ParnetModel and access my ChildModel in the View. Or should I make a own ViewModel, for those values I need for it in the view?

Here is my ParentModel

```<code>public class ParentModel
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ChildModel ChildModel { get; set; }
    public List<ChildModel> ChildModelList { get; set; }
}
</code>```

and a ChildModel

```<code>public class ChildModel
{
    public int Number { get; set; }
    public string ChildName { get; set; }
}
</code>```

In the controller I have to fill the Parentmodel+the Childmodel and give it to the View

```<code>List<ParentModel> listparent = new List<ParentModel>();
listparent.Add(
    new ParentModel
    {
        Id = 1,
        Name = "abc",
        ChildModel.Number = 2,    // does not work
        ChildModelList.Number = 2 // does not work
    }
);
</code>```

I don't know how to access the ChildModel here, when I want to add values for it.

In the View I have to access the Child too. I added the ParentModel with:

```<code>@model List<TestApp4.Models.ParentModel>
</code>```

And then I would try to achieve them viea:

```<code>@foreach (var item in Model)
{
     @item.Id
     @item.Name
     @item.ChildModel.Number
}
</code>```

This does not work. Am I right, that the controller has to be a List because otherwise I cannot iterate over it in the View?

答:
Well, ChildModel is a class, so you have to create a new instance first.

And ChildModel is an generic list, so you have to create an instance of the list, and add an instance of the generic type

```<code>listparent.Add(
    new ParentModel
    {
        Id = 1,
        Name = "abc",
        ChildModel = new ChildModel {Number = 2},
        ChildModelList = new List<ChildeModel>(new[]{
                                 new ChildModel{Number=1},
                                 new ChildModel{Number= xxx}
                                })
    }
);
</code>```

so in your view, you can have something like this

```<code>@foreach (var item in Model)
{
     @item.Id
     @item.Name
     @item.ChildModel.Number //you may check for null if ChildModel is not always declared
     foreach(var cm in item.ChildModelList) {//nul check may also be usefull
        @c.Number
     }
}
</code>```

You may create an instance of ChildModelList in the constructor of your ParentModel class , to be sure you have an existing instance of ChildModelList.

```<code>public class ParentModel
{
    public ParentModel() {
        ChildModelList = new List<ChildModel>();
    }
    //and even a ctor  with a given number to instanciate ChildModel
    public ParentModel(int childNumber) : this() {
        ChildModel = new ChildModel{Number = childNumber};
    }
    public int Id { get; set; }
    public string Name { get; set; }

    public ChildModel ChildModel { get; set; }
    public List<ChildModel> ChildModelList { get; set; }
}
</code>```

Body:
I am not able to give Values to the ChildModel via the ParnetModel and access my ChildModel in the View. Or should I make a own ViewModel, for those values I need for it in the view?

Here is my ParentModel

public class ParentModel
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ChildModel ChildModel { get; set; }
    public List<ChildModel> ChildModelList { get; set; }
}

and a ChildModel

public class ChildModel
{
    public int Number { get; set; }
    public string ChildName { get; set; }
}

In the controller I have to fill the Parentmodel+the Childmodel and give it to the View

List<ParentModel> listparent = new List<ParentModel>();
listparent.Add(
    new ParentModel
    {
        Id = 1,
        Name = "abc",
        ChildModel.Number = 2,    // does not work
        ChildModelList.Number = 2 // does not work
    }
);

I don't know how to access the ChildModel here, when I want to add values for it.

In the View I have to access the Child too. I added the ParentModel with:

@model List<TestApp4.Models.ParentModel>

And then I would try to achieve them viea:

@foreach (var item in Model)
{
     @item.Id
     @item.Name
     @item.ChildModel.Number
}

This does not work. Am I right, that the controller has to be a List because otherwise I cannot iterate over it in the View?

Body:
Well, ChildModel is a class, so you have to create a new instance first.

And ChildModel is an generic list, so you have to create an instance of the list, and add an instance of the generic type

listparent.Add(
    new ParentModel
    {
        Id = 1,
        Name = "abc",
        ChildModel = new ChildModel {Number = 2},
        ChildModelList = new List<ChildeModel>(new[]{
                                 new ChildModel{Number=1},
                                 new ChildModel{Number= xxx}
                                })
    }
);

so in your view, you can have something like this

@foreach (var item in Model)
{
     @item.Id
     @item.Name
     @item.ChildModel.Number //you may check for null if ChildModel is not always declared
     foreach(var cm in item.ChildModelList) {//nul check may also be usefull
        @c.Number
     }
}

You may create an instance of ChildModelList in the constructor of your ParentModel class , to be sure you have an existing instance of ChildModelList.

public class ParentModel
{
    public ParentModel() {
        ChildModelList = new List<ChildModel>();
    }
    //and even a ctor  with a given number to instanciate ChildModel
    public ParentModel(int childNumber) : this() {
        ChildModel = new ChildModel{Number = childNumber};
    }
    public int Id { get; set; }
    public string Name { get; set; }

    public ChildModel ChildModel { get; set; }
    public List<ChildModel> ChildModelList { get; set; }
}


来源: stackexchange

问:
How to add new packages in Kubernetes
As the title, I added a new algorithm package in the plugin/pkg/scheduler/algorithm/priorities folder for Kubernetes. It is a folder, there are some Go source files, like the util folder. But, when run make, I got the errors:

```<code>test/e2e_node/e2e_node.test
    cmd/gke-certificates-controller
plugin/pkg/scheduler/algorithm/priorities/test.go:7:2: no buildable Go source files in /home/zhangjian/src/k8s.io/kubernetes/_output/local/go/src/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/test
!!! [0703 09:22:46] Call tree:
!!! [0703 09:22:46]  1: /home/zhangjian/src/k8s.io/kubernetes/hack/lib/golang.sh:740 kube::golang::build_binaries_for_platform(...)
!!! [0703 09:22:46]  2: hack/make-rules/build.sh:27 kube::golang::build_binaries(...)
!!! [0703 09:22:46] Call tree:
!!! [0703 09:22:46]  1: hack/make-rules/build.sh:27 kube::golang::build_binaries(...)
!!! [0703 09:22:46] Call tree:
!!! [0703 09:22:46]  1: hack/make-rules/build.sh:27 kube::golang::build_binaries(...)
make: *** [all] Error 1
</code>```

They are the Go files indeed, I didn't know the reason of the error. Or something else I missed?

And I just want to add my own algorithm package (not the third libs, such exapmle.com/xxx/xxx) into the priority, so what's the steps?

I referred to community/contributors/devel/godep.md and tried go build ./..., ./hack/godep-restore.sh, ./hack/godep-save.sh commands, but still did not work.

答: The problem turned out to be caused by CGO_ENABLED variable, still need to set it enable in hack/lib/golang.sh file (a file of kubernetes project) although you enabled it in environment variable.

ContentLicense: CC BY-SA 3.0

Title: How to add new packages in Kubernetes

Body:
As the title, I added a new algorithm package in the plugin/pkg/scheduler/algorithm/priorities folder for Kubernetes. It is a folder, there are some Go source files, like the util folder. But, when run make, I got the errors:

test/e2e_node/e2e_node.test
    cmd/gke-certificates-controller
plugin/pkg/scheduler/algorithm/priorities/test.go:7:2: no buildable Go source files in /home/zhangjian/src/k8s.io/kubernetes/_output/local/go/src/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/test
!!! [0703 09:22:46] Call tree:
!!! [0703 09:22:46]  1: /home/zhangjian/src/k8s.io/kubernetes/hack/lib/golang.sh:740 kube::golang::build_binaries_for_platform(...)
!!! [0703 09:22:46]  2: hack/make-rules/build.sh:27 kube::golang::build_binaries(...)
!!! [0703 09:22:46] Call tree:
!!! [0703 09:22:46]  1: hack/make-rules/build.sh:27 kube::golang::build_binaries(...)
!!! [0703 09:22:46] Call tree:
!!! [0703 09:22:46]  1: hack/make-rules/build.sh:27 kube::golang::build_binaries(...)
make: *** [all] Error 1

They are the Go files indeed, I didn't know the reason of the error. Or something else I missed?

And I just want to add my own algorithm package (not the third libs, such exapmle.com/xxx/xxx) into the priority, so what's the steps?

I referred to community/contributors/devel/godep.md and tried go build ./..., ./hack/godep-restore.sh, ./hack/godep-save.sh commands, but still did not work.


问:
Bigquery Find which table an entry belongs to
I'm cleaning my production dataset, to do, i'm looking for some useless entries.

```<code>SELECT count(pid_like) FROM TABLE_DATE_RANGE(DATASET.TABLE_PRODUCTION_, DATE_ADD(CURRENT_TIMESTAMP(), -30, 'DAY'),CURRENT_TIMESTAMP()) where c1 is null and c2 is null and c3 is null and c4 is null
</code>```

So I want to delete entries where c1, c2, c3 and c4 are null.

Before I made on the last 30 tables the cleaning as:

```<code># done for each last 30 tables
DELETE FROM DATASET.TABLE_PRODUCTION_YYYYMMDD where c1 is null and c2 is null and c2 is null and c4 is null.
</code>```

But after the cleaning, some useless entries remain but I can't find on what table they are.

答:
Try this to find which tables have rows with nulls:

```<code>#standardSQL
SELECT
  _TABLE_SUFFIX AS suffix,
  COUNT(*) AS null_count
FROM `DATASET.TABLE_PRODUCTION_*`
WHERE _TABLE_SUFFIX BETWEEN
    FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)) AND
    FORMAT_DATE('%Y%m%d', CURRENT_DATE()) AND
  c1 IS NULL AND
  c2 IS NULL AND
  c3 IS NULL AND
  c4 IS NULL
GROUP BY suffix
HAVING null_count > 0
ORDER BY null_count DESC;
</code>```

It will return the suffixes (dates) with null rows and the counts.

Body:
I'm cleaning my production dataset, to do, i'm looking for some useless entries.

SELECT count(pid_like) FROM TABLE_DATE_RANGE(DATASET.TABLE_PRODUCTION_, DATE_ADD(CURRENT_TIMESTAMP(), -30, 'DAY'),CURRENT_TIMESTAMP()) where c1 is null and c2 is null and c3 is null and c4 is null

So I want to delete entries where c1, c2, c3 and c4 are null.

Before I made on the last 30 tables the cleaning as:

# done for each last 30 tables
DELETE FROM DATASET.TABLE_PRODUCTION_YYYYMMDD where c1 is null and c2 is null and c2 is null and c4 is null.

But after the cleaning, some useless entries remain but I can't find on what table they are.

Body:
Try this to find which tables have rows with nulls:

#standardSQL
SELECT
  _TABLE_SUFFIX AS suffix,
  COUNT(*) AS null_count
FROM `DATASET.TABLE_PRODUCTION_*`
WHERE _TABLE_SUFFIX BETWEEN
    FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)) AND
    FORMAT_DATE('%Y%m%d', CURRENT_DATE()) AND
  c1 IS NULL AND
  c2 IS NULL AND
  c3 IS NULL AND
  c4 IS NULL
GROUP BY suffix
HAVING null_count > 0
ORDER BY null_count DESC;

It will return the suffixes (dates) with null rows and the counts.


问:
Get min,max and avg per hour of the created_at time
I have a table with a field created_at with the following values:

```<code>2017-06-06 13:04:50
2017-06-06 13:09:54
2017-06-06 13:20:20
2017-06-06 13:40:29
2017-06-06 14:05:30
2017-06-06 14:12:50
2017-06-06 14:30:40
2017-06-06 15:01:36
2017-06-06 15:06:16
</code>```

What I want is to create a new table and do the following thing:
I want to get per hour the min, max and average and save it into another table.

答:
IMO integers are easier to manipulate than datetime. Step 1 convert values to timestamps. Then it is a matter of mathematical operations such as

min: http://php.net/manual/en/function.min.php

max: http://php.net/manual/en/function.max.php

average: add all, divide by count

Once you have the three values use PDO http://php.net/manual/en/book.pdo.php to insert the data to a table.

(Note: DO NOT USE the mysql database extension!)

Body:
I have a table with a field created_at with the following values:

2017-06-06 13:04:50
2017-06-06 13:09:54
2017-06-06 13:20:20
2017-06-06 13:40:29
2017-06-06 14:05:30
2017-06-06 14:12:50
2017-06-06 14:30:40
2017-06-06 15:01:36
2017-06-06 15:06:16

What I want is to create a new table and do the following thing:
I want to get per hour the min, max and average and save it into another table.


问:
How to remove all non-uppercase characters in a string?
Yeah I'm basically just trying to explode a phrase like Social Inc. or David Jason to SI and DJ. I've tried using explode but couldn't figure out how to explode everything BUT the capital letters, do I need to use preg_match()?

答:
I've got a more complicated solution but it works too!

```<code>$s = str_split("Social Inc.");
foreach ($s as $idx => $char) {
    if(preg_match("/[A-Z]/", $char))
    {
        echo $char;
    }
}
</code>```

It will echo the upper-case letters.

Body:
I've got a more complicated solution but it works too!

$s = str_split("Social Inc.");
foreach ($s as $idx => $char) {
    if(preg_match("/[A-Z]/", $char))
    {
        echo $char;
    }
}

It will echo the upper-case letters.


问:
Java algorithms
I am a server side Java programmer. In my recent job search, I have come across a few postings where they mention : ' Candidates with expereince in algorithm development will be preferred'. What exactly does this refer to? This is the posting for a Bank...so not a job for a research laboratory...just to clarify a bit.

I asked my headhunter ...he does not have an idea about this.

When we use Java in applications, we use the APIs that implement algorithms...so technically we are not developing algorithms. Right?

答:
Wrong.

Well, of course it depends on the project.  But there are plenty of mundane projects that need more than just sticking tab A into slot B.  If you like, consider that they said "algorithm development", not "algorithm research".  Research and development are two parts of of the deal -- related but not the same.

Not every algorithm is available as a standard library.  Also, a particular implementation of an algorithm is not necessarily appropriate for every application.  Finally, even when using a canned routine, understanding how the algorithm works is frequently helpful in figuring out how to use it properly.

So, the job postings are for someone with some understanding of algorithms.  How to use them.  How to adapt them to a particular purpose. How to read a paper (written by an egghead from a research laboratory, perhaps?) and implement the algorithm therein -- or to reject it and continue looking for something more suitable to the purpose at hand.  And, yes, very occasionally, how to come up with something new and different.

ContentLicense: CC BY-SA 2.5

Title: Java algorithms


问:
C# foreach with string - ignore last character
I have a methode who add numbers together parsed from a string.

If user type : "52+7+1", it will result in (60)
"52++2+3", "52+c+2", "+52+2", "52+2++", ... won't work.

My code works almost perfectly, expect... it ignores the last character. It works when, in the code I add "+0" to the string but of course it brokes the condition who prevent the user to type "+" as a last character.

```<code>    public int addFromString(string str)
    {
        bool valid_str = true;
        bool current_char_numeric = false;

        string unparsedNumber = "";
        int parsedNumber = 0;
        List<int> parsedNumbers = new List<int>();

        if (string.IsNullOrEmpty(chaine))
            chaine_valide = false;
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber))
               valid_str = false;

            if (!int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
                valid_str = false;
        }

        foreach (char c in str)
        {
            current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);

            if (current_char_numeric)
                unparsedNumber += c;
            else if(c == '+')
            {
                int.TryParse(unparsedNumber, out parsedNumber);
                parsedNumbers.Add(parsedNumber);

                if (str.IndexOf(c) < str.Length && str.ElementAt(str.IndexOf(c) + 1) == '+')
                    valid_str = false;

                //Just in case :
                unparsedNumber = "";
                current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);
            }
            else valid_str = false;
        }

        int result = 0;

        if(valid_str) { foreach(int n in parsedNumbers) { result += n; } }

        return result;
}
</code>```

So if I type : "52+2" I get 52

If I type : "52+2+6" I get 54

答:
It seems that all you want is Split:

```<code>  string source = "52+7+1";

  int sum = 0;                // initial sum is 0
  bool chaine_valide = true;  // the chain is valid (we don't have any counter examples)

  // Split on terms: 52, 7, 1
  foreach (string term in source.Split('+')) {
    int value;

    // No need in Trim() etc. - TryParse is smart enough
    if (int.TryParse(term, out value))
      sum += value;          // valid term: add it up
    else {
      chaine_valide = false; // counter example: term is not a valid integer

      break;
    }
  }

  ...

  Console.Write(chaine_valide ? sum.ToString() : "Invalid formula");
</code>```

In case of C# 7.0 you can (with a help of out var) simplify the code into

```<code>  int sum = 0;                // initial sum is 0
  bool chaine_valide = true;  // the chain is valid (we don't have any counter examples)

  // Split on terms: 52, 7, 1
  foreach (string term in source.Split('+'))
    if (int.TryParse(term, out var value))
      sum += value;          // valid term: add it up
    else {
      chaine_valide = false; // counter example: term is not a valid integer

      break;
    }
</code>```

Body:
I have a methode who add numbers together parsed from a string.

If user type : "52+7+1", it will result in (60)
"52++2+3", "52+c+2", "+52+2", "52+2++", ... won't work.

My code works almost perfectly, expect... it ignores the last character. It works when, in the code I add "+0" to the string but of course it brokes the condition who prevent the user to type "+" as a last character.

    public int addFromString(string str)
    {
        bool valid_str = true;
        bool current_char_numeric = false;

        string unparsedNumber = "";
        int parsedNumber = 0;
        List<int> parsedNumbers = new List<int>();

        if (string.IsNullOrEmpty(chaine))
            chaine_valide = false;
        else
        {
            if (!int.TryParse(str[0].ToString(), out parsedNumber))
               valid_str = false;

            if (!int.TryParse(str[str.Length - 1].ToString(), out parsedNumber))
                valid_str = false;
        }

        foreach (char c in str)
        {
            current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);

            if (current_char_numeric)
                unparsedNumber += c;
            else if(c == '+')
            {
                int.TryParse(unparsedNumber, out parsedNumber);
                parsedNumbers.Add(parsedNumber);

                if (str.IndexOf(c) < str.Length && str.ElementAt(str.IndexOf(c) + 1) == '+')
                    valid_str = false;

                //Just in case :
                unparsedNumber = "";
                current_char_numeric = int.TryParse(c.ToString(), out parsedNumber);
            }
            else valid_str = false;
        }

        int result = 0;

        if(valid_str) { foreach(int n in parsedNumbers) { result += n; } }

        return result;
}

So if I type : "52+2" I get 52

If I type : "52+2+6" I get 54

Body:
It seems that all you want is Split:

  string source = "52+7+1";

  int sum = 0;                // initial sum is 0
  bool chaine_valide = true;  // the chain is valid (we don't have any counter examples)

  // Split on terms: 52, 7, 1
  foreach (string term in source.Split('+')) {
    int value;

    // No need in Trim() etc. - TryParse is smart enough
    if (int.TryParse(term, out value))
      sum += value;          // valid term: add it up
    else {
      chaine_valide = false; // counter example: term is not a valid integer

      break;
    }
  }

  ...

  Console.Write(chaine_valide ? sum.ToString() : "Invalid formula");

In case of C# 7.0 you can (with a help of out var) simplify the code into

  int sum = 0;                // initial sum is 0
  bool chaine_valide = true;  // the chain is valid (we don't have any counter examples)

  // Split on terms: 52, 7, 1
  foreach (string term in source.Split('+'))
    if (int.TryParse(term, out var value))
      sum += value;          // valid term: add it up
    else {
      chaine_valide = false; // counter example: term is not a valid integer

      break;
    }


问:
SQL error - Incorrect syntax near the keyword 'Database'
I want to detect databases beginning with 'NAV'in a MS SQL DB. I tried it with this code:

```<code>DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE' + @DBName);
</code>```

But I got the error message:

```<code>Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Database'.
</code>```

Do know what is wrong there?

答:
Put a space after USE and put brackets around the database name:</p>

```<code>DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName + ']');
</code>```

Body:
I want to detect databases beginning with 'NAV'in a MS SQL DB. I tried it with this code:

DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE' + @DBName);

But I got the error message:

Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Database'.

Do know what is wrong there?

Body:
Put a space after USE and put brackets around the database name:

DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName + ']');


问:
how to get list of all available images for a region in amazon web services using aws-java-sdk?
How can i get the list of all available images for a region using aws-java-sdk, I just tried with the below code, it is keep on executing for a long time.</p>

```<code>AmazonEC2  ec2Client = new AmazonEC2Client(awsCredetials);
ec2Client.setRegion(RegionUtils.getRegion("us-west-2"));
DescribeImagesRequest request = new DescribeImagesRequest().withFilters(new LinkedList<Filter>());
DescribeImagesResult describeImagesResult= ec2Client.describeImages(request);
</code>```

答:
When I tried with filter

```<code>request.getFilters().add(new Filter().withName("architecture").withValues("x86_64"));
request.getFilters().add(new Filter().withName("platform").withValues("Ubuntu"));
</code>```

I got zero result and the reason I found was like platform is always null apart from windows.

I have tried with wildcards

```<code>request.getFilters().add(new Filter().withName("architecture").withValues("x86_64"));
request.getFilters().add(new Filter().withName("description").withValues("*Linux*"));
</code>```

which works well since we are not bothering about plarform here. But hardly I don't know why DescribeImagesResult returns platform as null for OS apart from windows

Body:
How can i get the list of all available images for a region using aws-java-sdk, I just tried with the below code, it is keep on executing for a long time.

AmazonEC2  ec2Client = new AmazonEC2Client(awsCredetials);
ec2Client.setRegion(RegionUtils.getRegion("us-west-2"));
DescribeImagesRequest request = new DescribeImagesRequest().withFilters(new LinkedList<Filter>());
DescribeImagesResult describeImagesResult= ec2Client.describeImages(request);

Body:
When I tried with filter

request.getFilters().add(new Filter().withName("architecture").withValues("x86_64"));
request.getFilters().add(new Filter().withName("platform").withValues("Ubuntu"));

I got zero result and the reason I found was like platform is always null apart from windows.

I have tried with wildcards

request.getFilters().add(new Filter().withName("architecture").withValues("x86_64"));
request.getFilters().add(new Filter().withName("description").withValues("*Linux*"));

which works well since we are not bothering about plarform here. But hardly I don't know why DescribeImagesResult returns platform as null for OS apart from windows


问:
Bootstrap form input does not allow for editing when clicked
Problem:
My bootstrap form does not allow for editing.

Details:
I am using a bootstrap form within a .thumbnail and the .caption class. I wanted very specific column sizing for each form-group which is why I used a nested grid system. When I click on an input absolutely nothing happens (literally nothing). However, when I connect a jQuery event listener to the input the event does indeed fire. Why does my form appear to be incapable of editing? Thank you in advance!

Web Development Application

    <form class="col-xs-12" method="post">

        First Name

          <input id="first-name" type="text" class="form-control" placeholder="John">

        Last Name

          <input id="last-name" type="text" class="form-control" placeholder="Doe" />

        Email Address

          <input id="apply-email" type="email" class="form-control" placeholder="johnnyappleseed@gmail.com" />

        LinkedIn

          <input id="linked-in" type="text" class="form-control" placeholder="mylinkedIn.com" />

        Portfolio

          <input id="portfolio" type="text" class="form-control" placeholder="mylinkedIn.com" />

        CV

                                Upload <input class="form-control" type="file">

              No file chosen...

          <button type="submit" class="submit-btn col-sm-4 col-sm-offset-8 btn btn-success btn-mini">Submit!</button>

    </form>

```

答:
I ended up figuring out a workaround. It isn't the best solution because it requires some jQuery/js and there has to be a way around the problem with the html structure. However, if someone else runs into a problem similar to this I came up with a quick jQuery workaround which places an event on each form-group to detect clicks and then brings the child input into focus.</p>

```<code>$("#application .form-group").on("click", function() {
  $(this).children('div').children('input').focus();
});
</code>```

Body:
I ended up figuring out a workaround. It isn't the best solution because it requires some jQuery/js and there has to be a way around the problem with the html structure. However, if someone else runs into a problem similar to this I came up with a quick jQuery workaround which places an event on each form-group to detect clicks and then brings the child input into focus.

$("#application .form-group").on("click", function() {
  $(this).children('div').children('input').focus();
});


问:
Line break on some Qtip tooltips
On this page: http://antidote.treethink.com/projects/
Some of the tooltips have a line break on them (#2, #8, #9, #10) in Firefox only
I would like to get rid of the line break on these but can't figure out why those have it and others (that are even longer) don't.

This problem isn't there in Safari.
I am using Qtip (http://craigsworks.com/projects/qtip/) and the code calling everything is:

```<code><script type="text/javascript">
$(document).ready(function()
{
   $('#post-11 a[title]').qtip({
      position: {
         corner: {
            target: 'topMiddle',
            tooltip: 'bottomMiddle'
         }
      },
      style: {
         name: 'dark',
         padding: '7px 13px',
         width: {
            max: 4000,
            min: 0
         },
         tip: true
      }
   });
});
</script>
</code>```

Thanks,
Wade

答:
I tried it in Firefox but none of them had linebreaks.
If you're still having this problem you could add the css</p>

```<code>#qtip-content{
    white-space:nowrap;
}
</code>```

Title: Line break on some Qtip tooltips

Body:
On this page: http://antidote.treethink.com/projects/
Some of the tooltips have a line break on them (#2, #8, #9, #10) in Firefox only
I would like to get rid of the line break on these but can't figure out why those have it and others (that are even longer) don't.

This problem isn't there in Safari.
I am using Qtip (http://craigsworks.com/projects/qtip/) and the code calling everything is:

Thanks,
Wade

Body:
I tried it in Firefox but none of them had linebreaks.
If you're still having this problem you could add the css

#qtip-content{
    white-space:nowrap;
}


问:
How do I list all the files in a commit?
How can I print a plain list of all files that were part of a given commit?

Although the following lists the files, it also includes unwanted diff information for each:

```<code>git show a303aa90779efdd2f6b9d90693e2cbbbe4613c1d
</code>```

答:
OK, there are a couple of ways to show all files in a particular commit...

To reduce the information and show only names of the files which committed, you simply can add --name-only or --name-status flag... These flags just show you the file names which are different from previous commits as you want...

So you can do git diff followed by --name-only, with two commit hashes after <sha0> <sha1>. Something like below:

```<code>git diff --name-only 5f12f15 kag9f02
</code>```

I also created the below image to show all steps to go through in these situations:

OwnerDisplayName: Philip Fourie

ContentLicense: CC BY-SA 4.0

Body:
How can I print a plain list of all files that were part of a given commit?

Although the following lists the files, it also includes unwanted diff information for each:

git show a303aa90779efdd2f6b9d90693e2cbbbe4613c1d

LastEditorDisplayName: Philip Fourie

Body:
OK, there are a couple of ways to show all files in a particular commit...

To reduce the information and show only names of the files which committed, you simply can add --name-only or --name-status flag... These flags just show you the file names which are different from previous commits as you want...

So you can do git diff followed by --name-only, with two commit hashes after <sha0> <sha1>. Something like below:

git diff --name-only 5f12f15 kag9f02

I also created the below image to show all steps to go through in these situations:


问:
How to set Proxy Authentication in seleniumWebdriver for Chrome Browser
I'm trying to Automate a web application selenium 2.0 [webdriver+java].The web application is currently deployed in our UAT servers on our local network.My test cases are executing, but I have to manually enter the Proxy Authentication details for my Chrome instance at the start of the test execution. I have tried all the solutions provided on stack overflow but still, the authentication message pops out.

This is the code I'm using in my driver initializing process

package com.misyn.ess.ui;

```<code>import java.util.Arrays;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

/**
 *
 * @author User
 */
public class DriverClass {

    private String baseUrl;
    private String driverPath;
    private String driverName;
    private static WebDriver driver;
    private static DriverClass driverClass;

        private DriverClass() {
            try {
                baseUrl = "http://192.168.0.10:8282/ess";
                driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
                driverName = "webdriver.chrome.driver";

                //Set the location of the ChromeDriver
            System.setProperty(driverName, driverPath);
            //Create a new desired capability
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            // Create a new proxy object and set the proxy
            Proxy proxy = new Proxy();
            proxy.setHttpProxy("192.168.0.200:3128");
            proxy.setSocksUsername("avishka");
            proxy.setSocksPassword("12345678");
            //Add the proxy to our capabilities
            capabilities.setCapability("proxy", proxy);
            //Start a new ChromeDriver using the capabilities object we created and added the proxy to
            driver = new ChromeDriver(capabilities);

            //Navigation to a url and a look at the traffic logged in fiddler
            driver.navigate().to(baseUrl);

    //            System.setProperty(driverName, driverPath);
    //            driver = new ChromeDriver();
    //            driver.get(baseUrl);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
</code>```

Can anyone give me a solution how to give this proxy username and password thing from the application itself than manually entering details on the pop-up(Authentication), any help would be much appreciated.Thanks

the currently answered one is only for

As of Selenium 3.4 it is still in beta
Right now implementation is only done for InternetExplorerDriver

Where I'm using selenium 3.0 and Google Chrome as my web browser.

答:
You can do via MultiPass for HTTP basic authentication

Download the extension from

https://chrome.google.com/webstore/detail/multipass-for-http-basic/enhldmjbphoeibbpdhmjkchohnidgnah

Download the extension as crx. You can get it as crx from chrome-extension-downloader

After that the config is simple.

```<code>import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

/**
 *
 * @author Phystem
 */
public class ChromeAuthTest {

    WebDriver driver;

    public ChromeAuthTest() {
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
    }

    private void initDriver() {
        ChromeOptions cOptions = new ChromeOptions();
        cOptions.addExtensions(new File("MultiPass-for-HTTP-basic-authentication_v.crx"));
        driver = new ChromeDriver(cOptions);
        configureAuth(
                "https://the-internet.herokuapp.com/basic_auth",
                "admin",
                "admin");
    }

    private void configureAuth(String url, String username, String password) {
        driver.get("chrome-extension://enhldmjbphoeibbpdhmjkchohnidgnah/options.html");
        driver.findElement(By.id("url")).sendKeys(url);
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).sendKeys(password);
        driver.findElement(By.className("credential-form-submit")).click();
    }

    public void doTest() {
        initDriver();
        driver.get("https://the-internet.herokuapp.com/basic_auth");
        System.out.println(driver.getTitle());
        driver.quit();
    }

    public static void main(String[] args) {
        new ChromeAuthTest().doTest();
    }
}
</code>```

I have used a sample site for testing.

Provide your url,username and password in the configure Auth function and try

Body:
I'm trying to Automate a web application selenium 2.0 [webdriver+java].The web application is currently deployed in our UAT servers on our local network.My test cases are executing, but I have to manually enter the Proxy Authentication details for my Chrome instance at the start of the test execution. I have tried all the solutions provided on stack overflow but still, the authentication message pops out.

This is the code I'm using in my driver initializing process

package com.misyn.ess.ui;

import java.util.Arrays;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

/**
 *
 * @author User
 */
public class DriverClass {

    private String baseUrl;
    private String driverPath;
    private String driverName;
    private static WebDriver driver;
    private static DriverClass driverClass;

        private DriverClass() {
            try {
                baseUrl = "http://192.168.0.10:8282/ess";
                driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
                driverName = "webdriver.chrome.driver";

                //Set the location of the ChromeDriver
            System.setProperty(driverName, driverPath);
            //Create a new desired capability
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            // Create a new proxy object and set the proxy
            Proxy proxy = new Proxy();
            proxy.setHttpProxy("192.168.0.200:3128");
            proxy.setSocksUsername("avishka");
            proxy.setSocksPassword("12345678");
            //Add the proxy to our capabilities
            capabilities.setCapability("proxy", proxy);
            //Start a new ChromeDriver using the capabilities object we created and added the proxy to
            driver = new ChromeDriver(capabilities);

            //Navigation to a url and a look at the traffic logged in fiddler
            driver.navigate().to(baseUrl);

    //            System.setProperty(driverName, driverPath);
    //            driver = new ChromeDriver();
    //            driver.get(baseUrl);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

Can anyone give me a solution how to give this proxy username and password thing from the application itself than manually entering details on the pop-up(Authentication), any help would be much appreciated.Thanks

the currently answered one is only for

As of Selenium 3.4 it is still in beta
Right now implementation is only done for InternetExplorerDriver

Where I'm using selenium 3.0 and Google Chrome as my web browser.

Body:
You can do via MultiPass for HTTP basic authentication

Download the extension from

https://chrome.google.com/webstore/detail/multipass-for-http-basic/enhldmjbphoeibbpdhmjkchohnidgnah

Download the extension as crx. You can get it as crx from chrome-extension-downloader

After that the config is simple.

import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

/**
 *
 * @author Phystem
 */
public class ChromeAuthTest {

    WebDriver driver;

    public ChromeAuthTest() {
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
    }

    private void initDriver() {
        ChromeOptions cOptions = new ChromeOptions();
        cOptions.addExtensions(new File("MultiPass-for-HTTP-basic-authentication_v.crx"));
        driver = new ChromeDriver(cOptions);
        configureAuth(
                "https://the-internet.herokuapp.com/basic_auth",
                "admin",
                "admin");
    }

    private void configureAuth(String url, String username, String password) {
        driver.get("chrome-extension://enhldmjbphoeibbpdhmjkchohnidgnah/options.html");
        driver.findElement(By.id("url")).sendKeys(url);
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).sendKeys(password);
        driver.findElement(By.className("credential-form-submit")).click();
    }

    public void doTest() {
        initDriver();
        driver.get("https://the-internet.herokuapp.com/basic_auth");
        System.out.println(driver.getTitle());
        driver.quit();
    }

    public static void main(String[] args) {
        new ChromeAuthTest().doTest();
    }
}

I have used a sample site for testing.

Provide your url,username and password in the configure Auth function and try


问:
How can I run computations on this "nested" structured array using Dask?
I'm trying to get started with dask.  In the toy example below, I have three columns, site, counts and readings.  site and counts are columns of scalars, whereas readings contains 3-dimensional arrays.

I can run computations on counts fine, but if I try to run them on readings, I get an exception.  Am I using dask correctly here?

```<code>import dask.array as da
import numpy as np
import tables

dtype = np.dtype([
    ('site', 'S1'),
    ('counts', np.int8),
    ('readings', np.float64, (2, 2, 3))
])

with tables.open_file('test.hdf5', 'w') as f:
    sensors = f.create_table('/', 'sensors', description=dtype)
    rows = [(site, count, np.random.rand(2, 2, 3))
            for count, site in enumerate('abcdefghij')]
    sensors.append(rows)
    sensors.flush()

    # Operating on 'counts' column works fine...
    x = da.from_array(f.root.sensors.cols.counts, chunks=5)
    x_add = (x + 1).compute()

    # But on 'readings' does not
    y = da.from_array(f.root.sensors.cols.readings, chunks=5)
    y_add = (y + 1).compute()
</code>```

At (y + 1).compute(), I get the following exception.  (The actual error at the bottom seems to be from building the error string for a TypeError in pytables, so it's not very helpful.)

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-115-77c7e132695c> in <module>()
     22     # But on readings column does not
     23     y = da.from_array(f.root.sensors.cols.readings, chunks=5)
---> 24     y_add = (y + 1).compute()

~/miniconda/lib/python3.6/site-packages/dask/base.py in compute(self, **kwargs)
     95             Extra keywords to forward to the scheduler ``get`` function.
     96         """
---> 97         (result,) = compute(self, traverse=False, **kwargs)
     98         return result
     99

~/miniconda/lib/python3.6/site-packages/dask/base.py in compute(*args, **kwargs)
    202     dsk = collections_to_dsk(variables, optimize_graph, **kwargs)
    203     keys = [var._keys() for var in variables]
--> 204     results = get(dsk, keys, **kwargs)
    205
    206     results_iter = iter(results)

~/miniconda/lib/python3.6/site-packages/dask/threaded.py in get(dsk, result, cache, num_workers, **kwargs)
     73     results = get_async(pool.apply_async, len(pool._pool), dsk, result,
     74                         cache=cache, get_id=_thread_get_id,
---> 75                         pack_exception=pack_exception, **kwargs)
     76
     77     # Cleanup pools associated to dead threads

~/miniconda/lib/python3.6/site-packages/dask/local.py in get_async(apply_async, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, **kwargs)
    519                         _execute_task(task, data)  # Re-execute locally
    520                     else:
--> 521                         raise_exception(exc, tb)
    522                 res, worker_id = loads(res_info)
    523                 state['cache'][key] = res

~/miniconda/lib/python3.6/site-packages/dask/compatibility.py in reraise(exc, tb)
     58         if exc.__traceback__ is not tb:
     59             raise exc.with_traceback(tb)
---> 60         raise exc
     61
     62 else:

~/miniconda/lib/python3.6/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)
    288     try:
    289         task, data = loads(task_info)
--> 290         result = _execute_task(task, data)
    291         id = get_id()
    292         result = dumps((result, id))

~/miniconda/lib/python3.6/site-packages/dask/local.py in _execute_task(arg, cache, dsk)
    269         func, args = arg[0], arg[1:]
    270         args2 = [_execute_task(a, cache) for a in args]
--> 271         return func(*args2)
    272     elif not ishashable(arg):
    273         return arg

~/miniconda/lib/python3.6/site-packages/dask/array/core.py in getarray(a, b, lock)
     61         lock.acquire()
     62     try:
---> 63         c = a[b]
     64         if type(c) != np.ndarray:
     65             c = np.asarray(c)

~/miniconda/lib/python3.6/site-packages/tables/table.py in __getitem__(self, key)
   3455         else:
   3456             raise TypeError(
-> 3457                 "'%s' key type is not valid in this context" % key)
   3458
   3459     def __iter__(self):

TypeError: not all arguments converted during string formatting
</code>```

And finally, the value of x_add is array([ 6,  7,  8,  9, 10,  6,  7,  8,  9, 10], dtype=int8), which is +1 on the last chunk tiled twice.  I would expect [1, 2, ..., 10].  Again, makes me wonder if I'm using dask as intended.

答:
Dask.array expects arrays given to it to follow numpy-style slicing.  It looks like PyTables doesn't support this.

```<code>In [12]: f.root.sensors.cols.counts
Out[12]: /sensors.cols.counts (Column(10,), int8, idx=None)

In [13]: f.root.sensors.cols.counts[:]
Out[13]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int8)

In [14]: f.root.sensors.cols.readings
Out[14]: /sensors.cols.readings (Column(10, 2, 2, 3), float64, idx=None)

In [15]: f.root.sensors.cols.counts[:, :, :, :]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-5e59d077075e> in <module>()
----> 1 f.root.sensors.cols.counts[:, :, :, :]

/home/mrocklin/Software/anaconda/lib/python3.6/site-packages/tables/table.py in __getitem__(self, key)
   3453         else:
   3454             raise TypeError(
-> 3455                 "'%s' key type is not valid in this context" % key)
   3456
   3457     def __iter__(self):

TypeError: not all arguments converted during string formatting
</code>```

I recommend trying h5py instead if that works for you.  I've generally found that h5py is a bit more sensible than PyTables.

Body:
I'm trying to get started with dask.  In the toy example below, I have three columns, site, counts and readings.  site and counts are columns of scalars, whereas readings contains 3-dimensional arrays.

I can run computations on counts fine, but if I try to run them on readings, I get an exception.  Am I using dask correctly here?

import dask.array as da
import numpy as np
import tables

dtype = np.dtype([
    ('site', 'S1'),
    ('counts', np.int8),
    ('readings', np.float64, (2, 2, 3))
])

with tables.open_file('test.hdf5', 'w') as f:
    sensors = f.create_table('/', 'sensors', description=dtype)
    rows = [(site, count, np.random.rand(2, 2, 3))
            for count, site in enumerate('abcdefghij')]
    sensors.append(rows)
    sensors.flush()

    # Operating on 'counts' column works fine...
    x = da.from_array(f.root.sensors.cols.counts, chunks=5)
    x_add = (x + 1).compute()

    # But on 'readings' does not
    y = da.from_array(f.root.sensors.cols.readings, chunks=5)
    y_add = (y + 1).compute()

At (y + 1).compute(), I get the following exception.  (The actual error at the bottom seems to be from building the error string for a TypeError in pytables, so it's not very helpful.)

TypeError                                 Traceback (most recent call last)
<ipython-input-115-77c7e132695c> in <module>()
     22     # But on readings column does not
     23     y = da.from_array(f.root.sensors.cols.readings, chunks=5)
---> 24     y_add = (y + 1).compute()

~/miniconda/lib/python3.6/site-packages/dask/base.py in compute(self, **kwargs)
     95             Extra keywords to forward to the scheduler ``get`` function.
     96         """
---> 97         (result,) = compute(self, traverse=False, **kwargs)
     98         return result
     99

~/miniconda/lib/python3.6/site-packages/dask/base.py in compute(*args, **kwargs)
    202     dsk = collections_to_dsk(variables, optimize_graph, **kwargs)
    203     keys = [var._keys() for var in variables]
--> 204     results = get(dsk, keys, **kwargs)
    205
    206     results_iter = iter(results)

~/miniconda/lib/python3.6/site-packages/dask/threaded.py in get(dsk, result, cache, num_workers, **kwargs)
     73     results = get_async(pool.apply_async, len(pool._pool), dsk, result,
     74                         cache=cache, get_id=_thread_get_id,
---> 75                         pack_exception=pack_exception, **kwargs)
     76
     77     # Cleanup pools associated to dead threads

~/miniconda/lib/python3.6/site-packages/dask/local.py in get_async(apply_async, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, **kwargs)
    519                         _execute_task(task, data)  # Re-execute locally
    520                     else:
--> 521                         raise_exception(exc, tb)
    522                 res, worker_id = loads(res_info)
    523                 state['cache'][key] = res

~/miniconda/lib/python3.6/site-packages/dask/compatibility.py in reraise(exc, tb)
     58         if exc.__traceback__ is not tb:
     59             raise exc.with_traceback(tb)
---> 60         raise exc
     61
     62 else:

~/miniconda/lib/python3.6/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)
    288     try:
    289         task, data = loads(task_info)
--> 290         result = _execute_task(task, data)
    291         id = get_id()
    292         result = dumps((result, id))

~/miniconda/lib/python3.6/site-packages/dask/local.py in _execute_task(arg, cache, dsk)
    269         func, args = arg[0], arg[1:]
    270         args2 = [_execute_task(a, cache) for a in args]
--> 271         return func(*args2)
    272     elif not ishashable(arg):
    273         return arg

~/miniconda/lib/python3.6/site-packages/dask/array/core.py in getarray(a, b, lock)
     61         lock.acquire()
     62     try:
---> 63         c = a[b]
     64         if type(c) != np.ndarray:
     65             c = np.asarray(c)

~/miniconda/lib/python3.6/site-packages/tables/table.py in __getitem__(self, key)
   3455         else:
   3456             raise TypeError(
-> 3457                 "'%s' key type is not valid in this context" % key)
   3458
   3459     def __iter__(self):

TypeError: not all arguments converted during string formatting

And finally, the value of x_add is array([ 6,  7,  8,  9, 10,  6,  7,  8,  9, 10], dtype=int8), which is +1 on the last chunk tiled twice.  I would expect [1, 2, ..., 10].  Again, makes me wonder if I'm using dask as intended.

Body:
Dask.array expects arrays given to it to follow numpy-style slicing.  It looks like PyTables doesn't support this.

In [12]: f.root.sensors.cols.counts
Out[12]: /sensors.cols.counts (Column(10,), int8, idx=None)

In [13]: f.root.sensors.cols.counts[:]
Out[13]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int8)

In [14]: f.root.sensors.cols.readings
Out[14]: /sensors.cols.readings (Column(10, 2, 2, 3), float64, idx=None)

In [15]: f.root.sensors.cols.counts[:, :, :, :]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-5e59d077075e> in <module>()
----> 1 f.root.sensors.cols.counts[:, :, :, :]

/home/mrocklin/Software/anaconda/lib/python3.6/site-packages/tables/table.py in __getitem__(self, key)
   3453         else:
   3454             raise TypeError(
-> 3455                 "'%s' key type is not valid in this context" % key)
   3456
   3457     def __iter__(self):

TypeError: not all arguments converted during string formatting

I recommend trying h5py instead if that works for you.  I've generally found that h5py is a bit more sensible than PyTables.


问:
Delete content between 2 lines
I have a pacfile which I am trying to update and need to remove content between two strings; the strings themselves should be kept:

```<code> // OFFICE 365 DIRECT ACCESS
</code>```

and

```<code>// END OFFICE 365 DIRECT ACCESS
</code>```

example:

```<code>// OFFICE 365 DIRECT ACCESS
  if (isInNet(hostip, "23.103.132.0","255.255.252.0") ||    //EOP
  isInNet(hostip, "23.103.136.0","255.255.248.0") ||    //EOP
  isInNet(hostip, "23.103.144.0","255.255.240.0") ||    //EOP
  isInNet(hostip, "23.103.191.0","255.255.255.0") ||    //EOP
// END OFFICE 365 DIRECT ACCESS
</code>```

I want to remove the lines between the top and bottom lines

```<code>$Pacfile = Get-ChildItem .\o365.pac | Get-Content -Raw
$startstring= " \/\/ OFFICE 365 DIRECT ACCESS(.*? )\/\/END OFFICE 365 DIRECT ACCESS"
$NewPacfile = [regex]::match($Pacfile, $startstring).Groups[1].value
$NewPacfile
</code>```

答:
```<code>$regex=@'
(?ms)^(\s*// OFFICE 365 DIRECT ACCESS\s*?\r?\n).*?\r?\n(\s*// END OFFICE 365 DIRECT ACCESS\s*)
'@
(Get-Content -Raw .\o365.pac) -replace $regex, '$1$2'
</code>```

-replace $regex, '$1$2' replaces what the regex matched with what the 1st ($1) and 2nd capture groups ($2) (parenthesized subexpression, (...)) inside of it matched.

Here, these capture groups capture the strings enclosing the range of interest.

(?ms) sets both the multi-line and the single-line option for the regex:

m means that ^ and $ should match the start and end of each line rather than the input string as a whole.

s means that metacharacter . should match \n characters too, so that an expression such as .* can be used to match across lines.

\r?\n matches a single line break, both the CRLF and the LF variety.

.*? matches the part to remove; note the non-greedy modifier (?) following .*, which ensures that the next occurrence of the end string is matched.

Title: Delete content between 2 lines

Body:
I have a pacfile which I am trying to update and need to remove content between two strings; the strings themselves should be kept:

 // OFFICE 365 DIRECT ACCESS

and

// END OFFICE 365 DIRECT ACCESS

example:

// OFFICE 365 DIRECT ACCESS
  if (isInNet(hostip, "23.103.132.0","255.255.252.0") ||    //EOP
  isInNet(hostip, "23.103.136.0","255.255.248.0") ||    //EOP
  isInNet(hostip, "23.103.144.0","255.255.240.0") ||    //EOP
  isInNet(hostip, "23.103.191.0","255.255.255.0") ||    //EOP
// END OFFICE 365 DIRECT ACCESS

I want to remove the lines between the top and bottom lines

$Pacfile = Get-ChildItem .\o365.pac | Get-Content -Raw
$startstring= " \/\/ OFFICE 365 DIRECT ACCESS(.*? )\/\/END OFFICE 365 DIRECT ACCESS"
$NewPacfile = [regex]::match($Pacfile, $startstring).Groups[1].value
$NewPacfile

Body:
$regex=@'
(?ms)^(\s*// OFFICE 365 DIRECT ACCESS\s*?\r?\n).*?\r?\n(\s*// END OFFICE 365 DIRECT ACCESS\s*)
'@
(Get-Content -Raw .\o365.pac) -replace $regex, '$1$2'

-replace $regex, '$1$2' replaces what the regex matched with what the 1st ($1) and 2nd capture groups ($2) (parenthesized subexpression, (...)) inside of it matched.

Here, these capture groups capture the strings enclosing the range of interest.

(?ms) sets both the multi-line and the single-line option for the regex:

m means that ^ and $ should match the start and end of each line rather than the input string as a whole.

s means that metacharacter . should match \n characters too, so that an expression such as .* can be used to match across lines.

\r?\n matches a single line break, both the CRLF and the LF variety.

.*? matches the part to remove; note the non-greedy modifier (?) following .*, which ensures that the next occurrence of the end string is matched.


问:
Multiple database connection in classic ASP with SQL 2008
I have a page (default.asp) where as of right now i need to connect data from two different databases. My problem is I keep getting this error

"Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."

Before adding the following connection my site worked fine from a the includes file connection..I found out it does error out on conn.Open

```<code> <%
       Set conn = Server.CreateObject("ADODB.Connection")
       conn.ConnectionString = "Provider=SQLNCLI10.1;Integrated Security=True;Persist Security Info=False;Initial Catalog=member;Data Source=608;"
       conn.Open
       conn.Close
 %>
</code>```

Any suggestions as to what I can do here? Ps this one is hardcoded into the page itself.

答:
That is a very common error message, you need to check the errors collection on the connection, something like this should give you more info:</p>

```<code><%
for each objErr in objConn.Errors
  response.write("<p>")
  response.write("Description: ")
  response.write(objErr.Description & "<br />")
  response.write("Help context: ")
  response.write(objErr.HelpContext & "<br />")
  response.write("Help file: ")
  response.write(objErr.HelpFile & "<br />")
  response.write("Native error: ")
  response.write(objErr.NativeError & "<br />")
  response.write("Error number: ")
  response.write(objErr.Number & "<br />")
  response.write("Error source: ")
  response.write(objErr.Source & "<br />")
  response.write("SQL state: ")
  response.write(objErr.SQLState & "<br />")
  response.write("</p>")
next
%>
</code>```

Body:
I have a page (default.asp) where as of right now i need to connect data from two different databases. My problem is I keep getting this error

"Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."

Before adding the following connection my site worked fine from a the includes file connection..I found out it does error out on conn.Open

 <%
       Set conn = Server.CreateObject("ADODB.Connection")
       conn.ConnectionString = "Provider=SQLNCLI10.1;Integrated Security=True;Persist Security Info=False;Initial Catalog=member;Data Source=608;"
       conn.Open
       conn.Close
 %>

Any suggestions as to what I can do here? Ps this one is hardcoded into the page itself.

Body:
That is a very common error message, you need to check the errors collection on the connection, something like this should give you more info:

<%
for each objErr in objConn.Errors
  response.write("<p>")
  response.write("Description: ")
  response.write(objErr.Description & "<br />")
  response.write("Help context: ")
  response.write(objErr.HelpContext & "<br />")
  response.write("Help file: ")
  response.write(objErr.HelpFile & "<br />")
  response.write("Native error: ")
  response.write(objErr.NativeError & "<br />")
  response.write("Error number: ")
  response.write(objErr.Number & "<br />")
  response.write("Error source: ")
  response.write(objErr.Source & "<br />")
  response.write("SQL state: ")
  response.write(objErr.SQLState & "<br />")
  response.write("</p>")
next
%>


问:
C++ regex: Which group matched?
I have a regex containig various sub-groups which are connected through an or condition:

```<code>([[:alpha:]]+)|([[:digit:]]+)
</code>```

When I match the string 1 a 2, I get three matches: 1, a and 2.

Is there a way in C++ to determine which of the sub-patterns matched?

答:
Not directly.

with the std::regex library, match_result class takes care of the sub-match and it has a method named std::match_results::size and with that you can find the number of sub-match.

Ex:

```<code>std::string str( "one two three four five" );
std::regex rx( "(\\w+)(\\w+)(\\w+)(\\w+)(\\w+)" );
std::match_results< std::string::const_iterator > mr;

std::regex_search( str, mr, rx );

std::cout << mr.size() << '\n'; // 6
</code>```

here the output is 6 not 5 because the match itself is counted as well. You can access them by .str( number ) method or operator[]

So because sub-match are counted form left-to-right you should after seeing the output of size method figure out witch group was matched.

If you change the rx to "(\\w+)(\\d+)(\\w+)" then the size = 0

If you change the rx to "(\\w+).+" then the size is 2. That means you have a whole successful match and a sum-match

Ex:

```<code>std::string str( "one two three four five" );
std::regex rx( "(\\w+).+" );
std::match_results< std::string::const_iterator > mr;

std::regex_search( str, mr, rx );

std::cout << mr.str( 1 ) << '\n'; // one
std::cout << mr[ 1 ] << '\n';     // one
</code>```

the output for both is: one

And also if you want to print only the sub-match you can use a simple loop that has an index and this index starts from 1 not 0

Ex:

```<code>std::string str( "one two three four five" );
std::regex rx( "(\\w+) \\w+ (\\w+) \\w+ (\\w+)" );
std::match_results< std::string::const_iterator > mr;

std::regex_search( str, mr, rx );

for( std::size_t index = 1; index < mr.size(); ++index ){
    std::cout << mr[ index ] << '\n';
}
</code>```

the output is:

```<code>one
three
five
</code>```

By saying determine which of the sub-patterns matched

if you mean specify which sub-match should be return from the search-engine then the answer is yes by using std::regex_token_iterator you can determine that:

Ex: (Iterate over second sub-match of each match )

```<code>std::string str( "How are you today ? I am fine . How about you ?" );
std::regex rx( "(\\w+) (\\w+) ?" );
std::match_results< std::string::const_iterator > mr;

std::regex_token_iterator< std::string::const_iterator > first( str.begin(), str.end(), rx, 2 ), last;

while( first != last ){
    std::cout << first->str() << '\n';
    ++first;
}
</code>```

the last parameter is 2 : ( str.begin(), str.end(), rx, 2 ) and it means you want only the second sub-match. So the output is:

```<code>are
today
am
about
</code>```

Title: C++ regex: Which group matched?

Body:
I have a regex containig various sub-groups which are connected through an or condition:

([[:alpha:]]+)|([[:digit:]]+)

When I match the string 1 a 2, I get three matches: 1, a and 2.

Is there a way in C++ to determine which of the sub-patterns matched?

Body:
Not directly.

with the std::regex library, match_result class takes care of the sub-match and it has a method named std::match_results::size and with that you can find the number of sub-match.

Ex:

std::string str( "one two three four five" );
std::regex rx( "(\\w+)(\\w+)(\\w+)(\\w+)(\\w+)" );
std::match_results< std::string::const_iterator > mr;

std::regex_search( str, mr, rx );

std::cout << mr.size() << '\n'; // 6

here the output is 6 not 5 because the match itself is counted as well. You can access them by .str( number ) method or operator[]

So because sub-match are counted form left-to-right you should after seeing the output of size method figure out witch group was matched.

If you change the rx to "(\\w+)(\\d+)(\\w+)" then the size = 0

If you change the rx to "(\\w+).+" then the size is 2. That means you have a whole successful match and a sum-match

Ex:

std::string str( "one two three four five" );
std::regex rx( "(\\w+).+" );
std::match_results< std::string::const_iterator > mr;

std::regex_search( str, mr, rx );

std::cout << mr.str( 1 ) << '\n'; // one
std::cout << mr[ 1 ] << '\n';     // one

the output for both is: one

And also if you want to print only the sub-match you can use a simple loop that has an index and this index starts from 1 not 0

Ex:

std::string str( "one two three four five" );
std::regex rx( "(\\w+) \\w+ (\\w+) \\w+ (\\w+)" );
std::match_results< std::string::const_iterator > mr;

std::regex_search( str, mr, rx );

for( std::size_t index = 1; index < mr.size(); ++index ){
    std::cout << mr[ index ] << '\n';
}

the output is:

one
three
five

By saying determine which of the sub-patterns matched

if you mean specify which sub-match should be return from the search-engine then the answer is yes by using std::regex_token_iterator you can determine that:

Ex: (Iterate over second sub-match of each match )

std::string str( "How are you today ? I am fine . How about you ?" );
std::regex rx( "(\\w+) (\\w+) ?" );
std::match_results< std::string::const_iterator > mr;

std::regex_token_iterator< std::string::const_iterator > first( str.begin(), str.end(), rx, 2 ), last;

while( first != last ){
    std::cout << first->str() << '\n';
    ++first;
}

the last parameter is 2 : ( str.begin(), str.end(), rx, 2 ) and it means you want only the second sub-match. So the output is:

are
today
am
about


问:
jQuery $(this).nextUntil('h3').toggle(); - hidden ul inside an ul
I'm struggling for two days now on how to toggle specific content for my first project (started coding about a week ago, so I'm a newbie). I have searched other topics and read articles/done tutorials, and they helped me in the right direction, but I'm still not there yet. Who knows how to tackle this?

Goal:
Only the h3s should be visible when the page loads. When I click on h3, I want everything until the next h3 to toggle (thus, the ul and the 'sub' ul).

Current situation: List Items 1 and 2 toggle, but the Sublist items are not (they stay hidden).

```<code><div>
<h3>Heading</h3>
  <ul>
    <li>List item 1</li>
      <ul>
       <li>Sublist item 1</li>
       <li>Sublist item 2</li>
      </ul>
    <li>List item 2</li>
      <ul>
        <li></li>
      </ul>
  </ul>
<h3>Next heading</h3>
...
</div>
</code>```

This is the jQuery code:

```<code> $(document).ready(function() {
   $('h3').click(function() {
     $(this).nextUntil('h3').toggle();
   });
 });
</code>```

And the CSS that hides the ul when the page loads:

```<code>ul {
  display: none;
  visibility: inherit;
}
</code>```

I think the problem is in my CSS (because List Item 2 does load), but after two days I'm still not able to fix it. Who can help me?

答:
```<code> Please try this one.
</code>```

 $(document).ready(function() {
   $('h3').click(function() {
     $(this).nextUntil('h3').toggle();
   });
 });
 ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  display: none;
  visibility: inherit;
}</code>```

Heading

List item 1

Sublist item 1

Sublist item 2

List item 2

Next heading

List item 3

Sublist item 3

Sublist item 4

List item 4

```

Body:
I'm struggling for two days now on how to toggle specific content for my first project (started coding about a week ago, so I'm a newbie). I have searched other topics and read articles/done tutorials, and they helped me in the right direction, but I'm still not there yet. Who knows how to tackle this?

Goal:
Only the h3s should be visible when the page loads. When I click on h3, I want everything until the next h3 to toggle (thus, the ul and the 'sub' ul).

Current situation: List Items 1 and 2 toggle, but the Sublist items are not (they stay hidden).

Heading

List item 1

Sublist item 1

Sublist item 2

List item 2

Next heading

...

This is the jQuery code:

 $(document).ready(function() {
   $('h3').click(function() {
     $(this).nextUntil('h3').toggle();
   });
 });

And the CSS that hides the ul when the page loads:

ul {
  display: none;
  visibility: inherit;
}

I think the problem is in my CSS (because List Item 2 does load), but after two days I'm still not able to fix it. Who can help me?

Body:
 Please try this one.

 $(document).ready(function() {
   $('h3').click(function() {
     $(this).nextUntil('h3').toggle();
   });
 });

ul {
  display: none;
  visibility: inherit;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
<h3>Heading</h3>
  <ul>
    <li>List item 1</li>
      <ul>
       <li>Sublist item 1</li>
       <li>Sublist item 2</li>
      </ul>
    <li>List item 2</li>
      <ul>
        <li></li>
      </ul>
  </ul>
<h3>Next heading</h3>
<ul>
    <li>List item 3</li>
      <ul>
       <li>Sublist item 3</li>
       <li>Sublist item 4</li>
      </ul>
    <li>List item 4</li>
      <ul>
        <li></li>
      </ul>
  </ul>
</div>


问:
No rows found, C# using OleDB
I have been rewriting a C# program to better encapsulate accessing an Access database, using OleDb.  It runs, but doesn't find the row that exists, but running the SQL query in Access does find it.

The question is: what is wrong with my code?  Why don't I get any rows returned?

I'm using VS 2017 and Access 2013.  The PC is an up-to-date windows 10 x64 machine.

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;

namespace OleDbTest
{
    class Program
    {
        static void Main( string[] args )
        {
            // Create Profile File object
            ProcessEJFile EJP = new ProcessEJFile(
                "Provider=Microsoft.ACE.OLEDB.12.0;" +
                @"Data Source=E:\Users\sallyw\Documents\Bar.accdb;" +
                "Persist Security Info=False;");

            // Get details of last header - this should return just one row
            string query =
            //      @"select * from stock_head where sh_ref in ( select max( stock_head.[ sh_ref ] ) FROM stock_head WHERE sh_ref like ""[#]%"")";

                    "select sh_id, sh_ref, sh_lineno, sh_type, sh_supplier, sh_datetime from stock_head where sh_id = 19;";

            //      "select * from stock_head where sh_ref = 19;"

            List<StockHead> shlist = EJP.GetStockHead(query, null );
            if ( shlist == null )
            {
                Console.WriteLine( "shlist is null" );
            }
            else
            {
                Console.WriteLine( "shlist contains {0} entries", shlist.Count );
            }
            Console.ReadLine();
        }
    }

    class ProcessEJFile
    {
        AccessDatabase Accdb = null;

        public ProcessEJFile( string connectionString )
        {
            Accdb = new AccessDatabase( connectionString );
            Console.WriteLine( "ProfessEJFile #1 - connection string = {0}", connectionString );
        }

        public List<StockHead> GetStockHead( string sql, params object[] args )
        {
            DataTable t;
            if ( args == null )
            {
                Console.WriteLine( "GetStockHead #1 - args are NULL " );
            }
            else
            {
                Console.WriteLine( "GetStockHead #2 - {0} arguments passed", args.Count() );
            }

            Accdb.ExecuteQuery( out t, sql, args );

            if ( t != null )
            {
                List<StockHead> shlist = new List<StockHead>();

                foreach ( DataRow r in t.Rows )
                {
                    Console.WriteLine( t.ToString() );
                    //StockHead sh = new StockHead(
                    //    (int)r["sh_id"],
                    //    (string)r["sh_ref"],
                    //    (int)r["sh_lineno"],
                    //    (string)r["sh_type"],
                    //    (string)r["sh_supplier"],
                    //    (DateTime)r["sh_datetime"]);
                    //shlist.Add( sh );
                }
                return shlist;
            }
            else
            {
                Console.WriteLine( "GetStockHead #3 - t is null" );
                return null;
            }
        }
    }
    class AccessDatabase
    {
        public OleDbConnection conn = new OleDbConnection();

        public AccessDatabase( string connection )
        {
            conn.ConnectionString = connection;
        }

        public bool OpenDatabase()
        {
            try
            {
                conn.Open();
            }
            catch ( Exception ex )
            {
                Console.WriteLine( "OpenDatabase()\n" + ex.Message );
                return false;
            }
            return true;
        }

        public void CloseDatabase()
        {
            if ( conn == null )
                return;

            conn.Close();
        }

        public void ExecuteQuery( out DataTable dataTable, string sql, params object[] args )
        {
            dataTable = new DataTable();
            string query;

            // Simplified version not validating or cleaning arguments in any way
            if (args == null )
            {
                query = sql;
            }
            else
            {
                query = string.Format( sql, args );
            }
            Console.WriteLine( "ExecuteQuery #3 - query = '{0}'", query );

            if ( OpenDatabase() )
            {
                OleDbCommand command = new OleDbCommand( query, conn );
                OleDbDataAdapter adapter = new OleDbDataAdapter( command );
                adapter.Fill( dataTable );
            }
            else
            {
                Console.WriteLine( "ExecuteQuery #9 - cannot open database" );
            }
        }
    }

    class StockHead
    {
        public int sh_id;              // autonumber
        public string sh_ref;          // short text
        public int sh_lineno;          // Number
        public string sh_type;         // short text
        public string sh_supplier;     // short text
        public DateTime sh_datetime;   // date/time

        public StockHead( int id, string refno, int lineno, string type, string supplier, DateTime datetime )
        {
            sh_id = id;
            sh_ref = refno;
            sh_lineno = lineno;
            sh_type = type;
            sh_supplier = supplier;
            sh_datetime = datetime;
        }
    }
}
</code>```

Data in CSV format, class stock_head shows the Access column types:

```<code>1,"#000001",,"IR","INITIAL RESET",20/8/2013 08:33:00
2,"#000002",,"SD","FORMATTING",20/8/2013 08:34:00
3,"#000003",,"SD","FOLDER CREATE",20/8/2013 08:35:00
4,"#000004",,"SD","FOLDER SELECT",20/8/2013 08:35:00
5,"#000005",,"NS","NO SALE",20/8/2013 11:14:00
6,"#000006",,"NS","NO SALE",20/8/2013 11:46:00
7,"#000007",,"NS","NO SALE",20/8/2013 12:16:00
8,"#000008",,"SALE",,20/8/2013 15:11:00
9,"#000009",,"SALE",,20/8/2013 15:30:00
10,"#000010",,"Z1",,20/8/2013 15:32:00
11,"#000011",,"NS","NO SALE",20/8/2013 15:32:00
12,"#000012",,"SALE",,20/8/2013 16:46:00
13,"#000013",,"SALE",,20/8/2013 16:47:00
14,"#000014",,"SALE",,20/8/2013 17:32:00
15,"#000015",,"Z1",,20/8/2013 19:25:00
16,"#000016",,"NS","NO SALE",20/8/2013 19:25:00
17,"#000017",,"Z1",,20/8/2013 21:52:00
18,"#000018",,"NS","NO SALE",20/8/2013 21:52:00
19,"#000019",,"SALE",,23/8/2013 18:27:00
20,"#000020",,"SALE",,23/8/2013 19:06:00
21,"#000021",,"SALE",,23/8/2013 20:24:00
22,"#000022",,"SALE",,23/8/2013 20:36:00
23,"#000023",,"SALE",,23/8/2013 21:21:00
24,"#000024",,"SALE",,23/8/2013 21:57:00
25,"#000025",,"SALE",,23/8/2013 22:38:00
26,"#000026",,"Z1",,23/8/2013 22:40:00
27,"#000027",,"NS","NO SALE",23/8/2013 22:40:00
28,"#000028",,"SALE",,24/8/2013 16:09:00
29,"#000029",,"SALE",,24/8/2013 16:28:00
30,"#000030",,"SALE",,24/8/2013 16:58:00
</code>```

答:
OK found a fix by amending the StockHead constructor to take the DataRow rather than individual arguments, and checking for any nulls there.

Is it a good way?  Is there a better way?  In a way I like it more as the complications are more tucked away - the line that calls it is now simply

StockHead sh = new StockHead( r );

Constructor code is now:

```<code>    public StockHead( DataRow row )
    {
        this.sh_id = (int)row[ "sh_id" ];
        this.sh_ref = (string)row[ "sh_ref" ];
        if ( !string.IsNullOrEmpty( row[ "sh_lineno" ].ToString() ) )
        {
            this.sh_lineno = (int)row[ "sh_lineno" ];
        }
        this.sh_type = (string)row[ "sh_type" ];
        if ( !string.IsNullOrEmpty( row[ "sh_lineno" ].ToString() ) )
        {
            this.sh_supplier = (string)row[ "sh_supplier" ];
        }
        this.sh_datetime = (DateTime)row[ "sh_datetime" ];
    }
</code>```

Title: No rows found, C# using OleDB

Body:
I have been rewriting a C# program to better encapsulate accessing an Access database, using OleDb.  It runs, but doesn't find the row that exists, but running the SQL query in Access does find it.

The question is: what is wrong with my code?  Why don't I get any rows returned?

I'm using VS 2017 and Access 2013.  The PC is an up-to-date windows 10 x64 machine.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;

namespace OleDbTest
{
    class Program
    {
        static void Main( string[] args )
        {
            // Create Profile File object
            ProcessEJFile EJP = new ProcessEJFile(
                "Provider=Microsoft.ACE.OLEDB.12.0;" +
                @"Data Source=E:\Users\sallyw\Documents\Bar.accdb;" +
                "Persist Security Info=False;");

            // Get details of last header - this should return just one row
            string query =
            //      @"select * from stock_head where sh_ref in ( select max( stock_head.[ sh_ref ] ) FROM stock_head WHERE sh_ref like ""[#]%"")";

                    "select sh_id, sh_ref, sh_lineno, sh_type, sh_supplier, sh_datetime from stock_head where sh_id = 19;";

            //      "select * from stock_head where sh_ref = 19;"

            List<StockHead> shlist = EJP.GetStockHead(query, null );
            if ( shlist == null )
            {
                Console.WriteLine( "shlist is null" );
            }
            else
            {
                Console.WriteLine( "shlist contains {0} entries", shlist.Count );
            }
            Console.ReadLine();
        }
    }

    class ProcessEJFile
    {
        AccessDatabase Accdb = null;

        public ProcessEJFile( string connectionString )
        {
            Accdb = new AccessDatabase( connectionString );
            Console.WriteLine( "ProfessEJFile #1 - connection string = {0}", connectionString );
        }

        public List<StockHead> GetStockHead( string sql, params object[] args )
        {
            DataTable t;
            if ( args == null )
            {
                Console.WriteLine( "GetStockHead #1 - args are NULL " );
            }
            else
            {
                Console.WriteLine( "GetStockHead #2 - {0} arguments passed", args.Count() );
            }

            Accdb.ExecuteQuery( out t, sql, args );

            if ( t != null )
            {
                List<StockHead> shlist = new List<StockHead>();

                foreach ( DataRow r in t.Rows )
                {
                    Console.WriteLine( t.ToString() );
                    //StockHead sh = new StockHead(
                    //    (int)r["sh_id"],
                    //    (string)r["sh_ref"],
                    //    (int)r["sh_lineno"],
                    //    (string)r["sh_type"],
                    //    (string)r["sh_supplier"],
                    //    (DateTime)r["sh_datetime"]);
                    //shlist.Add( sh );
                }
                return shlist;
            }
            else
            {
                Console.WriteLine( "GetStockHead #3 - t is null" );
                return null;
            }
        }
    }
    class AccessDatabase
    {
        public OleDbConnection conn = new OleDbConnection();

        public AccessDatabase( string connection )
        {
            conn.ConnectionString = connection;
        }

        public bool OpenDatabase()
        {
            try
            {
                conn.Open();
            }
            catch ( Exception ex )
            {
                Console.WriteLine( "OpenDatabase()\n" + ex.Message );
                return false;
            }
            return true;
        }

        public void CloseDatabase()
        {
            if ( conn == null )
                return;

            conn.Close();
        }

        public void ExecuteQuery( out DataTable dataTable, string sql, params object[] args )
        {
            dataTable = new DataTable();
            string query;

            // Simplified version not validating or cleaning arguments in any way
            if (args == null )
            {
                query = sql;
            }
            else
            {
                query = string.Format( sql, args );
            }
            Console.WriteLine( "ExecuteQuery #3 - query = '{0}'", query );

            if ( OpenDatabase() )
            {
                OleDbCommand command = new OleDbCommand( query, conn );
                OleDbDataAdapter adapter = new OleDbDataAdapter( command );
                adapter.Fill( dataTable );
            }
            else
            {
                Console.WriteLine( "ExecuteQuery #9 - cannot open database" );
            }
        }
    }

    class StockHead
    {
        public int sh_id;              // autonumber
        public string sh_ref;          // short text
        public int sh_lineno;          // Number
        public string sh_type;         // short text
        public string sh_supplier;     // short text
        public DateTime sh_datetime;   // date/time

        public StockHead( int id, string refno, int lineno, string type, string supplier, DateTime datetime )
        {
            sh_id = id;
            sh_ref = refno;
            sh_lineno = lineno;
            sh_type = type;
            sh_supplier = supplier;
            sh_datetime = datetime;
        }
    }
}

Data in CSV format, class stock_head shows the Access column types:

1,"#000001",,"IR","INITIAL RESET",20/8/2013 08:33:00
2,"#000002",,"SD","FORMATTING",20/8/2013 08:34:00
3,"#000003",,"SD","FOLDER CREATE",20/8/2013 08:35:00
4,"#000004",,"SD","FOLDER SELECT",20/8/2013 08:35:00
5,"#000005",,"NS","NO SALE",20/8/2013 11:14:00
6,"#000006",,"NS","NO SALE",20/8/2013 11:46:00
7,"#000007",,"NS","NO SALE",20/8/2013 12:16:00
8,"#000008",,"SALE",,20/8/2013 15:11:00
9,"#000009",,"SALE",,20/8/2013 15:30:00
10,"#000010",,"Z1",,20/8/2013 15:32:00
11,"#000011",,"NS","NO SALE",20/8/2013 15:32:00
12,"#000012",,"SALE",,20/8/2013 16:46:00
13,"#000013",,"SALE",,20/8/2013 16:47:00
14,"#000014",,"SALE",,20/8/2013 17:32:00
15,"#000015",,"Z1",,20/8/2013 19:25:00
16,"#000016",,"NS","NO SALE",20/8/2013 19:25:00
17,"#000017",,"Z1",,20/8/2013 21:52:00
18,"#000018",,"NS","NO SALE",20/8/2013 21:52:00
19,"#000019",,"SALE",,23/8/2013 18:27:00
20,"#000020",,"SALE",,23/8/2013 19:06:00
21,"#000021",,"SALE",,23/8/2013 20:24:00
22,"#000022",,"SALE",,23/8/2013 20:36:00
23,"#000023",,"SALE",,23/8/2013 21:21:00
24,"#000024",,"SALE",,23/8/2013 21:57:00
25,"#000025",,"SALE",,23/8/2013 22:38:00
26,"#000026",,"Z1",,23/8/2013 22:40:00
27,"#000027",,"NS","NO SALE",23/8/2013 22:40:00
28,"#000028",,"SALE",,24/8/2013 16:09:00
29,"#000029",,"SALE",,24/8/2013 16:28:00
30,"#000030",,"SALE",,24/8/2013 16:58:00

Body:
OK found a fix by amending the StockHead constructor to take the DataRow rather than individual arguments, and checking for any nulls there.

Is it a good way?  Is there a better way?  In a way I like it more as the complications are more tucked away - the line that calls it is now simply

StockHead sh = new StockHead( r );

Constructor code is now:

    public StockHead( DataRow row )
    {
        this.sh_id = (int)row[ "sh_id" ];
        this.sh_ref = (string)row[ "sh_ref" ];
        if ( !string.IsNullOrEmpty( row[ "sh_lineno" ].ToString() ) )
        {
            this.sh_lineno = (int)row[ "sh_lineno" ];
        }
        this.sh_type = (string)row[ "sh_type" ];
        if ( !string.IsNullOrEmpty( row[ "sh_lineno" ].ToString() ) )
        {
            this.sh_supplier = (string)row[ "sh_supplier" ];
        }
        this.sh_datetime = (DateTime)row[ "sh_datetime" ];
    }


问:
Get the last element of a window in Spark 2.1.1
I have a dataframe in which I have subcategories, and  want the last element of each of these subcategories.

```<code>val windowSpec = Window.partitionBy("name").orderBy("count")
sqlContext
    .createDataFrame(
      Seq[(String, Int)](
        ("A", 1),
        ("A", 2),
        ("A", 3),
        ("B", 10),
        ("B", 20),
        ("B", 30)
      ))
    .toDF("name", "count")
    .withColumn("firstCountOfName", first("count").over(windowSpec))
    .withColumn("lastCountOfName", last("count").over(windowSpec))
    .show()
</code>```

returns me something strange:

```<code>+----+-----+----------------+---------------+
|name|count|firstCountOfName|lastCountOfName|
+----+-----+----------------+---------------+
|   B|   10|              10|             10|
|   B|   20|              10|             20|
|   B|   30|              10|             30|
|   A|    1|               1|              1|
|   A|    2|               1|              2|
|   A|    3|               1|              3|
+----+-----+----------------+---------------+
</code>```

As we can see, the first value returned is correctly computed, but the last isn't, it's always the current value of the column.

Has someone a solution to do what I want?

答:
According to the issue SPARK-20969, you should be able to get the expected results by defining adequate bounds to your window, as shown below.

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val windowSpec = Window
  .partitionBy("name")
  .orderBy("count")
  .rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)

sqlContext
  .createDataFrame(
    Seq[(String, Int)](
      ("A", 1),
      ("A", 2),
      ("A", 3),
      ("B", 10),
      ("B", 20),
      ("B", 30)
    ))
  .toDF("name", "count")
  .withColumn("firstCountOfName", first("count").over(windowSpec))
  .withColumn("lastCountOfName", last("count").over(windowSpec))
  .show()
```

Alternatively, if your are ordering on the same column you are computing first and last, you can change for min and max with a non-ordered window, then it should also work properly.

Body:
I have a dataframe in which I have subcategories, and  want the last element of each of these subcategories.

val windowSpec = Window.partitionBy("name").orderBy("count")
sqlContext
    .createDataFrame(
      Seq[(String, Int)](
        ("A", 1),
        ("A", 2),
        ("A", 3),
        ("B", 10),
        ("B", 20),
        ("B", 30)
      ))
    .toDF("name", "count")
    .withColumn("firstCountOfName", first("count").over(windowSpec))
    .withColumn("lastCountOfName", last("count").over(windowSpec))
    .show()

returns me something strange:

+----+-----+----------------+---------------+
|name|count|firstCountOfName|lastCountOfName|
+----+-----+----------------+---------------+
|   B|   10|              10|             10|
|   B|   20|              10|             20|
|   B|   30|              10|             30|
|   A|    1|               1|              1|
|   A|    2|               1|              2|
|   A|    3|               1|              3|
+----+-----+----------------+---------------+

As we can see, the first value returned is correctly computed, but the last isn't, it's always the current value of the column.

Has someone a solution to do what I want?

Body:
According to the issue SPARK-20969, you should be able to get the expected results by defining adequate bounds to your window, as shown below.

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val windowSpec = Window
  .partitionBy("name")
  .orderBy("count")
  .rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)

sqlContext
  .createDataFrame(
    Seq[(String, Int)](
      ("A", 1),
      ("A", 2),
      ("A", 3),
      ("B", 10),
      ("B", 20),
      ("B", 30)
    ))
  .toDF("name", "count")
  .withColumn("firstCountOfName", first("count").over(windowSpec))
  .withColumn("lastCountOfName", last("count").over(windowSpec))
  .show()

Alternatively, if your are ordering on the same column you are computing first and last, you can change for min and max with a non-ordered window, then it should also work properly.


问:
How to use ruby win32ole to set Microsoft Exchange proxy settings?
using Outlook to access my work Exchange inbox via a HTTPS proxy used to be very straightforward until my employer changed the principal name I have to use. Mysteriously, in the background, the principal name gets reset to the old value. Now pretty much every time I log in, and often several times in a login session, I have to reconfigure the principal name to the new value in order to use VPN-less Outlook. Reconfiguring the HTTPS proxy principal name requires ten mouse clicks to get to the right text field (Control Panel -> mail, etc), then, once I've changed it, seven further mouse clicks to save it. It really winds me up that my employer can't find a solution to this.

I would love to be able to script this. Does anybody know (a) if it is possible and (b) how to access the Exchange proxy settings via ruby's win32ole? I've googled and googled but nobody else appears to have done this.

Kind regards,
Rob

答: through the registry maybe? (win32/registry.rb)</p>


问:
Multiple formatter functions in Bokeh datatable
Is it possible to do multiple format types within one "formatter"? For example:

```<code>TableColumn(field="y", title="y",formatter=HTMLTemplateFormatter(), NumberFormatter(),DateFormatter())
</code>```

etc

答: No it's not possible. Bokeh currently only accepts a single CellFormatter per TableColumn. You could try opening an issue on Bokeh's Github to allow thge formatter argument to accept a list of CellFormatters. Or, you may look into hooking up either a JS or python callback to the TableColumn to do some more sophisticated formatting.</p>

Body:
Is it possible to do multiple format types within one "formatter"? For example:

TableColumn(field="y", title="y",formatter=HTMLTemplateFormatter(), NumberFormatter(),DateFormatter())

etc


问:
JPA and PostgreSQL with GenerationType.IDENTITY
I have a question about Postgres and GenerationType.Identity vs Sequence

In this example...

```<code>@Id
@SequenceGenerator(name="mytable_id_seq",
                   sequenceName="mytable_id_seq",
                   allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
                generator="mytable_id_seq")
</code>```

I understand that I am specifying a Postgres sequence to use via annotations.

However, I have an id column defined with the 'serial' type, I have read that I can simply use GenerationType.IDENTITY and it will automatically generate a db sequence and use it to auto increment.

If that's the case, I don't see an advantage to using the SEQUENCE annotations unless you are using an integer for an id or have some specific reason to use another sequence you have created.  IDENTITY is alot less code and potentially makes it portable across databases.

Is there something I'm missing?

Thanks in advance for the feedback.

答: I think it can be helpful if you are using the same sequence for more than one table (for example you want a unique identifier for many types of bills) ... also If you want to keep track of the  sequence away from  the auto generated key</p>

Body:
I have a question about Postgres and GenerationType.Identity vs Sequence

In this example...

@Id
@SequenceGenerator(name="mytable_id_seq",
                   sequenceName="mytable_id_seq",
                   allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
                generator="mytable_id_seq")

I understand that I am specifying a Postgres sequence to use via annotations.

However, I have an id column defined with the 'serial' type, I have read that I can simply use GenerationType.IDENTITY and it will automatically generate a db sequence and use it to auto increment.

If that's the case, I don't see an advantage to using the SEQUENCE annotations unless you are using an integer for an id or have some specific reason to use another sequence you have created.  IDENTITY is alot less code and potentially makes it portable across databases.

Is there something I'm missing?

Thanks in advance for the feedback.


问:
How to get console output(in code) after running configurations in eclipse?
I need to start another launch configurations depending on output from executing first launch configurations. So there is a way to get console output from this launch?

Something like this:

```<code> Launch launch = (Launch) configurations[0].launch(ILaunchManager.RUN_MODE, console);
 if(launch.output){
   configurations[1].launch(ILaunchManager.RUN_MODE, console);
 }
</code>```

For example first launch configuration is a maven project, and I need to check if build is succesfully or it failed.

I have following code:

```<code>Launch launch = (Launch) configurations[0].launch(ILaunchManager.RUN_MODE,
                            new NullProgressMonitor());
                    final IProcess[] processes = launch.getProcesses();
                    IDebugEventSetListener listener = new IDebugEventSetListener() {

                        @Override
                        public void handleDebugEvents(DebugEvent[] events) {
                            for(DebugEvent e : events){
                                for(int i = 0; i < processes.length; i++){
                                    if(e.getKind() == DebugEvent.TERMINATE && e.getSource() == processes[i]){
                                        try {
                                            --------To check here if console contains Build Failed--------
                                            configurations[1].launch(ILaunchManager.RUN_MODE,
                                                    new NullProgressMonitor());
                                        } catch (CoreException e1) {
                                            e1.printStackTrace();
                                        }
                                    }
                                }

                            }
                        }
                    };
                    DebugPlugin.getDefault().addDebugEventListener(listener);
</code>```

答:
You can use the org.eclipse.ui.console.consolePatternMatchListeners extension point to match patterns in console output:

<extension
     point="org.eclipse.ui.console.consolePatternMatchListeners">
  <consolePatternMatchListener
        class="com.example.ExampleConsolePatternMatcher"
        id="com.example.ExampleConsolePatternMatcher"
        regex=".*foo.*">
     <enablement>
        <test property="org.eclipse.ui.console.consoleTypeTest" value="exampleConsole"/>
     </enablement>
  </consolePatternMatchListener>
</extension>
```

<p>You can use the <code>org.eclipse.debug.ui.consoleLineTrackers</code> extension point to listen to lines output by processes of a given process type:</p>

<pre class="lang-xml prettyprint-override"><code><extension
     point="org.eclipse.debug.ui.consoleLineTrackers">
  <consoleLineTracker
        class="org.eclipse.jdt.internal.ui.javadocexport.JavadocConsoleLineTracker"
        processType="org.eclipse.jdt.ui.javadocProcess"
        id="org.eclipse.jdt.ui.javadocexport.JavadocConsoleLineTracker">
  </consoleLineTracker>
</extension>
</code>```

Body:
I need to start another launch configurations depending on output from executing first launch configurations. So there is a way to get console output from this launch?

Something like this:

 Launch launch = (Launch) configurations[0].launch(ILaunchManager.RUN_MODE, console);
 if(launch.output){
   configurations[1].launch(ILaunchManager.RUN_MODE, console);
 }

For example first launch configuration is a maven project, and I need to check if build is succesfully or it failed.

I have following code:

Launch launch = (Launch) configurations[0].launch(ILaunchManager.RUN_MODE,
                            new NullProgressMonitor());
                    final IProcess[] processes = launch.getProcesses();
                    IDebugEventSetListener listener = new IDebugEventSetListener() {

                        @Override
                        public void handleDebugEvents(DebugEvent[] events) {
                            for(DebugEvent e : events){
                                for(int i = 0; i < processes.length; i++){
                                    if(e.getKind() == DebugEvent.TERMINATE && e.getSource() == processes[i]){
                                        try {
                                            --------To check here if console contains Build Failed--------
                                            configurations[1].launch(ILaunchManager.RUN_MODE,
                                                    new NullProgressMonitor());
                                        } catch (CoreException e1) {
                                            e1.printStackTrace();
                                        }
                                    }
                                }

                            }
                        }
                    };
                    DebugPlugin.getDefault().addDebugEventListener(listener);

Body:
You can use the org.eclipse.ui.console.consolePatternMatchListeners extension point to match patterns in console output:

<extension
     point="org.eclipse.ui.console.consolePatternMatchListeners">
  <consolePatternMatchListener
        class="com.example.ExampleConsolePatternMatcher"
        id="com.example.ExampleConsolePatternMatcher"
        regex=".*foo.*">
     <enablement>
        <test property="org.eclipse.ui.console.consoleTypeTest" value="exampleConsole"/>
     </enablement>
  </consolePatternMatchListener>
</extension>

You can use the org.eclipse.debug.ui.consoleLineTrackers extension point to listen to lines output by processes of a given process type:

<extension
     point="org.eclipse.debug.ui.consoleLineTrackers">
  <consoleLineTracker
        class="org.eclipse.jdt.internal.ui.javadocexport.JavadocConsoleLineTracker"
        processType="org.eclipse.jdt.ui.javadocProcess"
        id="org.eclipse.jdt.ui.javadocexport.JavadocConsoleLineTracker">
  </consoleLineTracker>
</extension>


问:
SQL error - Incorrect syntax near the keyword 'Database'
I want to detect databases beginning with 'NAV'in a MS SQL DB. I tried it with this code:

```<code>DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE' + @DBName);
</code>```

But I got the error message:

```<code>Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Database'.
</code>```

Do know what is wrong there?

答:
I'm not sure about the keyword database in the error message, but I do spot problems:
You concatenate USE and the databasename without a space: USENAV01 doesn't work. You should use 'USE ' + QUOTENAME(@DBName).

Secondly, I don't know what the intention is, but if you do EXECUTE ('USE ' + @DBName); followed by other (dynamic) queries, the following queries are executed on your current connection. In other words, the USE XXX doesn't matter for the following queries.

Thirdly, as mentioned by Jesse in below comment; if you have more than one database with a name like '%NAV%' (which your question suggests), your code is only executed for one of those databases. Which one that will be is unpredictable without an order by. If you want to execute code for all relevant databases, you have to loop through them.

Body:
I want to detect databases beginning with 'NAV'in a MS SQL DB. I tried it with this code:

DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE' + @DBName);

But I got the error message:

Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Database'.

Do know what is wrong there?