问:
Paperclip not uploading images, rollback
Paperclip does not upload images. Printing the output of the object the image is attached to show that no image is uploaded.

Console:

```<code>irb(main):011:0> b = Article.find(9)
  Article Load (0.5ms)  SELECT  "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT ?  [["id", 9], ["LIMIT", 1]]
=> #<Article id: 9, title: "Rails", body: "Server", created_at: "2017-07-07 15:05:41", updated_at: "2017-07-07 15:05:41", image_
file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil>
irb(main):012:0>
</code>```

Log:

```<code>Command :: file -b --mime "C:/Users/addis/AppData/Local/Temp/4d3d12fcec1dd8d0eff643aa438c2b9120170708-9872-8pkize.jpg"
[paperclip] Content Type Spoof: Filename 2006-05-09_01.19.32.jpg (image/jpeg from Headers, ["image/jpeg"] from Extension), conte
nt type discovered from file command: . See documentation to allow this combination.
Command :: file -b --mime "C:/Users/addis/AppData/Local/Temp/4d3d12fcec1dd8d0eff643aa438c2b9120170708-9872-knt072.jpg"
[paperclip] Content Type Spoof: Filename 2006-05-09_01.19.32.jpg (image/jpeg from Headers, ["image/jpeg"] from Extension), conte
nt type discovered from file command: . See documentation to allow this combination.
   (0.0ms)  rollback transaction
Redirected to http://localhost:3000/articles/1
Completed 302 Found in 49ms (ActiveRecord: 0.5ms)
</code>```

helper method:

```<code>module ArticlesHelper

  def article_params
    params.require(:article).permit(:title, :body, :tag_list, :image)
  end

end
</code>```

Model:

```<code>class Article < ApplicationRecord
    has_many :comments
    has_many :taggings
    has_many :tags, through: :taggings
    has_attached_file :image
    validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png"]

    def tag_list
    self.tags.collect do |tag|
        tag.name
    end.join(", ")
    end
    def tag_list=(tags_string)
        tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
        new_or_found_tags = tag_names.collect {|name| Tag.find_or_create_by(name: name)}
        self.tags = new_or_found_tags
    end
end
</code>```

Running on Windows 10, using Visual Code.

Following this guide.

答:
I think if it's rollback, the problem is from your validation.
below is sample code format for validates_attachment that probably you can try </p>

```<code>has_attached_file :image
validates_attachment :image, :content_type => { :content_type => ["application/octet-stream","image/jpg","image/jpeg","image/png"] }
</code>```

Body:
Paperclip does not upload images. Printing the output of the object the image is attached to show that no image is uploaded.

Console:

irb(main):011:0> b = Article.find(9)
  Article Load (0.5ms)  SELECT  "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT ?  [["id", 9], ["LIMIT", 1]]
=> #

irb(main):012:0>

Log:

Command :: file -b --mime "C:/Users/addis/AppData/Local/Temp/4d3d12fcec1dd8d0eff643aa438c2b9120170708-9872-8pkize.jpg"
[paperclip] Content Type Spoof: Filename 2006-05-09_01.19.32.jpg (image/jpeg from Headers, ["image/jpeg"] from Extension), conte
nt type discovered from file command: . See documentation to allow this combination.
Command :: file -b --mime "C:/Users/addis/AppData/Local/Temp/4d3d12fcec1dd8d0eff643aa438c2b9120170708-9872-knt072.jpg"
[paperclip] Content Type Spoof: Filename 2006-05-09_01.19.32.jpg (image/jpeg from Headers, ["image/jpeg"] from Extension), conte
nt type discovered from file command: . See documentation to allow this combination.
   (0.0ms)  rollback transaction
Redirected to http://localhost:3000/articles/1
Completed 302 Found in 49ms (ActiveRecord: 0.5ms)

helper method:

module ArticlesHelper

  def article_params
    params.require(:article).permit(:title, :body, :tag_list, :image)
  end

end

Model:

class Article < ApplicationRecord
    has_many :comments
    has_many :taggings
    has_many :tags, through: :taggings
    has_attached_file :image
    validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png"]

    def tag_list
    self.tags.collect do |tag|
        tag.name
    end.join(", ")
    end
    def tag_list=(tags_string)
        tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
        new_or_found_tags = tag_names.collect {|name| Tag.find_or_create_by(name: name)}
        self.tags = new_or_found_tags
    end
end

Running on Windows 10, using Visual Code.

Following this guide.

Body:
I think if it's rollback, the problem is from your validation.
below is sample code format for validates_attachment that probably you can try

has_attached_file :image
validates_attachment :image, :content_type => { :content_type => ["application/octet-stream","image/jpg","image/jpeg","image/png"] }


来源: stackexchange

问:
Want to use one tag with different values according to the scenario in cucumber
we have a cleanup hook in our automation framework which tagged from the cucumber feature file

E.g

@cc_task_clean_up_hook_enrol_A
 Scenario: Person can enrol_A
    When I select the context menu
    Then I am able to enroll the patient into 'enrol_A'

the implementation of the hook (@cc_task_clean_up_hook) is

```<code>@After(value = "@toc_task_clean_up_hook_enrol_A", order = HookOrder.CLEAN_UP_APP_AFTER)
public void cleanUpTOC() {
    this.patientContextPage.selectedContextMenuItem("Pathway");
    this.pathWayPage.selectReferences("Enroll in Pathway");
    this.pathWayPage.deactivateEnrollment("enrol_A", "Withdrawn");
}
</code>```

So exactly the same way we need an another scenario like

Scenario: Person can enroll_B
    When I select the context menu
    Then I am able to enroll the patient into 'enrollB'

So we can implement another hook as follows, the difference is the parameter type "enrollB"

```<code>@After(value = "@toc_task_clean_up_hook_enrollB", order = HookOrder.CLEAN_UP_APP_AFTER)
public void cleanUpTOC() {
    this.patientContextPage.selectedContextMenuItem("Pathway");
    this.pathWayPage.selectReferences("Enroll in Pathway");
    this.pathWayPage.deactivateEnrollment("enrol_B", "Withdrawn");
}
</code>```

So is it possible to consolidate these two methods and write only one generic clean up hook, based on the passed parameter? Your help is much appreciated.

答:
You can add the scenario object to the arguments passed to the after hook. The framework will inject the currently executing scenario to the method.

```<code>public void afterMethod(Scenario scenario){}
</code>```

You can use the getSourceTagNames() method of the Scenario object which will return you the collection of tags for the current executing scenario. From this collection you can determine if you have the tag ending with 'enroll_A' or 'enroll_B'.

Or you can use the getName() method which returns the description of the current scenario. So you will get either 'Person can enroll_A' or 'P..... enroll_B'. Just need to parse again.

You can modify the Then step to pass the enroll type to step definition. Store this in a variable. Use this variable in your after hook. But this will require the after hook to be in the same class.

Also you will need to change the value parameter of After hook to - {"@toc_task_clean_up_hook_enrollA,@toc_task_clean_up_hook_enrollB"}.

One observation that these two seem to have the same steps, if so then have you considered ScenarioOutline instead.

ContentLicense: CC BY-SA 3.0

Body:
we have a cleanup hook in our automation framework which tagged from the cucumber feature file

E.g

@cc_task_clean_up_hook_enrol_A
 Scenario: Person can enrol_A
    When I select the context menu
    Then I am able to enroll the patient into 'enrol_A'

the implementation of the hook (@cc_task_clean_up_hook) is

@After(value = "@toc_task_clean_up_hook_enrol_A", order = HookOrder.CLEAN_UP_APP_AFTER)
public void cleanUpTOC() {
    this.patientContextPage.selectedContextMenuItem("Pathway");
    this.pathWayPage.selectReferences("Enroll in Pathway");
    this.pathWayPage.deactivateEnrollment("enrol_A", "Withdrawn");
}

So exactly the same way we need an another scenario like

Scenario: Person can enroll_B
    When I select the context menu
    Then I am able to enroll the patient into 'enrollB'

So we can implement another hook as follows, the difference is the parameter type "enrollB"

@After(value = "@toc_task_clean_up_hook_enrollB", order = HookOrder.CLEAN_UP_APP_AFTER)
public void cleanUpTOC() {
    this.patientContextPage.selectedContextMenuItem("Pathway");
    this.pathWayPage.selectReferences("Enroll in Pathway");
    this.pathWayPage.deactivateEnrollment("enrol_B", "Withdrawn");
}

So is it possible to consolidate these two methods and write only one generic clean up hook, based on the passed parameter? Your help is much appreciated.

Body:
You can add the scenario object to the arguments passed to the after hook. The framework will inject the currently executing scenario to the method.

public void afterMethod(Scenario scenario){}

You can use the getSourceTagNames() method of the Scenario object which will return you the collection of tags for the current executing scenario. From this collection you can determine if you have the tag ending with 'enroll_A' or 'enroll_B'.

Or you can use the getName() method which returns the description of the current scenario. So you will get either 'Person can enroll_A' or 'P..... enroll_B'. Just need to parse again.

