问:
How to change the marker and draw a line between dots in matlab
I have this code that I am trying to plot:

```<code>battery_aH=55;
hour_of_battery_work=12;
one_battery_price=147.96;
system_amper=1;
while system_amper<20
    discharge_battery=1;
    [num_of_battery]=num_of_battery1(system_amper,hour_of_battery_work,battery_aH,discharge_battery);
    [total_price]=total_price1(one_battery_price,num_of_battery);
    plot(total_price,system_amper,'markersize', 30,)
    system_amper=system_amper+1;
end
xlabel('price(€)','fontname','times','fontsize',16);
ylabel('Energy of the system[aH]','fontname','times','fontsize',16);

hold off
</code>```

The thing is that when I run this code I am getting small dots.
Can I change the type of mark through the code (not the size)? Can I draw a line between these dots through the code and after it make the dots disappear?

答:
You can specify any line properties as parameter/value arguments to plot. In your case, you should be able to specify the Marker, MarkerSize, and LineStyle properties

```<code>plot(total_price, system_amper, 'Marker', '*', 'MarkerSize', 30, 'LineStyle', '-')
</code>```

Alternately, you can store the graphics handle to the line object produced by plot and use set to modify the properties

```<code>h = plot(total_price, system_amper);
set(h, 'Marker', '*', 'MarkerSize', 30, 'LineStyle', '-')
</code>```

Body:
I have this code that I am trying to plot:

battery_aH=55;
hour_of_battery_work=12;
one_battery_price=147.96;
system_amper=1;
while system_amper<20
    discharge_battery=1;
    [num_of_battery]=num_of_battery1(system_amper,hour_of_battery_work,battery_aH,discharge_battery);
    [total_price]=total_price1(one_battery_price,num_of_battery);
    plot(total_price,system_amper,'markersize', 30,)
    system_amper=system_amper+1;
end
xlabel('price(€)','fontname','times','fontsize',16);
ylabel('Energy of the system[aH]','fontname','times','fontsize',16);

hold off

The thing is that when I run this code I am getting small dots.
Can I change the type of mark through the code (not the size)? Can I draw a line between these dots through the code and after it make the dots disappear?

Body:
You can specify any line properties as parameter/value arguments to plot. In your case, you should be able to specify the Marker, MarkerSize, and LineStyle properties

plot(total_price, system_amper, 'Marker', '*', 'MarkerSize', 30, 'LineStyle', '-')

Alternately, you can store the graphics handle to the line object produced by plot and use set to modify the properties

h = plot(total_price, system_amper);
set(h, 'Marker', '*', 'MarkerSize', 30, 'LineStyle', '-')


来源: stackexchange

问:
Generate a sequence of numbers with repeated intervals
I am trying to create sequences of number of 6 cases, but with 144 cases intervals.

Like this one for example

```<code>c(1:6, 144:149, 288:293)

1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293
</code>```

How could I generate automatically such a sequence with

```<code>seq
</code>```

or with another function ?

答:
I am using R 3.3.2.  OSX 10.9.4

I tried:

```<code>a<-c()  # stores expected sequence
f<-288  # starting number of final sub-sequence
it<-144 # interval
for (d in seq(0,f,by=it))
{
    if (d==0)
    {
        d=1
    }
    a<-c(a, seq(d,d+5))
    print(d)
}
print(a)
</code>```

AND the expected sequence stores in a.