You can modify the Then step to pass the enroll type to step definition. Store this in a variable. Use this variable in your after hook. But this will require the after hook to be in the same class.

Also you will need to change the value parameter of After hook to - {"@toc_task_clean_up_hook_enrollA,@toc_task_clean_up_hook_enrollB"}.

One observation that these two seem to have the same steps, if so then have you considered ScenarioOutline instead.


问:
How to stop an image from scaling in a UIImageView?
This was a question asked by a user on Apple's cocoa-dev mailing list, who thought my answer would be helpful on Stack Overflow:

In XCode/IB, if add an Image View that has the Image property to an
  image in my project it shows the image scaled to fit the Frame of the
  Image View. How can I stop this and just truncate it? I want two
  images on top of each other and just show the top half of one and the
  bottom half of the other.

I see loads of scaling options in the “Content Mode” Property, but
  nothing to say “none”. The closest I’ve managed so far is to set the
  Content Mode to “Aspect Fit” and also set the clip to bounds. This
  does what I want BUT the centre of the image shows, not the top, left.

Basically, I have two 24 x 24 images placed one on top of the other, I
  want to show the first half (e.g. 0,0,24,12) of ImageA and the bottom
  half of imageB (e.g. 0,12,24,12).

Can I do this in XCode/IB? If not can I do this in code?

答:
Create two image views, set their sizes to 24 x 12, and set the Clip To Bounds property.

For one view, set its content mode to top (== top-center) or top-left, and the other to bottom (== bottom-center) or bottom-left.

If you turn off the clip property then you'll see that the images draw outside the image view's bounds.


问:
How to shuffle images to use for training and testing
I would like to split a dataset of images into two, training and testing, sets. I would like to split the data 80/20 between training and testing. I need to take the 80% from all of the classes of images and I need to take the remaining 20% of images from all of the classes of images as well.

This is currently how I am splitting the data into two, but it does not work properly.

```<code>image_filenames = glob.glob("./imagenet-dogs/n02*/*.jpg")

image_filenames[0:2]

training_dataset = defaultdict(list)
testing_dataset = defaultdict(list)

image_filename_with_breed = map(lambda filename: (filename.split("/")[2], filename), image_filenames)

for dog_breed, breed_images in groupby(image_filename_with_breed, lambda x: x[0]):
    """
    Append training/testing image datasets to respective dictionaries
    """
    # Enumerate each breed's image and send ~20% of the images to a testing set
    for i, breed_image in enumerate(breed_images):
        if i % 5 == 0:
            testing_dataset[dog_breed].append(breed_image[1])
        else:
            training_dataset[dog_breed].append(breed_image[1])
</code>```

What am I doing wrong and what is the best way to do this to ensure that images are taken from all classes?

Would shuffling the images then taking 80%, appending it to training then taking the remaining 20% and appending it to testing work? If so, what is the best way to do that?

答:
This is exactly what stratified train test split does, implemented for example in sklearn:
http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html

The general idea is very simple:

For each class C:

take all samples belonging to class C

shuffle them (just in case)

take first K% to train, remaining to test

Shuffle train and test again (separately)

This way you have a guarantee of selecting proper ratio of each class (hence the word stratified).

Body:
I would like to split a dataset of images into two, training and testing, sets. I would like to split the data 80/20 between training and testing. I need to take the 80% from all of the classes of images and I need to take the remaining 20% of images from all of the classes of images as well.

This is currently how I am splitting the data into two, but it does not work properly.

image_filenames = glob.glob("./imagenet-dogs/n02*/*.jpg")

image_filenames[0:2]

training_dataset = defaultdict(list)
testing_dataset = defaultdict(list)

image_filename_with_breed = map(lambda filename: (filename.split("/")[2], filename), image_filenames)

for dog_breed, breed_images in groupby(image_filename_with_breed, lambda x: x[0]):
    """
    Append training/testing image datasets to respective dictionaries
    """
    # Enumerate each breed's image and send ~20% of the images to a testing set
    for i, breed_image in enumerate(breed_images):
        if i % 5 == 0:
            testing_dataset[dog_breed].append(breed_image[1])
        else:
            training_dataset[dog_breed].append(breed_image[1])

What am I doing wrong and what is the best way to do this to ensure that images are taken from all classes?

Would shuffling the images then taking 80%, appending it to training then taking the remaining 20% and appending it to testing work? If so, what is the best way to do that?


问:
Doctrine Searchable Behavior vs Zend Lucene in symfony
I need to  search for keywords in 2 table, simple thing

I am undecided about using one or the other?
any suggestion performance wise?

Thanks!

答:
As cuhuak mentioned, Lucene is a fulltext search. Since it is written in Java, you additionaly need a Java Server (Tomcat for example). If you don't want an additional server, the Zend Lucene implementation (as noted in the comments by Matt Gibson) may also be worth looking into. With an additional server and if you only have a small host, this MAY not be good performance wise. Also, Lucene needs much more configuration and set-up than the Doctrine solutions.

On the performance side of things: Lucene is built to index millions of words and search within these in milliseconds. With millions of words in your "regular" RDBMS, things will get slow. You could set up a fulltextsearch in the database too, but this again needs setup and knowledge what to do.

So a generall thought: if the site is small (in terms of things to searc), go with the Doctrine approach, if you plan to get serious amounts of data, go with Lucene.

ContentLicense: CC BY-SA 2.5


问:
Python pandas - filter rows after groupby
For example, I have the following table:

```<code>index,A,B
0,0,0
1,0,8
2,0,8
3,1,5
4,1,3
</code>```

After grouping by A:

```<code>0:
index,A,B
0,0,0
1,0,8
2,0,8

1:
index,A,B
3,1,5
4,1,3
</code>```

What I need is to drop rows from each group, where the number in column B is less than maximum value from all rows from group's column B. Well I have a problem translating and formulating this problem to English so here is the example:

Maximum value from rows in column B in group 0: 8

So I want to drop row with index 0 and keep rows with indexes 1 and 2

Maximum value from rows in column B in group 1: 5

So I want to drop row with index 4 and keep row with index 3

I have tried to use pandas filter function, but the problem is that it is operating on all rows in group at one time:

```<code>data = <example table>
grouped = data.groupby("A")
filtered = grouped.filter(lambda x: x["B"] == x["B"].max())
</code>```

So what I ideally need is some filter, which iterates through all rows in group.

Thanks for help!

P.S. Is there also way to only delete rows in groups and do not return DataFrame object?

答:
Here's the other example for : Filtering the rows with maximum value after groupby operation using idxmax() and .loc()

```<code>In [465]: import pandas as pd

In [466]:   df = pd.DataFrame({
               'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2'],
               'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4'],
               'value' : [3,2,5,8,10,1]
                })

In [467]: df
Out[467]:
   mt   sp  value
0  S1  MM1      3
1  S1  MM1      2
2  S3  MM1      5
3  S3  MM2      8
4  S4  MM2     10
5  S4  MM2      1

### Here, idxmax() finds the indices of the rows with max value within groups,
### and .loc() filters the rows using those indices :
In [468]: df.loc[df.groupby(["mt"])["value"].idxmax()]
Out[468]:
   mt   sp  value
0  S1  MM1      3
3  S3  MM2      8
4  S4  MM2     10
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For example, I have the following table:

index,A,B
0,0,0
1,0,8
2,0,8
3,1,5
4,1,3

After grouping by A:

0:
index,A,B
0,0,0
1,0,8
2,0,8

1:
index,A,B
3,1,5
4,1,3

What I need is to drop rows from each group, where the number in column B is less than maximum value from all rows from group's column B. Well I have a problem translating and formulating this problem to English so here is the example:

Maximum value from rows in column B in group 0: 8

So I want to drop row with index 0 and keep rows with indexes 1 and 2

Maximum value from rows in column B in group 1: 5

So I want to drop row with index 4 and keep row with index 3

I have tried to use pandas filter function, but the problem is that it is operating on all rows in group at one time:

data = <example table>
grouped = data.groupby("A")
filtered = grouped.filter(lambda x: x["B"] == x["B"].max())

So what I ideally need is some filter, which iterates through all rows in group.

Thanks for help!

P.S. Is there also way to only delete rows in groups and do not return DataFrame object?

Body:
Here's the other example for : Filtering the rows with maximum value after groupby operation using idxmax() and .loc()

In [465]: import pandas as pd

In [466]:   df = pd.DataFrame({
               'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2'],
               'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4'],
               'value' : [3,2,5,8,10,1]
                })

In [467]: df
Out[467]:
   mt   sp  value
0  S1  MM1      3
1  S1  MM1      2
2  S3  MM1      5
3  S3  MM2      8
4  S4  MM2     10
5  S4  MM2      1

### Here, idxmax() finds the indices of the rows with max value within groups,
### and .loc() filters the rows using those indices :
In [468]: df.loc[df.groupby(["mt"])["value"].idxmax()]
Out[468]:
   mt   sp  value
0  S1  MM1      3
3  S3  MM2      8
4  S4  MM2     10


问:
How to make Responsive button with Bootstrap
I'm Trying to have submit button center the page.
my code in html is:

```<code><div class="container-fluid">
<div class="row" style="margin-right:0;margin-left:0">

<form method="POST"
      action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
    {{csrf_field()}}

    <button type="submit" class="btn btn-primary submit">Submit</button>
</form>
</div>
</code>```

I give the submit button center in desktop but this button Not at the center in mobile!what can I do to centered button in mobile?

答:
A solution with pure CSS (flexbox):

wrap your button with a div, add a class called centered with style:

```<code>.centered {
  display: flex;
  align-items: center;
  justify-content: center;
}
</code>```

.centered {
  display: flex;
  align-items: center;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row" style="margin-right:0;margin-left:0">

    <form method="POST" action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
      {{csrf_field()}}

      <div class="centered">
        <button type="submit" class="btn btn-primary submit">Submit</button>
      </div>
    </form>
  </div></code>```

Body:
I'm Trying to have submit button center the page.
my code in html is:

<form method="POST"
      action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
    {{csrf_field()}}

    <button type="submit" class="btn btn-primary submit">Submit</button>
</form>

I give the submit button center in desktop but this button Not at the center in mobile!what can I do to centered button in mobile?

Body:
A solution with pure CSS (flexbox):

wrap your button with a div, add a class called centered with style:

.centered {
  display: flex;
  align-items: center;
  justify-content: center;
}

.centered {
  display: flex;
  align-items: center;
  justify-content: center;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row" style="margin-right:0;margin-left:0">

    <form method="POST" action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
      {{csrf_field()}}

      <div class="centered">
        <button type="submit" class="btn btn-primary submit">Submit</button>
      </div>
    </form>
  </div>


问:
How to get the highest value of a standard deviation for last 2 hours in MQL4?
I'm trying to develop an Expert Advisor, so far I can understand and write this which will place orders when a new bar opens.

```<code>int BarsCount = 0;

int start()
{   if ( Bars >  BarsCount )
    {    OrderSend( Symbol(), OP_BUY, 0.01, Ask, 2, NULL, NULL );
         BarsCount = Bars;
    }
    return( 0 );
}
</code>```

how to get the highest value of standard deviation for last 2 hours to a variable?

E.g.: lets say the EA runs in a 30 mins chart and the bar1 has the standard deviation value 0.003, and bar2 has 0.001, bar3 has 0.004 and bar4 has 0.001.
So, the highest value for past 4 hours is bar3 which has the value of 0.004, so how to get that value to a variable?

I'm trying to make the EA place orders when this formula is true:

```<code> ( ( current_value_of_standard_deviation
   / highest_value_of_standard_deviation_for_last_2_hours
     )
   * 100
   ) > 10
</code>```

答:
Use built-in tools:

```<code>input  int    MA_period = 27;
       int    BarsCount = 0;
       int    nCells2CMP= ( PERIOD_H1 * 2 / PERIOD_CURRENT ) - 1;
       double Sig2H[100];

void OnInit(){
     ...
}

void OnTick(){
     if ( Bars >  BarsCount ){
          if (    BarsCount == 0 ){
                  for ( int i = MA_period; i >  0; i-- ){
                        Sig2H[i] = iStdDev( _Symbol,
                                            PERIOD_CURRENT,
                                            0,
                                            MODE_SMA,
                                            PRICE_CLOSE,
                                            i
                                            );
                  }
          }
          for ( int i = MA_period; i > 1; i-- )  Sig2H[i] = Sig2H[i-1];
          Sig2H[1] = iStdDev( _Symbol,           // symbol
                              PERIOD_CURRENT,    // timeframe
                              MA_period,         // MA averaging period
                              0,                 // MA shift
                              MODE_SMA,          // MA averaging method
                              PRICE_CLOSE,       // applied price
                              1                  // shift
                              );
     }
     Sig2H[0] = iStdDev( _Symbol,           // symbol
                         PERIOD_CURRENT,    // timeframe
                         MA_period,         // MA averaging period
                         0,                 // MA shift
                         MODE_SMA,          // MA averaging method
                         PRICE_CLOSE,       // applied price
                         0                  // shift
                         );
     if ( 0.1 < ( Sig2H[0]
                / Sig2H[ArrayMaximum( Sig2H,
                                      nCells2CMP,
                                      1
                                      )
                        ]
                  )
          ){...}
}
</code>```

Body:
I'm trying to develop an Expert Advisor, so far I can understand and write this which will place orders when a new bar opens.

int BarsCount = 0;

int start()
{   if ( Bars >  BarsCount )
    {    OrderSend( Symbol(), OP_BUY, 0.01, Ask, 2, NULL, NULL );
         BarsCount = Bars;
    }
    return( 0 );
}

how to get the highest value of standard deviation for last 2 hours to a variable?

E.g.: lets say the EA runs in a 30 mins chart and the bar1 has the standard deviation value 0.003, and bar2 has 0.001, bar3 has 0.004 and bar4 has 0.001.
So, the highest value for past 4 hours is bar3 which has the value of 0.004, so how to get that value to a variable?

I'm trying to make the EA place orders when this formula is true:

 ( ( current_value_of_standard_deviation
   / highest_value_of_standard_deviation_for_last_2_hours
     )
   * 100
   ) > 10

Body:
Use built-in tools:

input  int    MA_period = 27;
       int    BarsCount = 0;
       int    nCells2CMP= ( PERIOD_H1 * 2 / PERIOD_CURRENT ) - 1;
       double Sig2H[100];

void OnInit(){
     ...
}

void OnTick(){
     if ( Bars >  BarsCount ){
          if (    BarsCount == 0 ){
                  for ( int i = MA_period; i >  0; i-- ){
                        Sig2H[i] = iStdDev( _Symbol,
                                            PERIOD_CURRENT,
                                            0,
                                            MODE_SMA,
                                            PRICE_CLOSE,
                                            i
                                            );
                  }
          }
          for ( int i = MA_period; i > 1; i-- )  Sig2H[i] = Sig2H[i-1];
          Sig2H[1] = iStdDev( _Symbol,           // symbol
                              PERIOD_CURRENT,    // timeframe
                              MA_period,         // MA averaging period
                              0,                 // MA shift
                              MODE_SMA,          // MA averaging method
                              PRICE_CLOSE,       // applied price
                              1                  // shift
                              );
     }
     Sig2H[0] = iStdDev( _Symbol,           // symbol
                         PERIOD_CURRENT,    // timeframe
                         MA_period,         // MA averaging period
                         0,                 // MA shift
                         MODE_SMA,          // MA averaging method
                         PRICE_CLOSE,       // applied price
                         0                  // shift
                         );
     if ( 0.1 < ( Sig2H[0]
                / Sig2H[ArrayMaximum( Sig2H,
                                      nCells2CMP,
                                      1
                                      )
                        ]
                  )
          ){...}
}


问:
Resources$NotFoundException fatal exception for custom view after proguard, on specific devices
I'm getting the following stacktrace for crashes on few specific devices. Both the devices I faced the crash on are running OSv5.1

```<code>Fatal Exception: android.view.InflateException: Binary XML file line #161: Error inflating class com.adroitandroid.stitchastory.ui.AppTextInputLayoutPlus
       at android.view.LayoutInflater.createView(LayoutInflater.java:633)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:116)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:88)
       at com.adroitandroid.stitchastory.HomeActivity$StartStoryFragment.onCreateView(HomeActivity.java:415)
       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
       at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
       at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
       at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
       at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
       at android.os.Handler.handleCallback(Handler.java:815)
       at android.os.Handler.dispatchMessage(Handler.java:104)
       at android.os.Looper.loop(Looper.java:194)
       at android.app.ActivityThread.main(ActivityThread.java:5763)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by java.lang.reflect.InvocationTargetException
       at java.lang.reflect.Constructor.newInstance(Constructor.java)
       at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
       at android.view.LayoutInflater.createView(LayoutInflater.java:607)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:116)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:88)
       at com.adroitandroid.stitchastory.HomeActivity$StartStoryFragment.onCreateView(HomeActivity.java:415)
       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
       at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
       at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
       at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
       at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
       at android.os.Handler.handleCallback(Handler.java:815)
       at android.os.Handler.dispatchMessage(Handler.java:104)
       at android.os.Looper.loop(Looper.java:194)
       at android.app.ActivityThread.main(ActivityThread.java:5763)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by android.content.res.Resources$NotFoundException: Resource ID #0x7f0f007c
       at android.content.res.Resources.getValue(Resources.java:1463)
       at android.support.v7.content.res.AppCompatResources.isColorInt(AppCompatResources.java:161)
       at android.support.v7.content.res.AppCompatResources.inflateColorStateList(AppCompatResources.java:108)
       at android.support.v7.content.res.AppCompatResources.getColorStateList(AppCompatResources.java:74)
       at android.support.v7.widget.TintTypedArray.getColorStateList(TintTypedArray.java:136)
       at android.support.design.widget.TextInputLayout.(TextInputLayout.java:244)
       at android.support.design.widget.TextInputLayout.(TextInputLayout.java:183)
       at com.adroitandroid.stitchastory.ui.TextInputLayoutPlus.(TextInputLayoutPlus.java:19)
       at com.adroitandroid.stitchastory.ui.AppTextInputLayoutPlus.(AppTextInputLayoutPlus.java:16)
       at java.lang.reflect.Constructor.newInstance(Constructor.java)
       at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
       at android.view.LayoutInflater.createView(LayoutInflater.java:607)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:116)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:88)
       at com.adroitandroid.stitchastory.HomeActivity$StartStoryFragment.onCreateView(HomeActivity.java:415)
       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
       at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
       at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
       at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
       at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
       at android.os.Handler.handleCallback(Handler.java:815)
       at android.os.Handler.dispatchMessage(Handler.java:104)
       at android.os.Looper.loop(Looper.java:194)
       at android.app.ActivityThread.main(ActivityThread.java:5763)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

The resource mentioned is

```<code>    public static final int design_tint_password_toggle=0x7f0f007c;
</code>```

in my R.java, basically not a resource I've defined myself. However, it is a custom layout that I'm trying to inflate here. For another such previous crash, I explicitly mentioned the text color in my view in xml to fix it. But this is different in that it is an android resource which it couldn't find. This isn't right on app launch either.

To add, this is a proguarded apk, I have the following in my proguard config file to retain the constants.

```<code>-keepclassmembers class **.R$* {
    public static <fields>;
}
-keep class **.R$*
</code>```

Also I've tried commenting out

```<code>shrinkResources true
</code>```

for the particular build type, but it didn't fix this.

I'm using buildToolsVersion '25.0.1'

Support library version is 25.1.0 and here is the layout file it's trying to inflate when it crashes. Line 161 is where the view related to the crash is declared. Pasting here for convenience.

```<code><com.adroitandroid.stitchastory.ui.AppTextInputLayoutPlus
    android:id="@+id/contribution_til"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@id/done_ib"
    android:layout_alignStart="@id/cancel_ib"
    android:layout_below="@id/done_ib"
    android:layout_centerInParent="true"
    android:paddingTop="16dp"
    app:counterEnabled="true"
    app:counterMaxLength="@integer/maxContributionLength"
    app:errorEnabled="true"
    app:hintEnabled="false">

    <com.adroitandroid.stitchastory.ui.ContentEditTextPlus
        android:id="@+id/contribution_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="@string/hint_add_story"
        android:imeOptions="actionDone"
        android:inputType="textAutoComplete|textCapSentences|textShortMessage|textMultiLine" />
</com.adroitandroid.stitchastory.ui.AppTextInputLayoutPlus>
</code>```

Nothing fancy about the AppTextInputLayoutPlus, it just takes a custom typeface in the following manner.

```<code>abstract class TextInputLayoutPlus extends TextInputLayout {
    public TextInputLayoutPlus(Context context) {
        super(context);
        init();
    }

    public TextInputLayoutPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TextInputLayoutPlus(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setTypeface(Typeface.createFromAsset(getContext().getAssets(), getTextFont()));
    }

    protected abstract String getTextFont();
}
// in its own class file
public class AppTextInputLayoutPlus extends TextInputLayoutPlus {
    public AppTextInputLayoutPlus(Context context) {
        super(context);
    }

    public AppTextInputLayoutPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AppTextInputLayoutPlus(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected String getTextFont() {
        return AppTextView.APP_TEXT_FONT;
    }
}
</code>```

Does anyone know a way to fix this, and why this is coming up?

答: This is a guess - the issue had nothing to do with the TextInputLayout, but more to do with the ContentEditTextPlus. Recently I identified an issue in the code of the ContentEditTextPlus and other such classes where I had overridden a setTextColor() mixing up a ColorRes int argument for a ColorInt or vice versa. That should explain the resource not found exception in getColorStateList().

Body:
I'm getting the following stacktrace for crashes on few specific devices. Both the devices I faced the crash on are running OSv5.1

Fatal Exception: android.view.InflateException: Binary XML file line #161: Error inflating class com.adroitandroid.stitchastory.ui.AppTextInputLayoutPlus
       at android.view.LayoutInflater.createView(LayoutInflater.java:633)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:116)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:88)
       at com.adroitandroid.stitchastory.HomeActivity$StartStoryFragment.onCreateView(HomeActivity.java:415)
       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
       at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
       at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
       at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
       at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
       at android.os.Handler.handleCallback(Handler.java:815)
       at android.os.Handler.dispatchMessage(Handler.java:104)
       at android.os.Looper.loop(Looper.java:194)
       at android.app.ActivityThread.main(ActivityThread.java:5763)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by java.lang.reflect.InvocationTargetException
       at java.lang.reflect.Constructor.newInstance(Constructor.java)
       at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
       at android.view.LayoutInflater.createView(LayoutInflater.java:607)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:116)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:88)
       at com.adroitandroid.stitchastory.HomeActivity$StartStoryFragment.onCreateView(HomeActivity.java:415)
       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
       at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
       at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
       at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
       at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
       at android.os.Handler.handleCallback(Handler.java:815)
       at android.os.Handler.dispatchMessage(Handler.java:104)
       at android.os.Looper.loop(Looper.java:194)
       at android.app.ActivityThread.main(ActivityThread.java:5763)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by android.content.res.Resources$NotFoundException: Resource ID #0x7f0f007c
       at android.content.res.Resources.getValue(Resources.java:1463)
       at android.support.v7.content.res.AppCompatResources.isColorInt(AppCompatResources.java:161)
       at android.support.v7.content.res.AppCompatResources.inflateColorStateList(AppCompatResources.java:108)
       at android.support.v7.content.res.AppCompatResources.getColorStateList(AppCompatResources.java:74)
       at android.support.v7.widget.TintTypedArray.getColorStateList(TintTypedArray.java:136)
       at android.support.design.widget.TextInputLayout.(TextInputLayout.java:244)
       at android.support.design.widget.TextInputLayout.(TextInputLayout.java:183)
       at com.adroitandroid.stitchastory.ui.TextInputLayoutPlus.(TextInputLayoutPlus.java:19)
       at com.adroitandroid.stitchastory.ui.AppTextInputLayoutPlus.(AppTextInputLayoutPlus.java:16)
       at java.lang.reflect.Constructor.newInstance(Constructor.java)
       at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
       at android.view.LayoutInflater.createView(LayoutInflater.java:607)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:116)
       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:88)
       at com.adroitandroid.stitchastory.HomeActivity$StartStoryFragment.onCreateView(HomeActivity.java:415)
       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
       at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
       at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
       at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
       at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
       at android.os.Handler.handleCallback(Handler.java:815)
       at android.os.Handler.dispatchMessage(Handler.java:104)
       at android.os.Looper.loop(Looper.java:194)
       at android.app.ActivityThread.main(ActivityThread.java:5763)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

The resource mentioned is

    public static final int design_tint_password_toggle=0x7f0f007c;

in my R.java, basically not a resource I've defined myself. However, it is a custom layout that I'm trying to inflate here. For another such previous crash, I explicitly mentioned the text color in my view in xml to fix it. But this is different in that it is an android resource which it couldn't find. This isn't right on app launch either.

To add, this is a proguarded apk, I have the following in my proguard config file to retain the constants.

-keepclassmembers class **.R$* {
    public static <fields>;
}
-keep class **.R$*

Also I've tried commenting out

shrinkResources true

for the particular build type, but it didn't fix this.

I'm using buildToolsVersion '25.0.1'

Support library version is 25.1.0 and here is the layout file it's trying to inflate when it crashes. Line 161 is where the view related to the crash is declared. Pasting here for convenience.

<com.adroitandroid.stitchastory.ui.AppTextInputLayoutPlus
    android:id="@+id/contribution_til"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@id/done_ib"
    android:layout_alignStart="@id/cancel_ib"
    android:layout_below="@id/done_ib"
    android:layout_centerInParent="true"
    android:paddingTop="16dp"
    app:counterEnabled="true"
    app:counterMaxLength="@integer/maxContributionLength"
    app:errorEnabled="true"
    app:hintEnabled="false">

    <com.adroitandroid.stitchastory.ui.ContentEditTextPlus
        android:id="@+id/contribution_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="@string/hint_add_story"
        android:imeOptions="actionDone"
        android:inputType="textAutoComplete|textCapSentences|textShortMessage|textMultiLine" />
</com.adroitandroid.stitchastory.ui.AppTextInputLayoutPlus>

Nothing fancy about the AppTextInputLayoutPlus, it just takes a custom typeface in the following manner.

abstract class TextInputLayoutPlus extends TextInputLayout {
    public TextInputLayoutPlus(Context context) {
        super(context);
        init();
    }

    public TextInputLayoutPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TextInputLayoutPlus(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setTypeface(Typeface.createFromAsset(getContext().getAssets(), getTextFont()));
    }

    protected abstract String getTextFont();
}
// in its own class file
public class AppTextInputLayoutPlus extends TextInputLayoutPlus {
    public AppTextInputLayoutPlus(Context context) {
        super(context);
    }

    public AppTextInputLayoutPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AppTextInputLayoutPlus(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected String getTextFont() {
        return AppTextView.APP_TEXT_FONT;
    }
}

Does anyone know a way to fix this, and why this is coming up?


问:
Windows batch read a txt file, filter lines and print them in another file
I'm basing on Batch file to filter strings from text and replace... but in a single batch instead of multiple? but I'm still unable to understand how to do it.

I have an input txt flatfile with data stored in fixed columns. I need to use Windows batch to read line by line on this file. In a specific column, if the value is a specific one, I need to print its line in an output file. The input file doesn't have header so I don't have to worry about it.

In example, say it has 3 columns:

```<code>AAAA 1111 jjjjj
BBBB 2222 kkkkk
CCCC 1111 llll
</code>```

I need to filter lines whose 2nd column is 1111, so the new file must have:

```<code>AAAA 1111 jjjjj
CCCC 1111 llll
</code>```

What's the code to make this filter and print to the output file?

答:
As long as you are filtering on the 8th column or earlier, then all you need is a single FINDSTR command with an appropriately constructed regular expression. Note that FINDSTR regular expression support is very limited and non-standard.

Here is a solution for the example in your question - matching 1111 in the 2nd column:

```<code>findstr /rc:"^[^ ][^ ]*  *1111 " input.txt >output.txt
</code>```

Here is what it would look like to match 1111 in the 5th column

```<code>findstr /rc:"^[^ ][^ ]*  *[^ ][^ ]*  *[^ ][^ ]*  *[^ ][^ ]*  *1111 " input.txt >output.txt
</code>```

The reason this will fail if you attempt to filter on the 9th or later column is because FINDSTR is limited to a maximum of 15 character class ([x]) terms. See What are the undocumented features and limitations of the Windows FINDSTR command? for more info.

A more robust alternative is to use my JREPL.BAT regex utility. JREPL is pure script (hybrid batch/JScript) that runs on any Windows version from XP onward - no 3rd party exe file required.

```<code>jrepl "^\S+\s+1111\s" "" /k 0 /f input.txt /o output.txt
</code>```

If you wanted to match 1111 in the 25th column instead of the 2nd column, then a JREPL solution would look like:

```<code>jrepl "^(\S+\s+){24}1111\s" "" /k 0 /f input.txt /o output.txt
</code>```

Since JREPL is a batch script, you would need to use CALL JREPL if you put the command within another batch script.

Body:
I'm basing on Batch file to filter strings from text and replace... but in a single batch instead of multiple? but I'm still unable to understand how to do it.

I have an input txt flatfile with data stored in fixed columns. I need to use Windows batch to read line by line on this file. In a specific column, if the value is a specific one, I need to print its line in an output file. The input file doesn't have header so I don't have to worry about it.

In example, say it has 3 columns:

AAAA 1111 jjjjj
BBBB 2222 kkkkk
CCCC 1111 llll

I need to filter lines whose 2nd column is 1111, so the new file must have:

AAAA 1111 jjjjj
CCCC 1111 llll

What's the code to make this filter and print to the output file?

Body:
As long as you are filtering on the 8th column or earlier, then all you need is a single FINDSTR command with an appropriately constructed regular expression. Note that FINDSTR regular expression support is very limited and non-standard.

Here is a solution for the example in your question - matching 1111 in the 2nd column:

findstr /rc:"^[^ ][^ ]*  *1111 " input.txt >output.txt

Here is what it would look like to match 1111 in the 5th column

findstr /rc:"^[^ ][^ ]*  *[^ ][^ ]*  *[^ ][^ ]*  *[^ ][^ ]*  *1111 " input.txt >output.txt

The reason this will fail if you attempt to filter on the 9th or later column is because FINDSTR is limited to a maximum of 15 character class ([x]) terms. See What are the undocumented features and limitations of the Windows FINDSTR command? for more info.

A more robust alternative is to use my JREPL.BAT regex utility. JREPL is pure script (hybrid batch/JScript) that runs on any Windows version from XP onward - no 3rd party exe file required.

jrepl "^\S+\s+1111\s" "" /k 0 /f input.txt /o output.txt

If you wanted to match 1111 in the 25th column instead of the 2nd column, then a JREPL solution would look like:

jrepl "^(\S+\s+){24}1111\s" "" /k 0 /f input.txt /o output.txt

Since JREPL is a batch script, you would need to use CALL JREPL if you put the command within another batch script.


问:
Using Coda to access server SSH/sFTP
I have a VPS server and I lock down to only expose 3 ports 80, 443 and 22222 for ssh. So far I can connect to the server using Terminal (Mac) and Panic Transmit, but when I try to connect using Panic Coda the connection fail. What I am doing wrong?

I see Coda support sFTP and I can connect on Coda to the SSH, but not to the sFTP.

Ideas? Work around?

Thank you

答:
As to what coda is actually doing, I can't say for sure.

Workaround could be to create an ssh tunnel and just use FTP, configure your FTP server or firewall to only allow loopback connections

Establish tunnel using something like:

```<code>ssh -o'Port 22222' -f user@server -L 3000:127.0.0.1:21 -N
</code>```

Then point FTP at localhost, port 3000.

HOWTO: SSH Tunneling Made Easy

Title: Using Coda to access server SSH/sFTP

Body:
As to what coda is actually doing, I can't say for sure.

Workaround could be to create an ssh tunnel and just use FTP, configure your FTP server or firewall to only allow loopback connections

Establish tunnel using something like:

ssh -o'Port 22222' -f user@server -L 3000:127.0.0.1:21 -N

Then point FTP at localhost, port 3000.

HOWTO: SSH Tunneling Made Easy


问:
TextBox Style - Binding to width of text
I have a style for a textBox. I have in it a change to the textBox control template with a additional rectangle. I want the width of the rectangle to be bound to the width of the text that has been typed.

Here is the current style

```<code><Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
                <Border Name="Border"
                        Padding="2"
                        Background="{DynamicResource White#}">

                    <StackPanel VerticalAlignment="Center">
                        <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
                        <Rectangle x:Name="Rect1" Width="{Binding ActualWidth, ElementName=PART_ContentHost}" Height="2" Fill="{TemplateBinding Foreground}" Opacity="0.8">
                            <Rectangle.LayoutTransform>
                                <ScaleTransform ScaleX="0" />
                            </Rectangle.LayoutTransform>
                        </Rectangle>
                    </StackPanel>
                </Border>
           </ControlTemplate>

        </Setter.Value>
    </Setter>
</code>```

This xaml bar stretches I want it just to be as wide as the text

What do I have to put in the setter for the control template and what does the binding have to be?

答:
You were very close.

First, I added HorizontalAlignment="Left" to the ScrollViewer, to prevent it from stretching to the full width of its parent.

Second, I removed the ScaleTransform that shrank the Rectangle to a horizontal size of zero.

```<code><StackPanel VerticalAlignment="Center" >
    <ScrollViewer
        Margin="0"
        x:Name="PART_ContentHost"
        HorizontalAlignment="Left"
        />
    <Rectangle
        x:Name="Rect1"
        Width="{Binding ActualWidth, ElementName=PART_ContentHost}"
        Height="2"
        Fill="{TemplateBinding Foreground}" Opacity="0.8"
        HorizontalAlignment="Left"
        >
    </Rectangle>
</StackPanel>
</code>```

Now you've got another problem: The user has to click inside the ScrollViewer to make it get focus so he can start typing, and the scrollviewer is a little thing crowded into the left hand side of the control. I'm looking at some ways to do that; stand by for an update.

Update

How to handle focus on mousedown without committing any sins against MVVM:

```<code>using System.ComponentModel;
using System.Windows;
using System.Windows.Input;

namespace MyRandomNamespace
{
    public static class Extensions
    {
        #region Extensions.MouseDownFocusRecipient Attached Property

        //  Attached property. See XAML example below for usage.
        //  On mouse down, sets focus on bound target control.

        public static UIElement GetMouseDownFocusRecipient(UIElement obj)
        {
            return (UIElement)obj.GetValue(MouseDownFocusRecipientProperty);
        }

        public static void SetMouseDownFocusRecipient(UIElement obj, UIElement value)
        {
            obj.SetValue(MouseDownFocusRecipientProperty, value);
        }

        public static readonly DependencyProperty MouseDownFocusRecipientProperty =
            DependencyProperty.RegisterAttached("MouseDownFocusRecipient", typeof(UIElement), typeof(Extensions),
                new PropertyMetadata(null, MouseDownFocusRecipient_PropertyChanged));

        private static void MouseDownFocusRecipient_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var target = d as UIElement;

            //  Target must have some kind of background color or it will ignore mouse events.
            //  We can't do this object-orientedly because multiple Background dependency
            //  properties are defined in multiple control classes.

            var bkgDepProp = DependencyPropertyDescriptor.FromName("Background", target.GetType(), target.GetType(), true);

            if (bkgDepProp != null && bkgDepProp.GetValue(target) == null)
            {
                bkgDepProp.SetValue(target, System.Windows.Media.Brushes.Transparent);
            }

            //target.IsHitTestVisible = true;
            target.PreviewMouseDown -= Target_PreviewMouseDown;
            target.PreviewMouseDown += Target_PreviewMouseDown;
        }

        private static void Target_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var target = (UIElement)sender;

            var otherControl = GetMouseDownFocusRecipient(target);

            if (otherControl != null)
            {
                Keyboard.Focus(otherControl);
            }
        }
        #endregion Extensions.MouseDownFocusRecipient Attached Property
    }
}
</code>```

XAML:

```<code><ControlTemplate TargetType="{x:Type TextBoxBase}" x:Key="TextBoxTemplate">
    <Border
        Name="Border"
        Padding="2"
        Background="{DynamicResource White#}"
        local:Extensions.MouseDownFocusRecipient="{Binding ElementName=PART_ContentHost}"
        >
        <StackPanel
            VerticalAlignment="Center"
            MouseDown="StackPanel_MouseDown"
            >
            <ScrollViewer
                Margin="0"
                x:Name="PART_ContentHost"
                HorizontalAlignment="Left"
                />
            <Rectangle
                x:Name="Rect1"
                Width="{Binding ActualWidth, ElementName=PART_ContentHost}"
                Height="8"
                Fill="{TemplateBinding Foreground}" Opacity="0.8"
                IsHitTestVisible="False"
                HorizontalAlignment="Left"
                />
        </StackPanel>
    </Border>