[1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293

And another try:

```<code>a<-c()  # stores expected sequence
it<-144 # interval
lo<-4   # number of sub-sequences
for (d in seq(0,by=it, length.out = lo))
{
    if (d==0)
    {
        d=1
    }
    a<-c(a, seq(d,d+5))
    print(d)
}
print(a)
</code>```

The result:

[1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293 432 433 434 435 436 437

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create sequences of number of 6 cases, but with 144 cases intervals.

Like this one for example

c(1:6, 144:149, 288:293)

1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293

How could I generate automatically such a sequence with

seq

or with another function ?

Body:
I am using R 3.3.2.  OSX 10.9.4

I tried:

a<-c()  # stores expected sequence
f<-288  # starting number of final sub-sequence
it<-144 # interval
for (d in seq(0,f,by=it))
{
    if (d==0)
    {
        d=1
    }
    a<-c(a, seq(d,d+5))
    print(d)
}
print(a)

AND the expected sequence stores in a.

[1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293

And another try:

a<-c()  # stores expected sequence
it<-144 # interval
lo<-4   # number of sub-sequences
for (d in seq(0,by=it, length.out = lo))
{
    if (d==0)
    {
        d=1
    }
    a<-c(a, seq(d,d+5))
    print(d)
}
print(a)

The result:

[1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293 432 433 434 435 436 437

ContentLicense: CC BY-SA 3.0


问:
How can I take three consecutive terms of an array every nth terms?
Can anyone guide me on how to select several consecutive terms of an array (e.g. 3) every nth element from a 1D vector using MATLAB codes?

E.g if my array is array = [1 2 3 4 5 6 7 8 9 10 11 12];
I want to take three consecutive terms jumping four afterwards, so the solution would be array_solution = [1 2 3 8 9 10];

Thank you very much.

答:
use bsxfun to add two index vectors (column and row):

```<code>x = [1 2 3 4 5 6 7 8 9 10 11 12];
len = length(x); % total array length
c = 3; % number of consecutive elements
n = 4; % every nth element
idxs = bsxfun(@plus,(1:c)',0:(c+n):len);
y = x(idxs(:))

    y =

     [1     2     3     8     9    10]
</code>```

Body:
use bsxfun to add two index vectors (column and row):

x = [1 2 3 4 5 6 7 8 9 10 11 12];
len = length(x); % total array length
c = 3; % number of consecutive elements
n = 4; % every nth element
idxs = bsxfun(@plus,(1:c)',0:(c+n):len);
y = x(idxs(:))

    y =

     [1     2     3     8     9    10]


问:
Show names with 3 words only in SQL Server database
I have a database with table contains information about employees in my company.
I need a SQL statement to show all names whose have 3 parts like "haitham samey hegazy" and who less or more than 3 parts didn't shown in the condition result.
I try to use like operator but it doesn't work and my database is in Arabic language. </p>

<p>Thanks for helping... </p>

答:
Assuming names are separated by a single space, you can get at least three parts using:

```<code>where name like '% % %'
</code>```

You can get exactly three parts using:

```<code>where name like '% % %' and name not like '% % % %'
</code>```

Body:
I have a database with table contains information about employees in my company.
I need a SQL statement to show all names whose have 3 parts like "haitham samey hegazy" and who less or more than 3 parts didn't shown in the condition result.
I try to use like operator but it doesn't work and my database is in Arabic language.

Thanks for helping...

Body:
Assuming names are separated by a single space, you can get at least three parts using:

where name like '% % %'

You can get exactly three parts using:

where name like '% % %' and name not like '% % % %'


问:
abstract method async and sync implementation in Python
Let's say I have BaseClass which contains some logic in main_function() which is common for both SyncClass and AsyncClass. Let's say those 2 classes have their unique implementation of get_data() and the former gets in synchronous manner, while the latter in asynchronous manner. I have written something like this and it seems to work:

```<code>class BaseClass:
    def get_data():
        pass

    @gen.coroutine
    def main_function():
        # some logic
        try:
            data = yield self.get_data()
        except:
            data = self.get_data()
        # some more logic

class SyncClass(BaseClass):
    def get_data():
        //makes sync call to Mongo and gets data (using Mongoengine)

class AsyncClass(BaseClass):
    @gen.coroutine
    def get_data():
        //makes async call to Mongo and gets data (using Motorengine)
</code>```

I used this code as a workaround, because I already had those methods for get_data() implemented that way. Is there some more elegant solution? There are 2 parts of my code that concern me:

```<code>try:
    data = yield self.get_data()
except:
    data = self.get_data()
</code>```

I would prefer not to use try/except here.

The other thing is: I have @gen.coroutine in the AsyncClass while the same function isn't decorated with @gen.coroutine in the BaseClass.

Thank you!

答:
Synchronous and asynchronous methods have different interfaces (that's what it means to be asynchronous). AsyncClass.get_data returns a Future; SyncClass.get_data does not. If this were in a statically-typed language, these two methods would not be able to implement the same abstract method from the base class. Of course, Python is more flexible and does not restrict you in this way, but the caller still needs to either know which kind of method it's dealing with or be prepared to find out via try/except or isinstance checks, etc. (note that try/except is dangerous in this case, because yield in a tornado coroutine will accept things like lists and dicts)

In general, you cannot transparently switch between them as you're hoping to do here. Remember that any function that may call yield self.get_data() also needs to be decorated with @coroutine, so once one part of your system is asynchronous, it starts to spread. It's usually best to embrace this trend and just make things asynchronous.

Body:
Let's say I have BaseClass which contains some logic in main_function() which is common for both SyncClass and AsyncClass. Let's say those 2 classes have their unique implementation of get_data() and the former gets in synchronous manner, while the latter in asynchronous manner. I have written something like this and it seems to work:

class BaseClass:
    def get_data():
        pass

    @gen.coroutine
    def main_function():
        # some logic
        try:
            data = yield self.get_data()
        except:
            data = self.get_data()
        # some more logic

class SyncClass(BaseClass):
    def get_data():
        //makes sync call to Mongo and gets data (using Mongoengine)

class AsyncClass(BaseClass):
    @gen.coroutine
    def get_data():
        //makes async call to Mongo and gets data (using Motorengine)

I used this code as a workaround, because I already had those methods for get_data() implemented that way. Is there some more elegant solution? There are 2 parts of my code that concern me:

try:
    data = yield self.get_data()
except:
    data = self.get_data()

I would prefer not to use try/except here.

The other thing is: I have @gen.coroutine in the AsyncClass while the same function isn't decorated with @gen.coroutine in the BaseClass.

Thank you!


答:
You are plotting the points one-by-one in the 'while' loop. That's why they are not connected together.

What you want to do is to store all the points in an array and then plot them all at once. Then you can change the line and mark specs using plot options.

Title: How to change the marker and draw a line between dots in matlab


问:
sap.m.ComboBox - value is cleared, but item is still selected

I have a strange issue with ComboBox:

The control is located in xml fragment, inside sap.m.IconTabFilter.

I select a value in the combobox, then select another IconTabFilter.

Then I return to the previous tab, where the combobox is located.

The value of the combobox is cleared (I see a placeholder again), but when I open the dropdown menu of the combobox, I see that the item I have selected previously is highlighted and I can't select it again, like it's already been selected.

No function runs when switching tabs, no models are refreshed.

I tried to reproduce the issue, but my new code snippet works fine - the value is not cleared when I switch tabs.
What could it be?

Here is one of the ComboBoxes' definition:

<ComboBox id="comboid" items="{path: 'modelName>/'}"  placeholder="{i18n>select}" selectionChange="onChange" customData:userProfileSetting="userId">
    <core:Item text="{modelName>ID} {modelName>VALUE}" key="{modelName>ID}"/>
</ComboBox>
```

答:
The root of problem was the low version of sapui5.
After upgrading from 1.28.4 to 1.28.44 (I'm limited to 1.28) it works fine.</p>


问:
Refreshing Watch App From Watch
I started messing around with the Watch OS framework today and wanted to throw together a quick app, but have come to a couple questions.

I made an iOS app that just shows the current battery % as well as the state of the battery. I then wanted to show that over on the watch.

The only time the watch app will update is when I totally close the iOS app, then open it, while the watch app is active. How do I allow my watch app to be updated if I open it after the iOS app has been opened?

This kind of goes with number 2. But how do I allow the watch app to fetch info from the iOS app, after it has been in the background? As an example, lets say the iOS app has been in the background and I wanted to fetch the battery % without opening the iOS app to the foreground.

Some side notes on how I set this up -

Within the iOS app, in the viewDidLoad method, I start my session.

```<code> if ([WCSession isSupported]) {
    wcSession = [WCSession defaultSession];
    wcSession.delegate = self;
    [wcSession activateSession];
}
</code>```

Then call my method to update the actual battery % and state. Within that method, I have this which sends the info over to the watch:

```<code>NSDictionary *message = @{
                          @"message" : [NSString stringWithFormat:@"%@", [numberFormatter stringFromNumber:levelObj]],
                          @"message_2" : [NSString stringWithFormat:@"%ld",(long)[UIDevice currentDevice].batteryState],

                          };

[wcSession sendMessage:message replyHandler:nil errorHandler:^(NSError * _Nonnull error) {
    NSLog(@"%@", error.localizedDescription);
}];
</code>```

I also call this same method in the viewDidAppear, so I don't have to relaunch the app completely, to allow refreshing of the watch counterpart.

On the watch side I have the viewWillActivate method with the same activation as the iOS side as well as the method to handle what the watch app receives from the iOS side. But it will only update when I restart the iOS app fully.

```<code>    - (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message {

    NSLog(@"Message recieved!");
    [_batteryLevelLabelW setText:message[@"message"]];
}
</code>```

Also in there is the code to handle the battery state message, which is a bit long.

I hope I gave a good amount of information to help.

答:
According to documentation:

Use the sendMessage(_:replyHandler:errorHandler:) or
  sendMessageData(_:replyHandler:errorHandler:) method to
  transfer data to a reachable counterpart. These methods are intended
  for immediate communication between your iOS app and WatchKit
  extension. The isReachable property must currently be true for these
  methods to succeed.

If watchapp is not foreground, message will not be delivered since isReachable is false.

Method you should use is updateApplicationContext(_:) - it will wait till watch app will be opened at foreground and only then will be delivered.

Title: Refreshing Watch App From Watch

Body:
I started messing around with the Watch OS framework today and wanted to throw together a quick app, but have come to a couple questions.

I made an iOS app that just shows the current battery % as well as the state of the battery. I then wanted to show that over on the watch.

The only time the watch app will update is when I totally close the iOS app, then open it, while the watch app is active. How do I allow my watch app to be updated if I open it after the iOS app has been opened?

This kind of goes with number 2. But how do I allow the watch app to fetch info from the iOS app, after it has been in the background? As an example, lets say the iOS app has been in the background and I wanted to fetch the battery % without opening the iOS app to the foreground.

Some side notes on how I set this up -

Within the iOS app, in the viewDidLoad method, I start my session.

 if ([WCSession isSupported]) {
    wcSession = [WCSession defaultSession];
    wcSession.delegate = self;
    [wcSession activateSession];
}

Then call my method to update the actual battery % and state. Within that method, I have this which sends the info over to the watch:

NSDictionary *message = @{
                          @"message" : [NSString stringWithFormat:@"%@", [numberFormatter stringFromNumber:levelObj]],
                          @"message_2" : [NSString stringWithFormat:@"%ld",(long)[UIDevice currentDevice].batteryState],

                          };

[wcSession sendMessage:message replyHandler:nil errorHandler:^(NSError * _Nonnull error) {
    NSLog(@"%@", error.localizedDescription);
}];

I also call this same method in the viewDidAppear, so I don't have to relaunch the app completely, to allow refreshing of the watch counterpart.

On the watch side I have the viewWillActivate method with the same activation as the iOS side as well as the method to handle what the watch app receives from the iOS side. But it will only update when I restart the iOS app fully.

    - (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message {

    NSLog(@"Message recieved!");
    [_batteryLevelLabelW setText:message[@"message"]];
}

Also in there is the code to handle the battery state message, which is a bit long.

I hope I gave a good amount of information to help.


答:
You can use replace to count the number of spaces:

```<code>SELECT *
FROM Table
WHERE LEN(LTRIM(RTRIM(varcharColumn))) -
      LEN(REPLACE(LTRIM(RTRIM(varcharColumn)), ' ', '')) >= 2
</code>```

This will return all the rows where there are at least 2 spaces inside the varcharColumn.

Title: Show names with 3 words only in SQL Server database

Body:
You can use replace to count the number of spaces:

SELECT *
FROM Table
WHERE LEN(LTRIM(RTRIM(varcharColumn))) -
      LEN(REPLACE(LTRIM(RTRIM(varcharColumn)), ' ', '')) >= 2

This will return all the rows where there are at least 2 spaces inside the varcharColumn.


问:
Angular 2 how to handle asynchronous calls
First time button is clicked in form undefined is return, button has to be clicked twice to return correct result. How do I not process until result is return. When button clicked return correct result not previous one?

Product.componet.html

Product found

Price

Product details

{{ product.price }}

{{product.description}}

No Product found

```

<p>Product.compontent.ts</p>

<pre class="lang-typescript prettyprint-override"><code>onSubmit() {
    if (this.formModel.valid) {
        this.submitted = false;
        this.result = false;

        lens id = this.formModel.controls['id'].value;

        this.productService.getProductOne(id)
            .subscribe(product => this.product = product)

        //Check to see if object undefined
        if (this.product) {
            if (this.product.id != 0)
            {
                this.submitted = true;
            }
            else
            {
                this.result = true;
            }
        }
    }
}
</code>```

product-service.ts

  getProductOne(id: number): Observable<Product> {
      // Parameters obj
      let params: URLSearchParams = new URLSearchParams();
      params.set('id', id.toString());

      //Http request
      return this.http
          .get("api/getProduct", {
              search: params
          })
          .map(response => response.json())
          .catch(handleError);
  }
```

<p>Web api – ProductController.cs   </p>

<pre class="lang-csharp prettyprint-override"><code> [Route("api/getProduct")]
    public Product GetProduct(int id)
    {
        var product = products.FirstOrDefault((p) => p.id == id);

        if (product == null)
        {
            product = new Product();
        }

        return product;
    }
</code>```

答:
This happens because of this product => this.product = product. It assign product into this.product ,but before that program executes other codes which are after the  .subscribe(product => this.product = product)

what you need to do is just pass the observable to HTML and get values using | async pipe.like this.

Product.compontent.ts

```<code>  products: any;
  onSubmit() {
    if (this.formModel.valid) {
      this.submitted = false;
      this.result = false;

      lens id = this.formModel.controls['id'].value;
      this.products = this.productService.getProductOne(id);
    }
  }
</code>```

Product.componet.html

```<code><div [hidden]="!(products|async)?.id !=0">
  <h2>Product found</h2>
  <div class="row">
    <div class="col-xs-3">Price</div>
    <div class="col-xs-9  pull-left">Product details</div>
    <div class="col-xs-3">{{(products|async)?.price }}</div>
    <div class="col-xs-9  pull-left">{{(products|async)?.description }}</div>
  </div>
</div>
<div [hidden]="!(products|async)?.id ==0">
  <h2>No Product found</h2>
</div>
</code>```

Body:
First time button is clicked in form undefined is return, button has to be clicked twice to return correct result. How do I not process until result is return. When button clicked return correct result not previous one?

Product.componet.html

Product found

Price

Product details

{{ product.price }}

{{product.description}}

No Product found

Product.compontent.ts

onSubmit() {
    if (this.formModel.valid) {
        this.submitted = false;
        this.result = false;

        lens id = this.formModel.controls['id'].value;

        this.productService.getProductOne(id)
            .subscribe(product => this.product = product)

        //Check to see if object undefined
        if (this.product) {
            if (this.product.id != 0)
            {
                this.submitted = true;
            }
            else
            {
                this.result = true;
            }
        }
    }
}

product-service.ts

  getProductOne(id: number): Observable<Product> {
      // Parameters obj
      let params: URLSearchParams = new URLSearchParams();
      params.set('id', id.toString());

      //Http request
      return this.http
          .get("api/getProduct", {
              search: params
          })
          .map(response => response.json())
          .catch(handleError);
  }

Web api – ProductController.cs

 [Route("api/getProduct")]
    public Product GetProduct(int id)
    {
        var product = products.FirstOrDefault((p) => p.id == id);

        if (product == null)
        {
            product = new Product();
        }

        return product;
    }

Body:
This happens because of this product => this.product = product. It assign product into this.product ,but before that program executes other codes which are after the  .subscribe(product => this.product = product)

what you need to do is just pass the observable to HTML and get values using | async pipe.like this.

Product.compontent.ts

  products: any;
  onSubmit() {
    if (this.formModel.valid) {
      this.submitted = false;
      this.result = false;

      lens id = this.formModel.controls['id'].value;
      this.products = this.productService.getProductOne(id);
    }
  }

Product.componet.html

<div [hidden]="!(products|async)?.id !=0">
  <h2>Product found</h2>
  <div class="row">
    <div class="col-xs-3">Price</div>
    <div class="col-xs-9  pull-left">Product details</div>
    <div class="col-xs-3">{{(products|async)?.price }}</div>
    <div class="col-xs-9  pull-left">{{(products|async)?.description }}</div>
  </div>
</div>
<div [hidden]="!(products|async)?.id ==0">
  <h2>No Product found</h2>
</div>


问:
Rails - Not hitting while loop when creating classes
I have a create method in Rails where I am trying to create multiple objects in a while loop. For some reason it doesn't seem to be hitting the while loop so no objects are being created. The code is below:

```<code>def create
@user = User.find(params[:participant][:user_id])
@activity = Activity.find(params[:activity_id])
weeks = @activity.weeks
i = 1
while i <= weeks do
  puts "Test"
  participant = Participant.new
  participant.user_id = @user.id
  participant.activity_id = @activity.id
  participant.attended = false
  participant.paid = false
  participant.week = i
  participant.save

  i = i+1
end

redirect_to user_activities_path(@user, :id => @activity.id)

end
</code>```

The form I am using to submit is working fine as I can see from the console, and the redirect_to method at the end is working, so it just seems to be missing the loop. If it helps, the value of weeks is 10. Any help would be greatly appreciated.

答: If multiple Test have been output, try participant.save!, i think the participant save might fail, like some column not valid, so no objects are being created.

Body:
I have a create method in Rails where I am trying to create multiple objects in a while loop. For some reason it doesn't seem to be hitting the while loop so no objects are being created. The code is below:

def create
@user = User.find(params[:participant][:user_id])
@activity = Activity.find(params[:activity_id])
weeks = @activity.weeks
i = 1
while i <= weeks do
  puts "Test"
  participant = Participant.new
  participant.user_id = @user.id
  participant.activity_id = @activity.id
  participant.attended = false
  participant.paid = false
  participant.week = i
  participant.save

  i = i+1
end

redirect_to user_activities_path(@user, :id => @activity.id)

end

The form I am using to submit is working fine as I can see from the console, and the redirect_to method at the end is working, so it just seems to be missing the loop. If it helps, the value of weeks is 10. Any help would be greatly appreciated.


问:
How to fix my loop code in JAVA?
I'm trying to make it such that if the person typed anything else besides "BMW" or "AUDI" that they would get sent back to the point where they get to retype, I'm a beginner coder so please explain if possible :3 thanks a lot! Sorry if my code is messy still new to this and working on it!

edit: Thanks alot guys/girls for helping :3

```<code>import java.util.Scanner;

class MyClass {

public static void main(String[ ] args) {
  Vehicle V1 = new Vehicle();
  Vehicle V2 = new Vehicle();

  //Vehicle 1 (BMW)
  V1.setColour("Blue");
  V1.setFuel(56);
  V1.setWheels(3);
  V1.setMaxSpeed(150);
  //Vehicle 2 (AUDI)
  V2.setColour("Red");
  V2.setFuel(59);
  //Wheels and Max speed are on default...

      System.out.println("Choose from Audi or BMW");
      Scanner input = new Scanner(System.in);
      String q = input.next();
      while(q.equalsIgnoreCase("BMW") || q.equalsIgnoreCase("AUDI")){

      if (q.equalsIgnoreCase("BMW")){ // Prints BMW Car Specifications
          System.out.println("Here is the latest BMW Car specifications:");
          System.out.println("Colour: " + V1.getColour());
          System.out.println("Fuel Capacity: " + V1.getFuel() + " Liters");
          System.out.println("Wheel count: " + V1.getWheels());
          System.out.println("Maximum Speed: " + V1.getMaxSpeed() + " KM/H");
          break;
      }else if(q.equalsIgnoreCase("AUDI")){ //Prints AUDI Car Specifications
          System.out.println("Here is the latest AUDI Car specifications:");
          System.out.println("Colour: " + V2.getColour());
          System.out.println("Fuel Capacity: " + V2.getFuel() + " Liters");
          System.out.println("Wheel count: " + V2.getWheels());
          System.out.println("Maximum Speed: " + V2.getMaxSpeed() + " KM/H");
          break;
      }else{
          System.out.println("Sorry that is not a car manufacturer listed      (AUDI/BMW)");
      }
  }
}
}
</code>```

答:
You need to ask the user until he enters one of the correct words. So you have to do it like this:

```<code> String q = input.next();
 while(!q.equalsIgnoreCase("BMW") && !q.equalsIgnoreCase("AUDI")){
    q = input.next();
 }
</code>```

After that you can print out the information about the AUDI or BMW depending on what the user input was.

Title: How to fix my loop code in JAVA?

Body:
I'm trying to make it such that if the person typed anything else besides "BMW" or "AUDI" that they would get sent back to the point where they get to retype, I'm a beginner coder so please explain if possible :3 thanks a lot! Sorry if my code is messy still new to this and working on it!

edit: Thanks alot guys/girls for helping :3

import java.util.Scanner;

class MyClass {

public static void main(String[ ] args) {
  Vehicle V1 = new Vehicle();
  Vehicle V2 = new Vehicle();

  //Vehicle 1 (BMW)
  V1.setColour("Blue");
  V1.setFuel(56);
  V1.setWheels(3);
  V1.setMaxSpeed(150);
  //Vehicle 2 (AUDI)
  V2.setColour("Red");
  V2.setFuel(59);
  //Wheels and Max speed are on default...

      System.out.println("Choose from Audi or BMW");
      Scanner input = new Scanner(System.in);
      String q = input.next();
      while(q.equalsIgnoreCase("BMW") || q.equalsIgnoreCase("AUDI")){

      if (q.equalsIgnoreCase("BMW")){ // Prints BMW Car Specifications
          System.out.println("Here is the latest BMW Car specifications:");
          System.out.println("Colour: " + V1.getColour());
          System.out.println("Fuel Capacity: " + V1.getFuel() + " Liters");
          System.out.println("Wheel count: " + V1.getWheels());
          System.out.println("Maximum Speed: " + V1.getMaxSpeed() + " KM/H");
          break;
      }else if(q.equalsIgnoreCase("AUDI")){ //Prints AUDI Car Specifications
          System.out.println("Here is the latest AUDI Car specifications:");
          System.out.println("Colour: " + V2.getColour());
          System.out.println("Fuel Capacity: " + V2.getFuel() + " Liters");
          System.out.println("Wheel count: " + V2.getWheels());
          System.out.println("Maximum Speed: " + V2.getMaxSpeed() + " KM/H");
          break;
      }else{
          System.out.println("Sorry that is not a car manufacturer listed      (AUDI/BMW)");
      }
  }
}
}

Body:
You need to ask the user until he enters one of the correct words. So you have to do it like this:

 String q = input.next();
 while(!q.equalsIgnoreCase("BMW") && !q.equalsIgnoreCase("AUDI")){
    q = input.next();
 }

After that you can print out the information about the AUDI or BMW depending on what the user input was.


问:
SpEL Memory Leak using mixed mode
I'm having a problem using springs expression language when running in mixed mode.

In the standard interpreted mode everything seems to work ok.  If you have an expression say "a?.b?.c" then if on the object chain b is null you are returned null as I would expect.

The issue occurs when running in mixed mode and it gets compiled after 100 invocations.  In this case when you resolve an object where b is null, it seems that within the spring code a null pointer is thrown and the handled by resetting - but this appears to leave the original compiled class in memory.

If you run a test that repeatedly invokes this routine this you eventually run out of Perm Gen space.

It seems that the null safety checks such as "a?.b?.c" don't seem to be incorporated when used within compiled expressions.

Has anybody seen this previously, have ideas on potential solutions/workarounds?

Thanks!

答:
It sounds like a bug; I suggestion you open a JIRA issue against the Core:SpEL component.

It would be helpful if you attach your test case.

Title: SpEL Memory Leak using mixed mode


问:
Compare length of 2 variables and assign longest to another variable
I have 2 arrays of differing length assigned to $array1 and $array2,

Is there a more graceful way of checking each of there lengths and then assigning the biggest to a new variable?

Below is what i already have, but it seems a bit to 'dirty'.

```<code>if ($array1 > $array2) {
    $PlayerSum = $array1;
}
elseif ($array2 > $array1) {
    $PlayerSum = $array2;
}
else {
    $error = "<div class='alert alert-danger error'>Invalid Entry!</div>";
}
</code>```

答:
Yes use a simple count()

```<code>if (count($array1) > count($array2)) {
    $PlayerSum = $array1;
}
elseif (count($array2) > count($array1)) {
    $PlayerSum = $array2;
}
else {
    // the 2 arrays must be the same length
    $error = "<div class='alert alert-danger error'>Invalid Entry!</div>";
}
</code>```

Body:
I have 2 arrays of differing length assigned to $array1 and $array2,

Is there a more graceful way of checking each of there lengths and then assigning the biggest to a new variable?

Below is what i already have, but it seems a bit to 'dirty'.

if ($array1 > $array2) {
    $PlayerSum = $array1;
}
elseif ($array2 > $array1) {
    $PlayerSum = $array2;
}
else {
    $error = "
Invalid Entry!
";
}

Body:
Yes use a simple count()

if (count($array1) > count($array2)) {
    $PlayerSum = $array1;
}
elseif (count($array2) > count($array1)) {
    $PlayerSum = $array2;
}
else {
    // the 2 arrays must be the same length
    $error = "<div class='alert alert-danger error'>Invalid Entry!</div>";
}


答:
you need to exclude your if and else if statement out of the loop then reprompt
the user if it is not BMW or AUDI then outside the loop test the String</p>

```<code>int car=0;
    while(car==0)
    {
        if(q.equalsIgnoreCase("BMW")||q.equalsIgnoreCase("AUDI"))
            car++;
        else
        {
            System.out.println("Sorry that is not a car manufacturer listed           (AUDI/BMW)");
            System.out.println("Choose from Audi or BMW");
            q = input.next();
        }

    }
if (q.equalsIgnoreCase("BMW")){ // Prints BMW Car Specifications
      System.out.println("Here is the latest BMW Car specifications:");
      System.out.println("Colour: " + V1.getColour());
      System.out.println("Fuel Capacity: " + V1.getFuel() + " Liters");
      System.out.println("Wheel count: " + V1.getWheels());
      System.out.println("Maximum Speed: " + V1.getMaxSpeed() + " KM/H");

  }else if(q.equalsIgnoreCase("AUDI")){ //Prints AUDI Car Specifications
      System.out.println("Here is the latest AUDI Car specifications:");
      System.out.println("Colour: " + V2.getColour());
      System.out.println("Fuel Capacity: " + V2.getFuel() + " Liters");
      System.out.println("Wheel count: " + V2.getWheels());
      System.out.println("Maximum Speed: " + V2.getMaxSpeed() + " KM/H");
    }
</code>```

Title: How to fix my loop code in JAVA?

Body:
you need to exclude your if and else if statement out of the loop then reprompt
the user if it is not BMW or AUDI then outside the loop test the String

int car=0;
    while(car==0)
    {
        if(q.equalsIgnoreCase("BMW")||q.equalsIgnoreCase("AUDI"))
            car++;
        else
        {
            System.out.println("Sorry that is not a car manufacturer listed           (AUDI/BMW)");
            System.out.println("Choose from Audi or BMW");
            q = input.next();
        }

    }
if (q.equalsIgnoreCase("BMW")){ // Prints BMW Car Specifications
      System.out.println("Here is the latest BMW Car specifications:");
      System.out.println("Colour: " + V1.getColour());
      System.out.println("Fuel Capacity: " + V1.getFuel() + " Liters");
      System.out.println("Wheel count: " + V1.getWheels());
      System.out.println("Maximum Speed: " + V1.getMaxSpeed() + " KM/H");

  }else if(q.equalsIgnoreCase("AUDI")){ //Prints AUDI Car Specifications
      System.out.println("Here is the latest AUDI Car specifications:");
      System.out.println("Colour: " + V2.getColour());
      System.out.println("Fuel Capacity: " + V2.getFuel() + " Liters");
      System.out.println("Wheel count: " + V2.getWheels());
      System.out.println("Maximum Speed: " + V2.getMaxSpeed() + " KM/H");
    }


问:
Spring Boot JSP 404
I'm trying to add a jsp page in my Spring Boot service. My problem is that every time I try to go to that page I have this:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing
  this as a fallback.

Tue Apr 21 23:16:00 EEST 2015 There was an unexpected error (type=Not
  Found, status=404). No message available

I have added the prefix and sufix into my application.properties:

```<code>spring.view.prefix: /WEB-INF/jsp/
spring.view.suffix: .jsp
</code>```

This is my controller class:

```<code>@Controller
public class MarkerController {
    @RequestMapping(value="/map")
    public String trafficSpy() {
        return "index";
    }
}
</code>```

My Application class:

```<code>@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    private static Logger logger = Logger.getLogger(Application.class.getName());

    public static void main(String[] args) {
            logger.info("SPRING VERSION: " + SpringVersion.getVersion());
            SpringApplication.run(Application.class, args);
        }
}
</code>```

And the index.jsp:

```<code><!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">

<body>
    <h1>Hello, World!!!</h1>

    <p>JSTL URL: ${url}</p>
</body>

</html>
</code>```

And this is the src file structure:

```<code>├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── internetprogramming
│   │   │               └── myserver
│   │   │                   └── server
│   │   │                       ├── Application.java
│   │   │                       ├── config
│   │   │                       │   └── DatabaseConfig.java
│   │   │                       ├── controller
│   │   │                       │   └── MarkerController.java
│   │   │                       ├── dao
│   │   │                       │   ├── MarkerDaoImplementation.java
│   │   │                       │   └── MarkerDaoInterface.java
│   │   │                       ├── Marker.java
│   │   │                       └── service
│   │   │                           ├── MarkerServiceImplementation.java
│   │   │                           └── MarkerServiceInterface.java
│   │   ├── resources
│   │   │   └── application.properties
│   │   └── webapp
│   │       └── WEB-INF
│   │           └── jsp
│   │               └── index.jsp
</code>```

答:
my issue was  Spring vesrion : I found that since 1.4.3 version and above stops supporting the embedded JSPs . So I change version to 1.4.1 , it's worked for me.

an other thing take off  :

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</code>```

it will not work with it .

Title: Spring Boot JSP 404

Body:
I'm trying to add a jsp page in my Spring Boot service. My problem is that every time I try to go to that page I have this:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing
  this as a fallback.

Tue Apr 21 23:16:00 EEST 2015 There was an unexpected error (type=Not
  Found, status=404). No message available

I have added the prefix and sufix into my application.properties:

spring.view.prefix: /WEB-INF/jsp/
spring.view.suffix: .jsp

This is my controller class:

@Controller
public class MarkerController {
    @RequestMapping(value="/map")
    public String trafficSpy() {
        return "index";
    }
}

My Application class:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    private static Logger logger = Logger.getLogger(Application.class.getName());

    public static void main(String[] args) {
            logger.info("SPRING VERSION: " + SpringVersion.getVersion());
            SpringApplication.run(Application.class, args);
        }
}

And the index.jsp:

<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Hello, World!!!

JSTL URL: ${url}

And this is the src file structure:

├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── internetprogramming
│   │   │               └── myserver
│   │   │                   └── server
│   │   │                       ├── Application.java
│   │   │                       ├── config
│   │   │                       │   └── DatabaseConfig.java
│   │   │                       ├── controller
│   │   │                       │   └── MarkerController.java
│   │   │                       ├── dao
│   │   │                       │   ├── MarkerDaoImplementation.java
│   │   │                       │   └── MarkerDaoInterface.java
│   │   │                       ├── Marker.java
│   │   │                       └── service
│   │   │                           ├── MarkerServiceImplementation.java
│   │   │                           └── MarkerServiceInterface.java
│   │   ├── resources
│   │   │   └── application.properties
│   │   └── webapp
│   │       └── WEB-INF
│   │           └── jsp
│   │               └── index.jsp

Body:
my issue was  Spring vesrion : I found that since 1.4.3 version and above stops supporting the embedded JSPs . So I change version to 1.4.1 , it's worked for me.

an other thing take off  :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

it will not work with it .


问:
MVVM: Where to Place Methods used by Most ViewModels?
I have a few ViewModels which run a process from a simple string parameter. I want them to all use the same method to do it so as to not repeat code.

I was thinking about putting this method in ViewModelBase, however wouldn't that replicate the code anyway?

答: How about you just write a little helper class that contains the method that you want to call?</p>


问:
What is the alternative to cursors to retrieve large amounts of data from a database?
Searching through stackoverflow I found a large number of answers condemning the use of cursors in database programming. However I don't really understand what the alternative is.

I'm creating a program which reads a large number of rows (hundreds of thousands) from the database and keeps them in memory, for performance reasons. I can't really run a SELECT * FROM table and process all the results at once, can I?

The best way I have found is to use cursors and retrieve the rows in increments, for example 10 at a time.

Could someone enlighten me? I use PostgreSQL 9 on linux.

Thanks

答:
It should be rare to need a cursor. Maybe if your logic changes as each previous row is updated, then you may need a cursor.

Do you really need to open a cursor for your problem? Can you give the specifics of what you are trying to do? Large data sets are a good reason to avoid cursors, not a reason to use them.

You should try to do set-based processing. Just regular updates on the tables, with joins and where filters.

Can a simple update replace your cursor loop?

ContentLicense: CC BY-SA 2.5


问:
SAS LENGTH statement: what is a byte?
How would you explain to someone how much a "byte" is in the LENGTH statement? I always thought 1 byte equaled 1 character or 1 number, but that doesn't seem to be the case. Also, why is the syntax for it different than the syntax for the FORMAT statement? i.e.:

```<code>/*FORMAT Statement Syntax*/
FORMAT variable_name $8.;

/*LENGTH Statement*/
LENGTH variable_name $ 8
</code>```

答:
The syntax is different because they do different things. The LENGTH statement defines the type of the variable and how much room it takes to store the variable in the dataset. The FORMAT statement defines which FORMAT you want to attach to the variable so that SAS knows how to transform the variable when writing the value out to the log or output window.

The $ in the length statement means you are defining a character variable. The $ in a format statement is just part of the name of the format that you are attaching to the variable.  Formats that can be used with character variables start with a $ and numeric formats do not.  Formats need to have a period so that SAS can distinguish them from variable names.  But the lengths used in a LENGTH statement are integers and so periods are not needed (although SAS will ignore them if you add them after the integer value).

I see a lot of confusion in SAS code where the FORMAT statement is used as if it is intended to define variables.  This only works because SAS will guess at how to define a variable the first time it appears in the data step.  So it will use the details of the format you are attaching to guess at what type of variable you mean.  So if you first reference X in an assignment statement x=2+3 then SAS will guess that X should numeric and give it the default length of 8.  But if the first place it sees X is in a format statement like format x $10. then it will guess that you wanted to make X a character variable with length 10 to match the width of the format.

As to how characters are represented and stored it depends on what encoding you are using. If you are only using simple 7-bit ASCII codes then there is a 1-1 relationship between characters and how many bytes it takes to store them. But if you are using UTF-8 it can take up to 4 bytes to store a single character.

For numeric variables SAS uses the IEEE 64 bit format so the relationship between the LENGTH used to store the variable and the width of a format used to display it is much more complex. It is best to just define all numeric variables as length 8. SAS will allow you to define numeric variables with length less than 8 bytes, but that just means it throws away those extra bits of precision when writing the values to the SAS dataset. When storing integers you can do this without loss of precision as long as there are enough bits left to store the largest number you expect. For floating point values you will lose precision.

Title: SAS LENGTH statement: what is a byte?

Body:
How would you explain to someone how much a "byte" is in the LENGTH statement? I always thought 1 byte equaled 1 character or 1 number, but that doesn't seem to be the case. Also, why is the syntax for it different than the syntax for the FORMAT statement? i.e.:

/*FORMAT Statement Syntax*/
FORMAT variable_name $8.;

/*LENGTH Statement*/
LENGTH variable_name $ 8


问:
Developing a python Scraper that opens all links in multiple tabs using Chrome
I am trying to develop a scraper using python that will open links within a webpage in multiple tabs in Chrome.

The code I have managed to put together is

```<code>import urllib2
from datetime import timedelta, date
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
import time

from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()

i = driver.get("https://investmentinsightindia.wordpress.com/")

driver.find_element_by_partial_link_text(',').click()
driver.get("chrome://newtab/")
</code>```

I have figured out that most individual posts on that site have a ',' (in the date) so I have tried to click on the link that has a , in it's text.

I do realise to make it work on multiple sites, I would eventually need to use something more generic to a link like an href reference from Xpath, I don't know how to do that.

How can I configure it -
1. Opens the homepage (url)
2. Opens the first available link in a new tab
3. Leaves the tab open
4. Opens the second available link in a new tab.....and so on

答:
If your requirement to open specific post links which contains , in dates e.g. Posted on May 17, 2013 Then get all same kind of element in a list using following xpath :

```<code>//a/span[contains(text(),',')]
</code>```

OR

can use below xpath to get all post links

```<code>//h2/a
</code>```

and iterate through the for loop. Below is sample Java example to do the same Please implement as per python syntax

```<code> List <WebElement> allElement = driver.findElements(By.xpath("//a/span[contains(text(),',')]/parent::*")); // will get all anchor tag which having , and store in a list

 System.out.println(allElement.size());
 for(WebElement element:allElement)
 {
    System.out.println(element.getAttribute("href"));
    driver = new ChromeDriver();
    driver.get(element.getAttribute("href"));
 }
</code>```

Body:
I am trying to develop a scraper using python that will open links within a webpage in multiple tabs in Chrome.

The code I have managed to put together is

import urllib2
from datetime import timedelta, date
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
import time

from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()

i = driver.get("https://investmentinsightindia.wordpress.com/")

driver.find_element_by_partial_link_text(',').click()
driver.get("chrome://newtab/")

I have figured out that most individual posts on that site have a ',' (in the date) so I have tried to click on the link that has a , in it's text.

I do realise to make it work on multiple sites, I would eventually need to use something more generic to a link like an href reference from Xpath, I don't know how to do that.

How can I configure it -
1. Opens the homepage (url)
2. Opens the first available link in a new tab
3. Leaves the tab open
4. Opens the second available link in a new tab.....and so on

Body:
If your requirement to open specific post links which contains , in dates e.g. Posted on May 17, 2013 Then get all same kind of element in a list using following xpath :

//a/span[contains(text(),',')]

OR

can use below xpath to get all post links

//h2/a

and iterate through the for loop. Below is sample Java example to do the same Please implement as per python syntax

 List <WebElement> allElement = driver.findElements(By.xpath("//a/span[contains(text(),',')]/parent::*")); // will get all anchor tag which having , and store in a list

 System.out.println(allElement.size());
 for(WebElement element:allElement)
 {
    System.out.println(element.getAttribute("href"));
    driver = new ChromeDriver();
    driver.get(element.getAttribute("href"));
 }


问:
Apply rotate transform to tiled background image
Is there a simple way to render a rotated tiled image as a view background? Something to the effect of UIColor(patternImage:) but where the image is rotated at a certain angle?

答: There is no simple way to achieve this, at least not in vanilla Swift. I would use another UIView as a subview for our original view, set its background to a tiled image and add a CGAffineTransform to that particular view.


问:
Cancelling boost asio deadline timer safely
I'm trying to cancel a boost::asio::basic_waitable_timer<std::chrono::steady_clock> safely.

According to this answer, this code should do that work:

```<code>timer.get_io_service().post([&]{timer.cancel();})
</code>```

I'm afraid it doesn't work for me.

Am I doing something wrong?

This is my code:

```<code>#include <iostream>
#include "boost/asio.hpp"
#include <chrono>
#include <thread>
#include <random>

boost::asio::io_service io_service;
boost::asio::basic_waitable_timer<std::chrono::steady_clock> timer(io_service);
std::atomic<bool> started;

void handle_timeout(const boost::system::error_code& ec)
{
    if (!ec) {
        started = true;
        std::cerr << "tid: " << std::this_thread::get_id() << ", handle_timeout\n";
        timer.expires_from_now(std::chrono::milliseconds(10));
        timer.async_wait(&handle_timeout);
    } else if (ec == boost::asio::error::operation_aborted) {
        std::cerr << "tid: " << std::this_thread::get_id() << ", handle_timeout aborted\n";
    } else {
        std::cerr << "tid: " << std::this_thread::get_id() << ", handle_timeout another error\n";
    }
}

int main() {

    std::cout << "tid: " << std::this_thread::get_id() << ", Hello, World!" << std::endl;
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 100);

    for (auto i = 0; i < 1000; i++) {

        started = false;
        std::thread t([&](){

            timer.expires_from_now(std::chrono::milliseconds(0));
            timer.async_wait(&handle_timeout);

            io_service.run();
        });

        while (!started) {};
        auto sleep = dis(gen);
        std::cout << "tid: " << std::this_thread::get_id() << ", i: " << i << ", sleeps for " << sleep << " [ms]" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(sleep));
        timer.get_io_service().post([](){
            std::cerr << "tid: " << std::this_thread::get_id() << ", cancelling in post\n";
            timer.cancel();
        });
//      timer.cancel();
        std::cout << "tid: " << std::this_thread::get_id() << ", i: " << i << ", waiting for thread to join()" << std::endl;
        t.join();
        io_service.reset();
    }

    return 0;
}
</code>```

This is the output:

...

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  tid: 140737353967488, i: 2, waiting for thread to join()

  tid: 140737335076608, cancelling in post

  tid: 140737335076608, handle_timeout aborted

  tid: 140737353967488, i: 3, sleeps for 21 [ms]

  tid: 140737335076608, handle_timeout

  tid: 140737353967488, i: 3, waiting for thread to join()

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, cancelling in post

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  ...

  continue forever...

As you can see, the timer.cancel() is being called from the appropriate thread:

tid: 140737335076608, cancelling in post

BUT there's no

tid: 140737335076608, handle_timeout aborted

Afterwards.

Main waits forever.

答:
The cancellation is safe.

It's just not robust. You didn't account for the case when the timer wasn't pending. You cancel it once, then, but it will just start a new async wait once the completion handler is invoked.

What follows is my detailed steps on how I traced the issue.

SUMMARY TL;DR

Cancelling a time only cancels asynchronous operations in flight.

If you want to shutdown an asynchronous call chain, you'll have to use additional logic for that. An example is given below.

Handler Tracking

Enabling with

```<code>#define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1
</code>```

This produces output that can be visualized with boost/libs/asio/tools/handlerviz.pl:

A successful trace

As you can see, the async_wait is in-flight when the cancellation happens.

A "bad" trace

(truncated because it would run infinitely)

Note how the completion handler sees cc=system:0, not cc=system:125 (for operation_aborted). This is a symptom of the fact that the posted cancel did not actually "take". The only logical explanation (not visible in the diagram) is that the timer had already expired before the cancel gets invoked.

Let's compare the raw traces¹

¹ removing the noisy difference

Detecting It

So, we have a lead. Can we detect it?

```<code>    timer.get_io_service().post([](){
        std::cerr << "tid: " << std::this_thread::get_id() << ", cancelling in post\n";
        if (timer.expires_from_now() >= std::chrono::steady_clock::duration(0)) {
            timer.cancel();
        } else {
            std::cout << "PANIC\n";
            timer.cancel();
        }
    });
</code>```

Prints:

```<code>tid: 140113177143232, i: 0, waiting for thread to join()
tid: 140113177143232, i: 1, waiting for thread to join()
tid: 140113177143232, i: 2, waiting for thread to join()
tid: 140113177143232, i: 3, waiting for thread to join()
tid: 140113177143232, i: 4, waiting for thread to join()
tid: 140113177143232, i: 5, waiting for thread to join()
tid: 140113177143232, i: 6, waiting for thread to join()
tid: 140113177143232, i: 7, waiting for thread to join()
tid: 140113177143232, i: 8, waiting for thread to join()
tid: 140113177143232, i: 9, waiting for thread to join()
tid: 140113177143232, i: 10, waiting for thread to join()
tid: 140113177143232, i: 11, waiting for thread to join()
tid: 140113177143232, i: 12, waiting for thread to join()
tid: 140113177143232, i: 13, waiting for thread to join()
tid: 140113177143232, i: 14, waiting for thread to join()
tid: 140113177143232, i: 15, waiting for thread to join()
tid: 140113177143232, i: 16, waiting for thread to join()
tid: 140113177143232, i: 17, waiting for thread to join()
tid: 140113177143232, i: 18, waiting for thread to join()
tid: 140113177143232, i: 19, waiting for thread to join()
tid: 140113177143232, i: 20, waiting for thread to join()
tid: 140113177143232, i: 21, waiting for thread to join()
tid: 140113177143232, i: 22, waiting for thread to join()
tid: 140113177143232, i: 23, waiting for thread to join()
tid: 140113177143232, i: 24, waiting for thread to join()
tid: 140113177143232, i: 25, waiting for thread to join()
tid: 140113177143232, i: 26, waiting for thread to join()
PANIC
</code>```

Could we communicate the "super-cancellation" in another, clearer way? We have ... just the timer object to work with, of course:

Signaling Shutdown

The timer object doesn't have a lot of properties to work with. There's no close() or similar, like on a socket, that can be used to put the timer in some kind of invalid state.

However, there's the expiry timepoint, and we can use a special domain
value to signal "invalid" for our application:

```<code>timer.get_io_service().post([](){
    std::cerr << "tid: " << std::this_thread::get_id() << ", cancelling in post\n";
    // also cancels:
    timer.expires_at(Timer::clock_type::time_point::min());
});
</code>```

This "special value" is easy to handle in the completion handler:

```<code>void handle_timeout(const boost::system::error_code& ec)
{
    if (!ec) {
        started = true;
        if (timer.expires_at() != Timer::time_point::min()) {
            timer.expires_from_now(std::chrono::milliseconds(10));
            timer.async_wait(&handle_timeout);
        } else {
            std::cerr << "handle_timeout: detected shutdown\n";
        }
    }
    else if (ec != boost::asio::error::operation_aborted) {
        std::cerr << "tid: " << std::this_thread::get_id() << ", handle_timeout error " << ec.message() << "\n";
    }
}
</code>```

Body:
I'm trying to cancel a boost::asio::basic_waitable_timer<std::chrono::steady_clock> safely.

According to this answer, this code should do that work:

timer.get_io_service().post([&]{timer.cancel();})

I'm afraid it doesn't work for me.

Am I doing something wrong?

This is my code:

#include <iostream>
#include "boost/asio.hpp"
#include <chrono>
#include <thread>
#include <random>

boost::asio::io_service io_service;
boost::asio::basic_waitable_timer<std::chrono::steady_clock> timer(io_service);
std::atomic<bool> started;

void handle_timeout(const boost::system::error_code& ec)
{
    if (!ec) {
        started = true;
        std::cerr << "tid: " << std::this_thread::get_id() << ", handle_timeout\n";
        timer.expires_from_now(std::chrono::milliseconds(10));
        timer.async_wait(&handle_timeout);
    } else if (ec == boost::asio::error::operation_aborted) {
        std::cerr << "tid: " << std::this_thread::get_id() << ", handle_timeout aborted\n";
    } else {
        std::cerr << "tid: " << std::this_thread::get_id() << ", handle_timeout another error\n";
    }
}

int main() {

    std::cout << "tid: " << std::this_thread::get_id() << ", Hello, World!" << std::endl;
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 100);

    for (auto i = 0; i < 1000; i++) {

        started = false;
        std::thread t([&](){

            timer.expires_from_now(std::chrono::milliseconds(0));
            timer.async_wait(&handle_timeout);

            io_service.run();
        });

        while (!started) {};
        auto sleep = dis(gen);
        std::cout << "tid: " << std::this_thread::get_id() << ", i: " << i << ", sleeps for " << sleep << " [ms]" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(sleep));
        timer.get_io_service().post([](){
            std::cerr << "tid: " << std::this_thread::get_id() << ", cancelling in post\n";
            timer.cancel();
        });
//      timer.cancel();
        std::cout << "tid: " << std::this_thread::get_id() << ", i: " << i << ", waiting for thread to join()" << std::endl;
        t.join();
        io_service.reset();
    }

    return 0;
}

This is the output:

...

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  tid: 140737353967488, i: 2, waiting for thread to join()

  tid: 140737335076608, cancelling in post

  tid: 140737335076608, handle_timeout aborted

  tid: 140737353967488, i: 3, sleeps for 21 [ms]

  tid: 140737335076608, handle_timeout

  tid: 140737353967488, i: 3, waiting for thread to join()

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, cancelling in post

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  tid: 140737335076608, handle_timeout

  ...

  continue forever...

As you can see, the timer.cancel() is being called from the appropriate thread:

tid: 140737335076608, cancelling in post

BUT there's no

tid: 140737335076608, handle_timeout aborted

Afterwards.

Main waits forever.

Body:
The cancellation is safe.

It's just not robust. You didn't account for the case when the timer wasn't pending. You cancel it once, then, but it will just start a new async wait once the completion handler is invoked.

What follows is my detailed steps on how I traced the issue.

SUMMARY TL;DR

Cancelling a time only cancels asynchronous operations in flight.

If you want to shutdown an asynchronous call chain, you'll have to use additional logic for that. An example is given below.

Handler Tracking

Enabling with

#define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1

This produces output that can be visualized with boost/libs/asio/tools/handlerviz.pl:

A successful trace

As you can see, the async_wait is in-flight when the cancellation happens.

A "bad" trace

(truncated because it would run infinitely)

Note how the completion handler sees cc=system:0, not cc=system:125 (for operation_aborted). This is a symptom of the fact that the posted cancel did not actually "take". The only logical explanation (not visible in the diagram) is that the timer had already expired before the cancel gets invoked.

Let's compare the raw traces¹

¹ removing the noisy difference

Detecting It

So, we have a lead. Can we detect it?

    timer.get_io_service().post([](){
        std::cerr << "tid: " << std::this_thread::get_id() << ", cancelling in post\n";
        if (timer.expires_from_now() >= std::chrono::steady_clock::duration(0)) {
            timer.cancel();
        } else {
            std::cout << "PANIC\n";
            timer.cancel();
        }
    });

Prints:

tid: 140113177143232, i: 0, waiting for thread to join()
tid: 140113177143232, i: 1, waiting for thread to join()
tid: 140113177143232, i: 2, waiting for thread to join()
tid: 140113177143232, i: 3, waiting for thread to join()
tid: 140113177143232, i: 4, waiting for thread to join()
tid: 140113177143232, i: 5, waiting for thread to join()
tid: 140113177143232, i: 6, waiting for thread to join()
tid: 140113177143232, i: 7, waiting for thread to join()
tid: 140113177143232, i: 8, waiting for thread to join()
tid: 140113177143232, i: 9, waiting for thread to join()
tid: 140113177143232, i: 10, waiting for thread to join()
tid: 140113177143232, i: 11, waiting for thread to join()
tid: 140113177143232, i: 12, waiting for thread to join()
tid: 140113177143232, i: 13, waiting for thread to join()
tid: 140113177143232, i: 14, waiting for thread to join()
tid: 140113177143232, i: 15, waiting for thread to join()
tid: 140113177143232, i: 16, waiting for thread to join()
tid: 140113177143232, i: 17, waiting for thread to join()
tid: 140113177143232, i: 18, waiting for thread to join()
tid: 140113177143232, i: 19, waiting for thread to join()
tid: 140113177143232, i: 20, waiting for thread to join()
tid: 140113177143232, i: 21, waiting for thread to join()
tid: 140113177143232, i: 22, waiting for thread to join()
tid: 140113177143232, i: 23, waiting for thread to join()
tid: 140113177143232, i: 24, waiting for thread to join()
tid: 140113177143232, i: 25, waiting for thread to join()
tid: 140113177143232, i: 26, waiting for thread to join()
PANIC

Could we communicate the "super-cancellation" in another, clearer way? We have ... just the timer object to work with, of course:

Signaling Shutdown

The timer object doesn't have a lot of properties to work with. There's no close() or similar, like on a socket, that can be used to put the timer in some kind of invalid state.

However, there's the expiry timepoint, and we can use a special domain
value to signal "invalid" for our application:

timer.get_io_service().post([](){
    std::cerr << "tid: " << std::this_thread::get_id() << ", cancelling in post\n";
    // also cancels:
    timer.expires_at(Timer::clock_type::time_point::min());
});

This "special value" is easy to handle in the completion handler:

void handle_timeout(const boost::system::error_code& ec)
{
    if (!ec) {
        started = true;
        if (timer.expires_at() != Timer::time_point::min()) {
            timer.expires_from_now(std::chrono::milliseconds(10));
            timer.async_wait(&handle_timeout);
        } else {
            std::cerr << "handle_timeout: detected shutdown\n";
        }
    }
    else if (ec != boost::asio::error::operation_aborted) {
        std::cerr << "tid: " << std::this_thread::get_id() << ", handle_timeout error " << ec.message() << "\n";
    }
}


问:
Click in Angularjs using Casperjs
I would like to click in angularjs using casperjs. However, i cant achieve this. The webpage populates a dialogbox everytime i run so this is why i need to click.

This is what i try to click

```<code><button class="ng-scope" trans="" ng-click="closeDialog(activeDialog, 'okButton');$event.stopPropagation();" ng-if="!activeDialog.yesno">Tamam</button>
</code>```

This is what i use in casperjs

```<code>casper.then(function () {
this.evaluate(function() {

    $($(document).find('button[ng-if="!activeDialog.yesno"]')).click();
});

this.wait(3000);
</code>```

Thanks in advance

答:
You can solve it this way also:

```<code>this.click('button[ng-if="!activeDialog.yesno"]');
</code>```

I had similar problem. Every time I login to the website a popup window opens and I have to put certain value text field and click button. That's how popup window class and other attributes looks like:

```<code><button class="md-raised md-primary md-button md-button md-ink-ripple" aria-label="Okey", type="button">
</code>```

That's how I solved it:

```<code>this.waitUntilVisible('button[aria-label="Okay"]', function () {
    this.click('button[aria-label="Okay"]');
    this.echo("########### Okay button clicked")
})
</code>```

Title: Click in Angularjs using Casperjs

Body:
I would like to click in angularjs using casperjs. However, i cant achieve this. The webpage populates a dialogbox everytime i run so this is why i need to click.

This is what i try to click

<button class="ng-scope" trans="" ng-click="closeDialog(activeDialog, 'okButton');$event.stopPropagation();" ng-if="!activeDialog.yesno">Tamam</button>

This is what i use in casperjs

casper.then(function () {
this.evaluate(function() {

    $($(document).find('button[ng-if="!activeDialog.yesno"]')).click();
});

this.wait(3000);

Thanks in advance

Body:
You can solve it this way also:

this.click('button[ng-if="!activeDialog.yesno"]');

I had similar problem. Every time I login to the website a popup window opens and I have to put certain value text field and click button. That's how popup window class and other attributes looks like:

<button class="md-raised md-primary md-button md-button md-ink-ripple" aria-label="Okey", type="button">

That's how I solved it:

this.waitUntilVisible('button[aria-label="Okay"]', function () {
    this.click('button[aria-label="Okay"]');
    this.echo("########### Okay button clicked")
})


问:
latch(used for awaiting async response) freezes the WebView (and the UI)
I have an app that displays a webview on the whole layout. Sometimes I need to call an async method, that async operation is done by a 3-party sdk, and then I wait for it for a while until I get the response to a designated listener. I have solved it with a latch - once the response is received in the listener, I countDown the latch and then the initiating method can continue with this response.
Unfortunately, when I do this, the WebView is stuck. I imagined the native UI would be stuck , but I didn't expect the webview to get frozen as well.
How can that be overcome?

To make it clearer, here is an example. I need the ajaxFunc to wait until MyAsyncListener gets a certain response, and then return this exact response.

part of JS I inject to the webview :

```<code>var response = jsHandler.ajaxFunc(request.data);
</code>```

I have a variable global variable called response.

```<code>public class JavaScriptInterface
{
     @JavascriptInterface
     public String ajaxFunc(String data)
     {
         return MyUtils.handleData( data );
     }
}
</code>```

the handleData method :

```<code> public String handleData( String data )
 {
     SomeClass.startAsyncRequest(); // starts the async request, response is to come at the listener's callbacks .

     latch = new CountDownLatch(1);
     try {
         latch.await(30, TimeUnit.SECONDS);
     }
     catch (InterruptedException e) {
         e.printStackTrace();
     }

     return response;
   }
</code>```

now, once the handleData function calls a function, that does something asynchronously, the async function then returns some answer inside some Listener :

```<code>myAsyncListener = new MyAsyncListener() {
    @Override
        public Response handleEvent(CustomEvent event) {
            //Now I need to return this 'event' back to the handData/ajaxFunc function <--

            response = event.getName();
            latch.countDown();

        }
    });
</code>```

答:
I need the ajaxFunc to wait until MyAsyncListener gets a certain response, and then return this exact response.

Since you are dispatching an async request, you shouldn't expect the response to arrive in the same method call you made to start the async code. If you do this, the caller thread will block until the async response arrives, that is, it won't be async at all.

You can redesign your code to something like this:

public class JavaScriptInterface {
    @JavascriptInterface
    public void ajaxFunc(String data) {
        // draw a waiting animation or something
        MyUtils.handleData(data);
    }
}
```

<pre class="lang-java prettyprint-override"><code>public void handleData(String data) {
    SomeClass.startAsyncRequest();
}
</code>```

myAsyncListener = new MyAsyncListener() {
    @Override
    public void handleEvent(CustomEvent event) {
        // Do what you need to do
        // (update UI, call javascript etc.).
        //
        // Mind the thread that will execute this callback
        // to prevent multithreading issues.
    }
}
```

Body:
I have an app that displays a webview on the whole layout. Sometimes I need to call an async method, that async operation is done by a 3-party sdk, and then I wait for it for a while until I get the response to a designated listener. I have solved it with a latch - once the response is received in the listener, I countDown the latch and then the initiating method can continue with this response.
Unfortunately, when I do this, the WebView is stuck. I imagined the native UI would be stuck , but I didn't expect the webview to get frozen as well.
How can that be overcome?

To make it clearer, here is an example. I need the ajaxFunc to wait until MyAsyncListener gets a certain response, and then return this exact response.

part of JS I inject to the webview :

var response = jsHandler.ajaxFunc(request.data);

I have a variable global variable called response.

public class JavaScriptInterface
{
     @JavascriptInterface
     public String ajaxFunc(String data)
     {
         return MyUtils.handleData( data );
     }
}

the handleData method :

 public String handleData( String data )
 {
     SomeClass.startAsyncRequest(); // starts the async request, response is to come at the listener's callbacks .

     latch = new CountDownLatch(1);
     try {
         latch.await(30, TimeUnit.SECONDS);
     }
     catch (InterruptedException e) {
         e.printStackTrace();
     }

     return response;
   }

now, once the handleData function calls a function, that does something asynchronously, the async function then returns some answer inside some Listener :

myAsyncListener = new MyAsyncListener() {
    @Override
        public Response handleEvent(CustomEvent event) {
            //Now I need to return this 'event' back to the handData/ajaxFunc function <--

            response = event.getName();
            latch.countDown();

        }
    });

Body:
I need the ajaxFunc to wait until MyAsyncListener gets a certain response, and then return this exact response.

Since you are dispatching an async request, you shouldn't expect the response to arrive in the same method call you made to start the async code. If you do this, the caller thread will block until the async response arrives, that is, it won't be async at all.

You can redesign your code to something like this:

public class JavaScriptInterface {
    @JavascriptInterface
    public void ajaxFunc(String data) {
        // draw a waiting animation or something
        MyUtils.handleData(data);
    }
}

public void handleData(String data) {
    SomeClass.startAsyncRequest();
}

myAsyncListener = new MyAsyncListener() {
    @Override
    public void handleEvent(CustomEvent event) {
        // Do what you need to do
        // (update UI, call javascript etc.).
        //
        // Mind the thread that will execute this callback
        // to prevent multithreading issues.
    }
}


问:
Pulling twitter followers data using selenium chrome webdriver in python? Not able to load all the followers
I am trying to pull twitter followers data using Selenium chrome webdriver and BeautifulSoup for a account that has 80K followers.
I am facing two issues in my script :

1) While scrolling till the bottom of the page to get the entire page source after all the followers are loaded, my script does not scroll all the way to the bottom. It stops scrolling in between after loading a random number of followers and then start traversing each followers profile to get their data. I want it to load all the followers on the page and then start traversing the profiles.

2) My second issue is every time I run the script it would try to scroll to the bottom one by one till all the followers are loaded and then start pulling data by parsing one follower data at a time. This would take 4 to 5 days to fetch all the followers data in my case(80K followers). Is there any better way to do this.

Here is my script :

from bs4 import BeautifulSoup
import sys
import os,re
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from os import listdir
from os.path import isfile, join

print "Running for chrome."

chromedriver=sys.argv[1]
download_path=sys.argv[2]
os.system('killall -9 "Google Chrome"')
try:
 os.environ["webdriver.chrome.driver"]=chromedriver
 chromeOptions = webdriver.ChromeOptions()
 prefs = {"download.default_directory" : download_path}
 chromeOptions.add_experimental_option("prefs",prefs)
 driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chromeOptions)
 driver.implicitly_wait(20)
 driver.maximize_window()
except Exception as err:
 print "Error:Failed to open chrome."
 print "Error: ",err
 driver.stop_client()
 driver.close()

#opening the web page
try:
 driver.get('https://twitter.com/login')
except Exception as err:
 print "Error:Failed to open url."
 print "Error: ",err
 driver.stop_client()
 driver.close()

username = driver.find_element_by_xpath("//input[@name='session[username_or_email]' and @class='js-username-field email-input js-initial-focus']")
password = driver.find_element_by_xpath("//input[@name='session[password]' and @class='js-password-field']")

username.send_keys("###########")
password.send_keys("###########")
driver.find_element_by_xpath("//button[@type='submit']").click()
#os.system('killall -9 "Google Chrome"')
driver.get('https://twitter.com/sadserver/followers')

followers_link=driver.page_source  #follwer page 18at a time
soup=BeautifulSoup(followers_link,'html.parser')

output=open('twitter_follower_sadoperator.csv','a')
output.write('Name,Twitter_Handle,Location,Bio,Join_Date,Link'+'\n')
div = soup.find('div',{'class':'GridTimeline-items has-items'})
bref = div.findAll('a',{'class':'ProfileCard-bg js-nav'})
name_list=[]
lastHeight = driver.execute_script("return document.body.scrollHeight")

for _ in xrange(0, followers_count/followers_per_page + 1):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(5)
        newHeight = driver.execute_script("return document.body.scrollHeight")
        if newHeight == lastHeight:
                followers_link=driver.page_source  #follwer page 18at a time
                soup=BeautifulSoup(followers_link,'html.parser')
                div = soup.find('div',{'class':'GridTimeline-items has-items'})
                bref = div.findAll('a',{'class':'ProfileCard-bg js-nav'})
                for name in bref:
                        name_list.append(name['href'])
                break
        lastHeight = newHeight
        followers_link=''

print len(name_list)

for x in range(0,len(name_list)):
        #print name['href']
        #print name.text
        driver.stop_client()
        driver.get('https://twitter.com'+name_list[x])
        page_source=driver.page_source
        each_soup=BeautifulSoup(page_source,'html.parser')
        profile=each_soup.find('div',{'class':'ProfileHeaderCard'})

        try:
                name = profile.find('h1',{'class':'ProfileHeaderCard-name'}).find('a').text
                if name:
                        output.write('"'+name.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in name:',e

        try:
                handle=profile.find('h2',{'class':'ProfileHeaderCard-screenname u-inlineBlock u-dir'}).text
                if handle:
                        output.write('"'+handle.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in handle:',e

        try:
                location = profile.find('div',{'class':'ProfileHeaderCard-location'}).text
                if location:
                        output.write('"'+location.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in location:',e

        try:
                bio=profile.find('p',{'class':'ProfileHeaderCard-bio u-dir'}).text
                if bio:
                        output.write('"'+bio.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in bio:',e

        try:
                joinDate = profile.find('div',{'class':'ProfileHeaderCard-joinDate'}).text
                if joinDate:
                        output.write('"'+joinDate.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in joindate:',e

        try:
                url =  [check.find('a') for check in profile.find('div',{'class':'ProfileHeaderCard-url'}).findAll('span')][1]
                if url:
                        output.write('"'+url['href'].strip().encode('utf-8')+'"'+'\n')
                else:
                        output.write(' '+'\n')
        except Exception as e:
                output.write(' '+'\n')
                print 'Error in url:',e

output.close()

os.system("kill -9 `ps -deaf | grep chrome | awk '{print $2}'`")```

答:
There is a better way.
Use the Twitter API, here's a quick Github script that I found Github Script
Sorry you probably feel like you've waisted a lot of time by using Selenium (there are pros to not using an API)
Great post on automation and getting how stuff works: Twitter API

There's a way to scroll many times but you'd have to do some math or set a condition to stop this.

```<code>driver.execute_script("window.scrollTo(0, 10000);")
</code>```

Let's say you have 10k followers and the intial displays 100followers, and after that you'll load 10followers each scroll. You would scroll another 990 times.

Here's the exact usage for your case made by of course alecxe :D.
Qudora* answer By - alecxe -

```<code>html = driver.page_source
</code>```

This .page_source can be used once you reveal all the followers(scroll) and then parse it with something like BeautifulSoup

Body:
There is a better way.
Use the Twitter API, here's a quick Github script that I found Github Script
Sorry you probably feel like you've waisted a lot of time by using Selenium (there are pros to not using an API)
Great post on automation and getting how stuff works: Twitter API

There's a way to scroll many times but you'd have to do some math or set a condition to stop this.

driver.execute_script("window.scrollTo(0, 10000);")

Let's say you have 10k followers and the intial displays 100followers, and after that you'll load 10followers each scroll. You would scroll another 990 times.

Here's the exact usage for your case made by of course alecxe :D.
Qudora* answer By - alecxe -

html = driver.page_source

This .page_source can be used once you reveal all the followers(scroll) and then parse it with something like BeautifulSoup


问:
Webapp2 ImportError: cannot import name _thread
I am trying to start webapp2 development server from terminal but I get this error

```<code>> File "/Users/mertbarutcuoglu/Desktop/hellowebapp2/main.py", line 12,
> in main
>     from paste import httpserver   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/paste/httpserver.py",
> line 29, in <module>
>     from six.moves import _thread ImportError: cannot import name _thread
</code>```

And this is the python script:

```<code>import webapp2

class HelloWebapp2(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello, webapp2!')

app = webapp2.WSGIApplication([
    ('/', HelloWebapp2),
], debug=True)

def main():
    from paste import httpserver
    httpserver.serve(app, host='127.0.0.1', port='8080')

if __name__ == '__main__':
    main()
</code>```

答:
There seems to be an issue running this on Mac OS systems. See

https://github.com/pypa/pip/issues/3165

to fix, i had to uninstall paste i.e sudo pip uninstall paste then ran,
sudo pip install paste --ignore-installed six

Body:
I am trying to start webapp2 development server from terminal but I get this error

> File "/Users/mertbarutcuoglu/Desktop/hellowebapp2/main.py", line 12,
> in main
>     from paste import httpserver   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/paste/httpserver.py",
> line 29, in <module>
>     from six.moves import _thread ImportError: cannot import name _thread

And this is the python script:

import webapp2

class HelloWebapp2(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello, webapp2!')

app = webapp2.WSGIApplication([
    ('/', HelloWebapp2),
], debug=True)

def main():
    from paste import httpserver
    httpserver.serve(app, host='127.0.0.1', port='8080')

if __name__ == '__main__':
    main()


问:
How to change text localization “I'm not a robot” in recaptcha?
On different PC I see different localizations for I'm not a robot lable although I locates within one city. Aim - always to show same test distincts from  I'm not a robot

I have wrote following code to change label I'm not a robot in recaptcha.

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#recaptcha-anchor-label").text("Something different.");
    });
</script>
</code>```

maybe problem related with Iframe?

Can you help to fix my problem?

答:
You cannot change that specific text because it belongs to a third party iframe, though there is a workaround that fulfils exactly what you're asking for.

You can append a new div on the parent div you can control, aligning and overlapping it on the label text, considering the Google Captcha has always a fixed size. Therefore, according to documentation, considering you may have the main Captcha div on your code with class="g-recaptcha", you simply do:

```<code>$('.g-recaptcha').append('<div id="new_label"></div>');
$('#new_label').text("My custom text");
$('#new_label').css({"position":"absolute", "width":"160px", "top":"27px", "left":"53px", "background-color":"#f9f9f9"});
</code>```

it works :)

Body:
On different PC I see different localizations for I'm not a robot lable although I locates within one city. Aim - always to show same test distincts from  I'm not a robot

I have wrote following code to change label I'm not a robot in recaptcha.

maybe problem related with Iframe?

Can you help to fix my problem?

Body:
You cannot change that specific text because it belongs to a third party iframe, though there is a workaround that fulfils exactly what you're asking for.

You can append a new div on the parent div you can control, aligning and overlapping it on the label text, considering the Google Captcha has always a fixed size. Therefore, according to documentation, considering you may have the main Captcha div on your code with class="g-recaptcha", you simply do:

$('.g-recaptcha').append('<div id="new_label"></div>');
$('#new_label').text("My custom text");
$('#new_label').css({"position":"absolute", "width":"160px", "top":"27px", "left":"53px", "background-color":"#f9f9f9"});

it works :)


问:
TokenMismatchException in VerifyCsrfToken.php line 53 on Live server Laravel 5.1
I am using Laravel 5.1 Its working perfectly on localhost. But when I try to login it returns the error,

```<code>TokenMismatchException in VerifyCsrfToken.php line 53:
</code>```

When I remove CSRF token by commenting 'App\Http\Middleware\VerifyCsrfToken', In app/Http/Kernal.php. But after this it redirect to login page itself without session.

I also checked config/session.php,

```<code>// session.php

<?php

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'lottery' => [2, 100],
    'cookie' => 'laravel_session',
    'path' => '/',
    'domain' => null,
    'secure' => false,
];
</code>```

The storage and autoload folders are also writable.

Any Idea ?

答:
if you are using ajax, look at the manual about the csrf_field token setup:

https://laravel.com/docs/5.4/csrf#csrf-x-csrf-token

Body:
I am using Laravel 5.1 Its working perfectly on localhost. But when I try to login it returns the error,

TokenMismatchException in VerifyCsrfToken.php line 53:

When I remove CSRF token by commenting 'App\Http\Middleware\VerifyCsrfToken', In app/Http/Kernal.php. But after this it redirect to login page itself without session.

I also checked config/session.php,

// session.php

<?php

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'lottery' => [2, 100],
    'cookie' => 'laravel_session',
    'path' => '/',
    'domain' => null,
    'secure' => false,
];

The storage and autoload folders are also writable.

Any Idea ?


问:
What's a folder with a green and red arrow in IDEA?
I'm using IntelliJ IDEA Community Edition. When searching files for symbols, I came across the following results:

The bottom results have a symbol (on the right) of a folder with a green and a red arrow. What does this symbol mean?

答:
I think this means it is a junit test directory, but I can't find a reference for this info apart from this very old answer.

Edit: Version 2016.2 of the icons reference shows the arrows as a test resource


问:
Wordpress wp_list_pages: list parent page siblings
I'm trying to get this working for quite a while now. I get close but can't find a working solution.

My page structure is like this:

```<code>1 FIRST LEVEL
  2 SECOND LEVEL
    3 THIRD LEVEL
      4 CAR
         5 SUV
         5 MINIVAN
         5 FULLSIZE
      4 MOTORCYCLE
      4 BICYCLE
  2 SECOND LEVEL
  2 SECOND LEVEL
1 FIRST LEVEL
</code>```

I need a wp_list_pages statement that does the following: on 4th and 5th level pages (and ONLY on those) the navigation lists all 4th level pages.

(When i'm on page "CAR" the navigation should be CAR,MOTORCYCLE,BICYCLE. And also when i'm on page MINIVAN the navigation should be CAR,MOTORCYCLE,BICYCLE.)

Thank you very much for any help!

答:
Here's the code i finally used, thanks to TheDeadMedic's answer. (I canceled one page level so it's for 3rd and 4th level)</p>

```<code>$ancestors = get_post_ancestors($post);
if (count($ancestors) == 2) {
   $parent = $ancestors[0];
}
elseif (count($ancestors) == 3) {
   $parent = $ancestors[1];
}

if ($parent) {
   $tabs = wp_list_pages('depth=1&child_of=' . $parent);
}
</code>```

Body:
I'm trying to get this working for quite a while now. I get close but can't find a working solution.

My page structure is like this:

1 FIRST LEVEL
  2 SECOND LEVEL
    3 THIRD LEVEL
      4 CAR
         5 SUV
         5 MINIVAN
         5 FULLSIZE
      4 MOTORCYCLE
      4 BICYCLE
  2 SECOND LEVEL
  2 SECOND LEVEL
1 FIRST LEVEL

I need a wp_list_pages statement that does the following: on 4th and 5th level pages (and ONLY on those) the navigation lists all 4th level pages.

(When i'm on page "CAR" the navigation should be CAR,MOTORCYCLE,BICYCLE. And also when i'm on page MINIVAN the navigation should be CAR,MOTORCYCLE,BICYCLE.)

Thank you very much for any help!

Body:
Here's the code i finally used, thanks to TheDeadMedic's answer. (I canceled one page level so it's for 3rd and 4th level)

$ancestors = get_post_ancestors($post);
if (count($ancestors) == 2) {
   $parent = $ancestors[0];
}
elseif (count($ancestors) == 3) {
   $parent = $ancestors[1];
}

if ($parent) {
   $tabs = wp_list_pages('depth=1&child_of=' . $parent);
}


问:
dbext freeze when running SQL
I am using neovim with dbext;

In my init.vim i have this line

```<code>let g:dbext_default_profile_local_PSQL = 'type=PGSQL'
</code>```

I have test file: test.sql.

In file is:

```<code>select * from products;
</code>```

when i run \sel

nvim shows:
    dbext: Executing SQL at 22:56Password:

and it freeze and i can only kill it.
What can i do about it ?

答:
It looks like psql is prompting for a password.

Try adding let dbext_default_PGSQL_cmd_options = '-w' in .vimrc.

Title: dbext freeze when running SQL

Body:
I am using neovim with dbext;

In my init.vim i have this line

let g:dbext_default_profile_local_PSQL = 'type=PGSQL'

I have test file: test.sql.

In file is:

select * from products;

when i run \sel

nvim shows:
    dbext: Executing SQL at 22:56Password:

and it freeze and i can only kill it.
What can i do about it ?


问:
Unity3D update score error
I am following a tutorial by Charger Games on youtube it's about street racer android game and I am seeing this error on the Unity3D's console it says
 NullReferenceException: Object reference not set to an instance of an object UIManager.scoreUpdate ()

This is the code that has line that caused the error

```<code>public Text scoreText;
int score;

void Start () {
    score = 0;
    InvokeRepeating("scoreUpdate", 1.0f, 0.5f);
}
void Update () {
    scoreText.text = "Score: " + score; //this is the line. If I erase this the error will disappear
    }
void scoreUpdate () {
    if (gameOver == false) {
        score += 1;
        }
    }
</code>```

If I remove it, the error will disappear. It's not causing malfunctions or anything, I am just curious cos I am willing to learn. Please help me guys

答:
Make sure that your gameObject isn't empty, the gameObject won't be selected by magic! So try this

```<code>public Text scoreText;
private score;

void Start() {
  score = 5; //example
}

void Update() {
    scoreText.text = "Score: " + score;
}
</code>```

After that, you will need to assign your public gameObject and text to your script, so select the instance you gave your script and check in the inspector, you will see [none(Text)], click on it and select your UItext

Have fun!

Title: Unity3D update score error

Body:
I am following a tutorial by Charger Games on youtube it's about street racer android game and I am seeing this error on the Unity3D's console it says
 NullReferenceException: Object reference not set to an instance of an object UIManager.scoreUpdate ()

This is the code that has line that caused the error

public Text scoreText;
int score;

void Start () {
    score = 0;
    InvokeRepeating("scoreUpdate", 1.0f, 0.5f);
}
void Update () {
    scoreText.text = "Score: " + score; //this is the line. If I erase this the error will disappear
    }
void scoreUpdate () {
    if (gameOver == false) {
        score += 1;
        }
    }

If I remove it, the error will disappear. It's not causing malfunctions or anything, I am just curious cos I am willing to learn. Please help me guys

Body:
Make sure that your gameObject isn't empty, the gameObject won't be selected by magic! So try this

public Text scoreText;
private score;

void Start() {
  score = 5; //example
}

void Update() {
    scoreText.text = "Score: " + score;
}

After that, you will need to assign your public gameObject and text to your script, so select the instance you gave your script and check in the inspector, you will see [none(Text)], click on it and select your UItext

Have fun!