</ControlTemplate>
</code>```

Body:
I have a style for a textBox. I have in it a change to the textBox control template with a additional rectangle. I want the width of the rectangle to be bound to the width of the text that has been typed.

Here is the current style

<Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
                <Border Name="Border"
                        Padding="2"
                        Background="{DynamicResource White#}">

                    <StackPanel VerticalAlignment="Center">
                        <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
                        <Rectangle x:Name="Rect1" Width="{Binding ActualWidth, ElementName=PART_ContentHost}" Height="2" Fill="{TemplateBinding Foreground}" Opacity="0.8">
                            <Rectangle.LayoutTransform>
                                <ScaleTransform ScaleX="0" />
                            </Rectangle.LayoutTransform>
                        </Rectangle>
                    </StackPanel>
                </Border>
           </ControlTemplate>

        </Setter.Value>
    </Setter>

This xaml bar stretches I want it just to be as wide as the text

What do I have to put in the setter for the control template and what does the binding have to be?

Body:
You were very close.

First, I added HorizontalAlignment="Left" to the ScrollViewer, to prevent it from stretching to the full width of its parent.

Second, I removed the ScaleTransform that shrank the Rectangle to a horizontal size of zero.

<StackPanel VerticalAlignment="Center" >
    <ScrollViewer
        Margin="0"
        x:Name="PART_ContentHost"
        HorizontalAlignment="Left"
        />
    <Rectangle
        x:Name="Rect1"
        Width="{Binding ActualWidth, ElementName=PART_ContentHost}"
        Height="2"
        Fill="{TemplateBinding Foreground}" Opacity="0.8"
        HorizontalAlignment="Left"
        >
    </Rectangle>
</StackPanel>

Now you've got another problem: The user has to click inside the ScrollViewer to make it get focus so he can start typing, and the scrollviewer is a little thing crowded into the left hand side of the control. I'm looking at some ways to do that; stand by for an update.

Update

How to handle focus on mousedown without committing any sins against MVVM:

using System.ComponentModel;
using System.Windows;
using System.Windows.Input;

namespace MyRandomNamespace
{
    public static class Extensions
    {
        #region Extensions.MouseDownFocusRecipient Attached Property

        //  Attached property. See XAML example below for usage.
        //  On mouse down, sets focus on bound target control.

        public static UIElement GetMouseDownFocusRecipient(UIElement obj)
        {
            return (UIElement)obj.GetValue(MouseDownFocusRecipientProperty);
        }

        public static void SetMouseDownFocusRecipient(UIElement obj, UIElement value)
        {
            obj.SetValue(MouseDownFocusRecipientProperty, value);
        }

        public static readonly DependencyProperty MouseDownFocusRecipientProperty =
            DependencyProperty.RegisterAttached("MouseDownFocusRecipient", typeof(UIElement), typeof(Extensions),
                new PropertyMetadata(null, MouseDownFocusRecipient_PropertyChanged));

        private static void MouseDownFocusRecipient_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var target = d as UIElement;

            //  Target must have some kind of background color or it will ignore mouse events.
            //  We can't do this object-orientedly because multiple Background dependency
            //  properties are defined in multiple control classes.

            var bkgDepProp = DependencyPropertyDescriptor.FromName("Background", target.GetType(), target.GetType(), true);

            if (bkgDepProp != null && bkgDepProp.GetValue(target) == null)
            {
                bkgDepProp.SetValue(target, System.Windows.Media.Brushes.Transparent);
            }

            //target.IsHitTestVisible = true;
            target.PreviewMouseDown -= Target_PreviewMouseDown;
            target.PreviewMouseDown += Target_PreviewMouseDown;
        }

        private static void Target_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var target = (UIElement)sender;

            var otherControl = GetMouseDownFocusRecipient(target);

            if (otherControl != null)
            {
                Keyboard.Focus(otherControl);
            }
        }
        #endregion Extensions.MouseDownFocusRecipient Attached Property
    }
}

XAML:

<ControlTemplate TargetType="{x:Type TextBoxBase}" x:Key="TextBoxTemplate">
    <Border
        Name="Border"
        Padding="2"
        Background="{DynamicResource White#}"
        local:Extensions.MouseDownFocusRecipient="{Binding ElementName=PART_ContentHost}"
        >
        <StackPanel
            VerticalAlignment="Center"
            MouseDown="StackPanel_MouseDown"
            >
            <ScrollViewer
                Margin="0"
                x:Name="PART_ContentHost"
                HorizontalAlignment="Left"
                />
            <Rectangle
                x:Name="Rect1"
                Width="{Binding ActualWidth, ElementName=PART_ContentHost}"
                Height="8"
                Fill="{TemplateBinding Foreground}" Opacity="0.8"
                IsHitTestVisible="False"
                HorizontalAlignment="Left"
                />
        </StackPanel>
    </Border>
</ControlTemplate>


问:
Suspected Java Context Loader that uses files that no longer exists
I'm writing a test case that loads variables from the resources of my tests and loads them into a Properties object. It checks if there is a type of file that only exists in a Docker container when it is generated by configuration related to the Docker container. Let me be clear: config.alt.properties doesn't currently exist in my file system, but it used to and I believe I once ran these tests while it did exist. When I run this within my eclipse environment, I found out via a Debugger that the ContextClassLoader pulls the file out of thin air, and loads it with the values that were once in that file, but different from the normal config.properties file.

```<code>props = new Properties();
try (InputStream altInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.alt.properties")) {
        if(altInput != null){
            props.load(altInput);
        }
        else{
            LOG.info("Using environment props file");
            InputStream envInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
            props.load(envInput);
        }
    } catch (IOException e){
        e.printStackTrace();
    }
</code>```

Why is this happening? And more importantly, how do I get the ContextClassLoader to forget about this file that isn't here anymore? Here is my project structure:

```<code>src/main/java: {empty}
src/main/resources: rebel.xml
src/test/java: testClass.Java (where code is from)
src/test/resources: config.properties, log4j2.xml
</code>```

I have tried to use the other methods of resource loading mentioned here but all of the other methods lead to the program not finding any files at all including config.properties.

Any help is appreciated, thank you.

EDIT: The tests are running using JUnit, I don't know if that matters or not. Here is the JUnit info in the pom.XML

Under dependencies:

```<code><dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
</dependency>
</code>```

and under dependencyManagement

```<code><dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
</dependency>
</code>```

答:
You said the file does not exist in filesystem, but it seems you only looked for it under the sources directory. But at runtime the program uses resource files under target directory (they are copied there at build-time, at "process-resources" phase of default lifecycle), so the only explanation I see, and quick solution is to mvn clean (or use "Clean project" feature in Eclipse).

To verify where the file is taken from, right before you get it as stream, try Thread.currentThread().getContextClassLoader().getResource("config.alt.properties"), log the value, and verify the location it points to.

Body:
I'm writing a test case that loads variables from the resources of my tests and loads them into a Properties object. It checks if there is a type of file that only exists in a Docker container when it is generated by configuration related to the Docker container. Let me be clear: config.alt.properties doesn't currently exist in my file system, but it used to and I believe I once ran these tests while it did exist. When I run this within my eclipse environment, I found out via a Debugger that the ContextClassLoader pulls the file out of thin air, and loads it with the values that were once in that file, but different from the normal config.properties file.

props = new Properties();
try (InputStream altInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.alt.properties")) {
        if(altInput != null){
            props.load(altInput);
        }
        else{
            LOG.info("Using environment props file");
            InputStream envInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
            props.load(envInput);
        }
    } catch (IOException e){
        e.printStackTrace();
    }

Why is this happening? And more importantly, how do I get the ContextClassLoader to forget about this file that isn't here anymore? Here is my project structure:

src/main/java: {empty}
src/main/resources: rebel.xml
src/test/java: testClass.Java (where code is from)
src/test/resources: config.properties, log4j2.xml

I have tried to use the other methods of resource loading mentioned here but all of the other methods lead to the program not finding any files at all including config.properties.

Any help is appreciated, thank you.

EDIT: The tests are running using JUnit, I don't know if that matters or not. Here is the JUnit info in the pom.XML

Under dependencies:

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
</dependency>

and under dependencyManagement

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
</dependency>


问:
Counting Rows Based on Exist Condition
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

```<code>CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)
</code>```

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

```<code>| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |
</code>```

So here is what I have so far:

```<code>DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId
</code>```

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

答:
It's as simple as doing the opposite</p>

```<code>DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedToMe,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN null ELSE 0 END) AS AssignedToOthers

FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId
</code>```

Title: Counting Rows Based on Exist Condition

Body:
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |

So here is what I have so far:

DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

Body:
It's as simple as doing the opposite

DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedToMe,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN null ELSE 0 END) AS AssignedToOthers

FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId


问:
Unable to fetch code from git repository for a specific SHA in ansible
I want to fetch code using a particular SHA-id.This is what I am trying

```<code>- git:
        repo: http://<git-url>/Vara-Internal/mongo-db-dev.git
        dest: "{{ app_path }}/{{ app_dir }}"
        version: "{{ GIT_TAG }}"
        refspec: '+refs/heads/{{ GIT_TAG }}:refs/remotes/origin/{{ GIT_TAG }}'
        update: yes
        force: true
      register: cloned
</code>```

It throwing me this error

```<code>FAILED! => {"changed": false, "cmd": ["/usr/bin/git", "fetch", "--tags", "origin", "+refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e:refs/remotes/origin/dbde451f203a112d0838fb09bc19ed28bd231e6e"], "failed": true, "msg": "Failed to download remote objects and refs:  fatal: Couldn't find remote ref refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e\n"}
</code>```

答:
I used indirect method to the same.I have save commit ids in a file and added following code

```<code>- name: Reverting Changes
      command: "git reset --hard {{ GIT_TAG }}"
      args:
        chdir: "{{ app_path }}/{{ app_dir }}"
      when: build_type  == "revert"
</code>```

i.e. I took an extra variable which is build_type and checked whether this is for revert the changes.If it is then i read the commit id from my git information file and hard reset my branch.

Body:
I want to fetch code using a particular SHA-id.This is what I am trying

- git:
        repo: http://<git-url>/Vara-Internal/mongo-db-dev.git
        dest: "{{ app_path }}/{{ app_dir }}"
        version: "{{ GIT_TAG }}"
        refspec: '+refs/heads/{{ GIT_TAG }}:refs/remotes/origin/{{ GIT_TAG }}'
        update: yes
        force: true
      register: cloned

It throwing me this error

FAILED! => {"changed": false, "cmd": ["/usr/bin/git", "fetch", "--tags", "origin", "+refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e:refs/remotes/origin/dbde451f203a112d0838fb09bc19ed28bd231e6e"], "failed": true, "msg": "Failed to download remote objects and refs:  fatal: Couldn't find remote ref refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e\n"}

Body:
I used indirect method to the same.I have save commit ids in a file and added following code

- name: Reverting Changes
      command: "git reset --hard {{ GIT_TAG }}"
      args:
        chdir: "{{ app_path }}/{{ app_dir }}"
      when: build_type  == "revert"

i.e. I took an extra variable which is build_type and checked whether this is for revert the changes.If it is then i read the commit id from my git information file and hard reset my branch.


问:
UnityWebRequest and Azure Bot issue
I am currently trying to link a Unity application to my bot messaging endpoint in portal Azure. To do this, I use a UnityWebRequest.GET call as explained in Unity doc (https://docs.unity3d.com/Manual/UnityWebRequest-RetrievingTextBinaryData.html).

The fact is that I always encounter the same issue when I launch the app: The HTTP 'GET' method is not supported by the 'GenericJsonWebHookReceiver' WebHook receiver

I have no idea of how or where do I have to make changes in order to solve this. Does anyone facing the same issue?

Here is my code:

```<code>IEnumerator GetText()
{
    UnityWebRequest www = UnityWebRequest.Get("<messaging endpoint of the bot>");
    yield return www.Send();

    if (www.isError)
    {
        Debug.Log(www.error);
    }
    else
    {
        // Show results as text
        Debug.Log(www.downloadHandler.text);

        // Or retrieve results as binary data
        byte[] results = www.downloadHandler.data;
    }
}
</code>```

答:
The error you are seeing doesn't have anything to do with Unity, but https://[YourBotId].azurewebsites.net/api/messages is not callable via Get, it is a Post method.  If you navigate to the /api/messages path in a browser, you'll see the same error message.

Have you tried Posting an Activity to the messages endpoint?

I haven't tried this out, but maybe it can help you: https://github.com/tompaana/bot-direct-line-for-unity

Title: UnityWebRequest and Azure Bot issue

Body:
I am currently trying to link a Unity application to my bot messaging endpoint in portal Azure. To do this, I use a UnityWebRequest.GET call as explained in Unity doc (https://docs.unity3d.com/Manual/UnityWebRequest-RetrievingTextBinaryData.html).

The fact is that I always encounter the same issue when I launch the app: The HTTP 'GET' method is not supported by the 'GenericJsonWebHookReceiver' WebHook receiver

I have no idea of how or where do I have to make changes in order to solve this. Does anyone facing the same issue?

Here is my code:

IEnumerator GetText()
{
    UnityWebRequest www = UnityWebRequest.Get("<messaging endpoint of the bot>");
    yield return www.Send();

    if (www.isError)
    {
        Debug.Log(www.error);
    }
    else
    {
        // Show results as text
        Debug.Log(www.downloadHandler.text);

        // Or retrieve results as binary data
        byte[] results = www.downloadHandler.data;
    }
}


问:
Explicit vs implicit SQL joins
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

```<code>SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
</code>```

vs.

```<code>SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
</code>```

答:
Performance wise, they are exactly the same (at least in SQL Server) but be aware that they are deprecating this join syntax and it's not supported by sql server2005 out of the box.

I think you are thinking of the deprecated *= and =* operators vs. "outer join".

I have just now tested the two formats given, and they work properly on a SQL Server 2008 database.  In my case they yielded identical execution plans, but I couldn't confidently say that this would always be true.

OwnerDisplayName: dmanxiii

Title: Explicit vs implicit SQL joins

Body:
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;

vs.

SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;

LastEditorDisplayName: Eric Z Beard

OwnerDisplayName: Joshdan


问:
HTTP Connection in Iphone
Since I'm new in iphone I need help in learning about http Connections in Iphone.
Please guide me to some tutorials so that I could learn some http connections tricks in iphone and could communicate with websites.

Also please guide me through some Sample code for the following problem:
I want to send some "Hello world" text to the site and got a reply back from the Web the same word with adiition of s i.e. "Hello Worlds".. please brothers guide me through any sample code.. it's a part of my application that I'm developing in iphone.

答:
i too new ,but i have sent  some msg(soap xml) via http request .my sample code is...
   </p>

<p>```<code></p>

<p>// get host address
NSURL *url = [NSURL URLWithString:@"http://xyz.com"];
NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:url];</p>

<p>// find msg length, here x is my msg
NSString *msgLength = [NSString stringWithFormat:@"%d", [x length]];</p>

<p>// specify  type of msg which u have to send to the host(mine is xml)
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// name space which optional one
[theRequest addValue: @"http://mpack.h.org" forHTTPHeaderField:@"SOAPAction"];</p>

<p>[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
//type of http method
[theRequest setHTTPMethod:@"POST"];
// msg which is need to send to server
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];</p>

<p>// establish connection to host
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];</p>

<p>if( theConnection )
{
    webData = [[NSMutableData data] retain];
    NSLog(@"Connecting....");</p>

<p>}
else
{
NSLog(@"theConnection is NULL");</p>

<p>}</p>

<p>}</p>

<p>// delegate method for NSURLConnection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with theConenction %@",error);
    [connection release];
    [webData release];</p>

<p>}
// u ll get response here
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"DONE. Received Bytes: %d", [webData length]);</p>

<p>}
```</code></p>

Title: HTTP Connection in Iphone

Body:
i too new ,but i have sent  some msg(soap xml) via http request .my sample code is...

// get host address
NSURL *url = [NSURL URLWithString:@"http://xyz.com"];
NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:url];

// find msg length, here x is my msg
NSString *msgLength = [NSString stringWithFormat:@"%d", [x length]];

// specify  type of msg which u have to send to the host(mine is xml)
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// name space which optional one
[theRequest addValue: @"http://mpack.h.org" forHTTPHeaderField:@"SOAPAction"];

[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
//type of http method
[theRequest setHTTPMethod:@"POST"];
// msg which is need to send to server
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

// establish connection to host
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if( theConnection )
{
    webData = [[NSMutableData data] retain];
    NSLog(@"Connecting....");

}
else
{
NSLog(@"theConnection is NULL");

}

}

// delegate method for NSURLConnection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with theConenction %@",error);
    [connection release];
    [webData release];

}
// u ll get response here
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"DONE. Received Bytes: %d", [webData length]);

}


问:
what is the use setItemChecked method for a listview
what is the use of setItemChecked method for a ListView?
where can we use setItemChecked method for a ListView and why do we use it?</p>

答:
I haven't used list views for a few years, I only use Recycler views, so my answer is based on brief research and intuition.
Based on this thread and this thread and this documentation

I believe this method is to set that item in the listView as "selected".
In some apps you can long press a list item to mark it as selected, so you can perform some action on it; for example, in contacts, you can select multiple contacts from the list and delete them together, or in gallery long click an image to edit or delete it etc.

So if you want to programatically select an item as checked/selected, you can use this method.


问:
upload maven project file on save to google app engine like netbeans
I am new to eclipse and spring maven projects, I want to auto upload files whenever changes are  made to it. I am using google app engine, I want to upload files on google app engine, like in netbeans, it sync file with server whenever changes are made.
Please Help.
Thanks</p>

答:
The new Cloud Tools for Eclipse doesn't support this directly.  And to be honest, it's not an approach I'd recommend: it's better to launch and debug it locally (Debug As > App Engine Standard) and then use Deploy to deploy your working version.

That said, providing you use an external build tool like Maven, you could add your own builder to build and deploy your war on each build.  To do so:

Right-click on your project and select Properties

Navigate to the Builders tab.

Select New… and select the Program configuration type

In the Edit Configuration dialog:

the Location is the path to your program (mvn)

the Working Directory would be the location of your project; use the Browse Workspace… button to select your project

the Arguments will be package appengine:deploy

Then switch to the Build Options tab and you'll like wan to add During auto builds too, to cause the action to happen on save.

All of this assumes your pom.xml is properly configured.  See the Maven and App Engine Plugin page for details.  You could use Gradle too with the same approach.


问:
Can't find ghostscript in NLTK?
I'm playing around with NLTK, when I try to use the chunk module

```<code>enter import nltk as nk
Sentence  = "Betty Botter bought some butter, but she said the butter is  bitter, I f I put it in my batter, it will make my batter bitter."
tokens = nk.word_tokenize(Sentence)
tagged = nk.pos_tag(tokens)
entities = nk.chunk.ne_chunk(tagged)
</code>```

The code runs fine, when I type

```<code>>> entities
</code>```

I get the following error message:

```<code>enter code here Out[2]: Tree('S', [Tree('PERSON', [('Betty', 'NNP')]), Tree('PERSON', [('Botter', 'NNP')]), ('bought', 'VBD'), ('some', 'DT'), ('butter', 'NN'), (',', ','), ('but', 'CC'), ('she', 'PRP'), ('said', 'VBD'), ('the', 'DT'), ('butter', 'NN'), ('is', 'VBZ'), ('bitter', 'JJ'), (',', ','), ('I', 'PRP'), ('f', 'VBP'), ('I', 'PRP'), ('put', 'VBD'), ('it', 'PRP'), ('in', 'IN'), ('my', 'PRP$'), ('batter', 'NN'), (',', ','), ('it', 'PRP'), ('will', 'MD'), ('make', 'VB'), ('my', 'PRP$'), ('batter', 'NN'), ('bitter', 'NN'), ('.', '.')])Traceback (most recent call last):

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\IPython\core\formatters.py", line 343, in __call__
return method()

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\tree.py", line 726, in _repr_png_
subprocess.call([find_binary('gs', binary_names=['gswin32c.exe', 'gswin64c.exe'], env_vars=['PATH'], verbose=False)] +

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 602, in find_binary
binary_names, url, verbose))

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 596, in find_binary_iter
url, verbose):

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 567, in find_file_iter
raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))

LookupError:

===========================================================================
NLTK was unable to find the gs file!
Use software specific configuration paramaters or set the PATH environment variable.
===========================================================================
</code>```

According to this post, the solution is to install Ghostscript, since the chunker is trying to use it to display a parse tree, and is looking for one of 3 binaries:

```<code>file_names=['gs', 'gswin32c.exe', 'gswin64c.exe']
</code>```

to use.
But even though I installed ghostscript and I can now find the binary in a windows search, but I am still getting the same error.

What do I need to fix or update?

Additional path information:

```<code>import os; print os.environ['PATH']
</code>```

Returns:

```<code>C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Scripts;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Program Files (x86)\Parallels\Parallels Tools\Applications;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Oracle\RPAS14.1\RpasServer\bin;C:\Oracle\RPAS14.1\RpasServer\applib;C:\Program Files (x86)\Java\jre7\bin;C:\Program Files (x86)\Java\jre7\bin\client;C:\Program Files (x86)\Java\jre7\lib;C:\Program Files (x86)\Java\jre7\jre\bin\client;C:\Users\QP19\AppData\Local\Continuum\Anaconda2;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Scripts;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;
</code>```

答:
Download gs.exe from "https://www.ghostscript.com/download/gsdnld.html" and add its path to Environment Variables

Path may be stored at

C:\Program Files\

(in my system it looks like "C:\Program Files\gs\gs9.21\bin")

and for adding it to environment variable:

control panel->system and security->system->advanced system
  settings->Environment Variables->(in system variables scroll down and
  double click on path)->

and then add the copied path

(in my case "C:\Program Files\gs\gs9.21\bin")

P.S.: Don't forget to add semicolon (;) before coping the path instead of deleting the existing paths and then simply putting it there, you might get into trouble and would need to run backup :)

Title: Can't find ghostscript in NLTK?

Body:
I'm playing around with NLTK, when I try to use the chunk module

enter import nltk as nk
Sentence  = "Betty Botter bought some butter, but she said the butter is  bitter, I f I put it in my batter, it will make my batter bitter."
tokens = nk.word_tokenize(Sentence)
tagged = nk.pos_tag(tokens)
entities = nk.chunk.ne_chunk(tagged)

The code runs fine, when I type

>> entities

I get the following error message:

enter code here Out[2]: Tree('S', [Tree('PERSON', [('Betty', 'NNP')]), Tree('PERSON', [('Botter', 'NNP')]), ('bought', 'VBD'), ('some', 'DT'), ('butter', 'NN'), (',', ','), ('but', 'CC'), ('she', 'PRP'), ('said', 'VBD'), ('the', 'DT'), ('butter', 'NN'), ('is', 'VBZ'), ('bitter', 'JJ'), (',', ','), ('I', 'PRP'), ('f', 'VBP'), ('I', 'PRP'), ('put', 'VBD'), ('it', 'PRP'), ('in', 'IN'), ('my', 'PRP$'), ('batter', 'NN'), (',', ','), ('it', 'PRP'), ('will', 'MD'), ('make', 'VB'), ('my', 'PRP$'), ('batter', 'NN'), ('bitter', 'NN'), ('.', '.')])Traceback (most recent call last):

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\IPython\core\formatters.py", line 343, in __call__
return method()

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\tree.py", line 726, in _repr_png_
subprocess.call([find_binary('gs', binary_names=['gswin32c.exe', 'gswin64c.exe'], env_vars=['PATH'], verbose=False)] +

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 602, in find_binary
binary_names, url, verbose))

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 596, in find_binary_iter
url, verbose):

File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 567, in find_file_iter
raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))

LookupError:

===========================================================================
NLTK was unable to find the gs file!
Use software specific configuration paramaters or set the PATH environment variable.
===========================================================================

According to this post, the solution is to install Ghostscript, since the chunker is trying to use it to display a parse tree, and is looking for one of 3 binaries:

file_names=['gs', 'gswin32c.exe', 'gswin64c.exe']

to use.
But even though I installed ghostscript and I can now find the binary in a windows search, but I am still getting the same error.

What do I need to fix or update?

Additional path information:

import os; print os.environ['PATH']

Returns:

C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Scripts;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Program Files (x86)\Parallels\Parallels Tools\Applications;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Oracle\RPAS14.1\RpasServer\bin;C:\Oracle\RPAS14.1\RpasServer\applib;C:\Program Files (x86)\Java\jre7\bin;C:\Program Files (x86)\Java\jre7\bin\client;C:\Program Files (x86)\Java\jre7\lib;C:\Program Files (x86)\Java\jre7\jre\bin\client;C:\Users\QP19\AppData\Local\Continuum\Anaconda2;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Scripts;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;