问:
How do I update a fields in table with strings randomly selected from a known list?
I have a table named "buildings" that contains a varchar(50) field named "use".  The table already has several thousand records, however the "use" values are all null.  I would like to update these this table with randomly chosen values from a list of strings (e.g., warehouse, office, market, retail, workshop). I would also like to leave some of these null to emulate real world usage.

How can I update a field in a table with strings randomly selected from a known list?

答:
It's not random, but this is a nice and easy way to do it, provided you have a realtively uniform distribution of IDs:

```<code>UPDATE Buildings SET Use = 'warehouse' WHERE ID % 6 = 0
UPDATE Buildings SET Use = 'office'    WHERE ID % 6 = 1
UPDATE Buildings SET Use = 'market'    WHERE ID % 6 = 2
UPDATE Buildings SET Use = 'retail'    WHERE ID % 6 = 3
UPDATE Buildings SET Use = 'workshop'  WHERE ID % 6 = 4
UPDATE Buildings SET Use = NULL        WHERE ID % 6 = 5
</code>```

This is almost certainly going to be easier and faster than a "random" approach. Then again, it might not be random enough.

OwnerDisplayName: Ryan Taylor

Body:
It's not random, but this is a nice and easy way to do it, provided you have a realtively uniform distribution of IDs:

UPDATE Buildings SET Use = 'warehouse' WHERE ID % 6 = 0
UPDATE Buildings SET Use = 'office'    WHERE ID % 6 = 1
UPDATE Buildings SET Use = 'market'    WHERE ID % 6 = 2
UPDATE Buildings SET Use = 'retail'    WHERE ID % 6 = 3
UPDATE Buildings SET Use = 'workshop'  WHERE ID % 6 = 4
UPDATE Buildings SET Use = NULL        WHERE ID % 6 = 5

This is almost certainly going to be easier and faster than a "random" approach. Then again, it might not be random enough.

OwnerDisplayName: Michael Haren


来源: stackexchange

问:
How to extract HTTP status code from the RestTemplate call to a URL?
I am using RestTemplate to make an HTTP call to our service which returns a simple JSON response. I don't need to parse that JSON at all. I just need to return whatever I am getting back from that service.

So I am mapping that to String.class and returning the actual JSON response as a string.

```<code>RestTemplate restTemplate = new RestTemplate();

String response = restTemplate.getForObject(url, String.class);

return response;
</code>```

Now the question is -

I am trying to extract HTTP Status codes after hitting the URL. How can I extract HTTP Status code from the above code? Do I need to make any change into that in the way I doing it currently?

Update:-

This is what I have tried and I am able to get the response back and status code as well. But do I always need to set HttpHeaders and Entity object like below I am doing it?

```<code>    RestTemplate restTemplate = new RestTemplate();

    //and do I need this JSON media type for my use case?
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    //set my entity
    HttpEntity<Object> entity = new HttpEntity<Object>(headers);

    ResponseEntity<String> out = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

    System.out.println(out.getBody());
    System.out.println(out.getStatusCode());
</code>```

Couple of question -  Do I need to have MediaType.APPLICATION_JSON as I am just making a call to url which returns a response back, it can return either JSON or XML or simple string.

答:
There can be some slightly trickier use cases someone might fall in (as I did). Consider the following:

Supporting a Page object in order to use it with RestTemplate and ParameterizedTypeReference:

RestPageResponse:

```<code>import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

public class RestResponsePage<T> extends PageImpl<T>{

  private static final long serialVersionUID = 3248189030448292002L;

  public RestResponsePage(List<T> content, Pageable pageable, long total) {
    super(content, pageable, total);
  }

  public RestResponsePage(List<T> content) {
    super(content);
  }

  public RestResponsePage() {
    super(new ArrayList<T>());
  }

}
</code>```

Using ParameterizedTypeReference will yield the following:

```<code>ParameterizedTypeReference<RestResponsePage<MyObject>> responseType =
new ParameterizedTypeReference<RestResponsePage<MyObject>>() {};
HttpEntity<RestResponsePage<MyObject>> response = restTemplate.exchange(oauthUrl, HttpMethod.GET, entity, responseType);
</code>```

Calling #exchange:

```<code>HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<?> entity = new HttpEntity<>(headers);

response = restTemplate.exchange("localhost:8080/example", HttpMethod.GET, entity, responseType);
</code>```

Now here is the "tricky" part.

Trying to call exchange's getStatusCode will be impossible because the compiler, unfortunately, will be unaware of the "intended" type of response.

That is because generics are implemented via type erasure which removes all information regarding generic types during compilation (read more - source)

((ResponseEntity<RestResponsePage<MyObject>>) response).getStatusCode()

In this case, you have to explicitly cast the variable to the desired Class to get the statusCode (and/or other attributes)!

ContentLicense: CC BY-SA 3.0

Body:
I am using RestTemplate to make an HTTP call to our service which returns a simple JSON response. I don't need to parse that JSON at all. I just need to return whatever I am getting back from that service.

So I am mapping that to String.class and returning the actual JSON response as a string.

RestTemplate restTemplate = new RestTemplate();

String response = restTemplate.getForObject(url, String.class);

return response;

Now the question is -

I am trying to extract HTTP Status codes after hitting the URL. How can I extract HTTP Status code from the above code? Do I need to make any change into that in the way I doing it currently?

Update:-

This is what I have tried and I am able to get the response back and status code as well. But do I always need to set HttpHeaders and Entity object like below I am doing it?

    RestTemplate restTemplate = new RestTemplate();

    //and do I need this JSON media type for my use case?
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    //set my entity
    HttpEntity<Object> entity = new HttpEntity<Object>(headers);

    ResponseEntity<String> out = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

    System.out.println(out.getBody());
    System.out.println(out.getStatusCode());

Couple of question -  Do I need to have MediaType.APPLICATION_JSON as I am just making a call to url which returns a response back, it can return either JSON or XML or simple string.

Body:
There can be some slightly trickier use cases someone might fall in (as I did). Consider the following:

Supporting a Page object in order to use it with RestTemplate and ParameterizedTypeReference:

RestPageResponse:

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

public class RestResponsePage<T> extends PageImpl<T>{

  private static final long serialVersionUID = 3248189030448292002L;

  public RestResponsePage(List<T> content, Pageable pageable, long total) {
    super(content, pageable, total);
  }

  public RestResponsePage(List<T> content) {
    super(content);
  }

  public RestResponsePage() {
    super(new ArrayList<T>());
  }

}

Using ParameterizedTypeReference will yield the following:

ParameterizedTypeReference<RestResponsePage<MyObject>> responseType =
new ParameterizedTypeReference<RestResponsePage<MyObject>>() {};
HttpEntity<RestResponsePage<MyObject>> response = restTemplate.exchange(oauthUrl, HttpMethod.GET, entity, responseType);

Calling #exchange:

HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<?> entity = new HttpEntity<>(headers);

response = restTemplate.exchange("localhost:8080/example", HttpMethod.GET, entity, responseType);

Now here is the "tricky" part.

Trying to call exchange's getStatusCode will be impossible because the compiler, unfortunately, will be unaware of the "intended" type of response.

That is because generics are implemented via type erasure which removes all information regarding generic types during compilation (read more - source)

((ResponseEntity<RestResponsePage<MyObject>>) response).getStatusCode()

In this case, you have to explicitly cast the variable to the desired Class to get the statusCode (and/or other attributes)!


问:
Should I use std::for_each?
I'm always trying to learn more about the languages I use (different styles, frameworks, patterns, etc). I've noticed that I never use std::for_each so I thought that perhaps I should start. The goal in such cases is to expand my mind and not to improve the code in some measure (readability, expressiveness, compactness, etc).

So with that context in mind, is a good idea to use std::for_each for simple tasks like, say, printing out a vector:

```<code>for_each(v.begin(), v.end(), [](int n) { cout << n << endl; }
</code>```

(The [](int n) being a lambda function). Instead of:

```<code>for(int i=0; i<v.size(); i++) { cout << v[i] << endl; }
</code>```

I hope this question doesn't seem pointless. I guess it almost asks a larger question... should an intermediate programmer use a language feature even though he doesn't really need to at this time but just so that he can understand the feature better for a time that may actually greatly benefit from it. Although this larger question has probably already been asked (e.g. here).

答:
You can use for loop scoping C++11

For example:

```<code> T arr[5];
 for (T & x : arr) //use reference if you want write data
 {
 //something stuff...
 }
</code>```

Where T is every type you want.

It works for every containers in STL and classic arrays.

Title: Should I use std::for_each?

Body:
I'm always trying to learn more about the languages I use (different styles, frameworks, patterns, etc). I've noticed that I never use std::for_each so I thought that perhaps I should start. The goal in such cases is to expand my mind and not to improve the code in some measure (readability, expressiveness, compactness, etc).

So with that context in mind, is a good idea to use std::for_each for simple tasks like, say, printing out a vector:

for_each(v.begin(), v.end(), [](int n) { cout << n << endl; }

(The [](int n) being a lambda function). Instead of:

for(int i=0; i<v.size(); i++) { cout << v[i] << endl; }

I hope this question doesn't seem pointless. I guess it almost asks a larger question... should an intermediate programmer use a language feature even though he doesn't really need to at this time but just so that he can understand the feature better for a time that may actually greatly benefit from it. Although this larger question has probably already been asked (e.g. here).

Body:
You can use for loop scoping C++11

For example:

 T arr[5];
 for (T & x : arr) //use reference if you want write data
 {
 //something stuff...
 }

Where T is every type you want.

It works for every containers in STL and classic arrays.

ContentLicense: CC BY-SA 4.0


问:
Select users in relation with theire other table on rails
My users have one to many relation with my table "Bien" i want select only users who have biens in my result page

My controller is like this

```<code>def search
    @users = User.all
    @biens = Bien.near(params[:location], 3, units: :km).where(room_type: params[:room_type], nb_piece: params[:nb_piece])
    @hash = Gmaps4rails.build_markers(@bien) do |bien, marker|
      marker.lat @bien.latitude
      marker.lng @bien.longitude
    end
  end
</code>```

I want select only users who have biens.near(....)
I try many solutions but i want know the good solution to get it

Thanks

答:
You can join the User table to the bien table with something like this.
This will give you an inner join which will only show you the intersecting records...

If the user has many biens...

```<code>User.joins(:biens).where(...)
</code>```

If the user has one bien...

```<code>User.joins(:bien).where(...)
</code>```

This will give you a list of users who have biens...

You could then query further on the biens table to your liking:

```<code>User.joins(:biens).where('biens.room_type = ?', params[:room_type])
</code>```

etc.

Body:
My users have one to many relation with my table "Bien" i want select only users who have biens in my result page

My controller is like this

def search
    @users = User.all
    @biens = Bien.near(params[:location], 3, units: :km).where(room_type: params[:room_type], nb_piece: params[:nb_piece])
    @hash = Gmaps4rails.build_markers(@bien) do |bien, marker|
      marker.lat @bien.latitude
      marker.lng @bien.longitude
    end
  end

I want select only users who have biens.near(....)
I try many solutions but i want know the good solution to get it

Thanks

Body:
You can join the User table to the bien table with something like this.
This will give you an inner join which will only show you the intersecting records...

If the user has many biens...

User.joins(:biens).where(...)

If the user has one bien...

User.joins(:bien).where(...)

This will give you a list of users who have biens...

You could then query further on the biens table to your liking:

User.joins(:biens).where('biens.room_type = ?', params[:room_type])

etc.


问:
pyspark : how to count by group when the data is highly skewed?
I am using pyspark and I was able to load my parquet files using

df = sqlContext.read.parquet('/mypath/parquet_01')

the data contains various variables (col1, col2, col3, etc), and I would like to

group by variable col1

count how many obs. there are per group

return the highest 10 groups in terms of counts (and their respective counts)

I do not want to use groupby because the data is very skewed (some col1 groups have a lot of obs). It seems reduceByKey is appropriate here but I am not able to use it correctly..

Any ideas?

Thanks!

答:
Try this:

```<code> df.select('col1').map(lambda x: (x,1)).reduceByKey(lambda a,b: a+b)
</code>```

The map procedure is used to create (key, value) pairs:
The lambda function below is applied to each row of col1,

The transformation looks like this:

```<code> col1   ->  (col1, 1)
  a         (a,1)
  a         (a,1)
  b         (b,1)
  a         (a,1)
  b         (b,1)
</code>```

Now, we call reduceByKey(lambda a,b: a+b) on the key value pairs:
where a, b are values of two (key, value) pairs with the same key, which get's reduced to (key, a+b).

So, (a,1) , (a,1) get's reduced to (a,2) and the process continues until only one 'a' key remains, thus giving us the count of the key 'a'

We will be left with this:

```<code>  col1   ->  (col1, 1)  -> reducedByKey(key,value)
      a         (a,1)      (a,3)
      a         (a,1)      (b,2)
      b         (b,1)
      a         (a,1)
      b         (b,1)
</code>```

I think groupBy should be faster, even if the data is skewed, reduceByKey is probably slower.

I would also try:

```<code> df.groupBy("col1").count()
</code>```

Body:
Try this:

 df.select('col1').map(lambda x: (x,1)).reduceByKey(lambda a,b: a+b)

The map procedure is used to create (key, value) pairs:
The lambda function below is applied to each row of col1,

The transformation looks like this:

 col1   ->  (col1, 1)
  a         (a,1)
  a         (a,1)
  b         (b,1)
  a         (a,1)
  b         (b,1)

Now, we call reduceByKey(lambda a,b: a+b) on the key value pairs:
where a, b are values of two (key, value) pairs with the same key, which get's reduced to (key, a+b).

So, (a,1) , (a,1) get's reduced to (a,2) and the process continues until only one 'a' key remains, thus giving us the count of the key 'a'

We will be left with this:

  col1   ->  (col1, 1)  -> reducedByKey(key,value)
      a         (a,1)      (a,3)
      a         (a,1)      (b,2)
      b         (b,1)
      a         (a,1)
      b         (b,1)

I think groupBy should be faster, even if the data is skewed, reduceByKey is probably slower.

I would also try:

 df.groupBy("col1").count()


问:
Vue - run method for every v-for item
I loop through days in a calendar via v-for:

Over in Firebase, I have events stored. Each event has a date property:

```<code>eVeNtKeY
  date: 12/7/17
</code>```

Now, each day won't have an event but I need to get an event count for each day. I downloaded all the event for the month via Firebase call and have it saved in the Vue data as an array thisMonthsEvent.

```<code>data: {
  thisMonthsEvents: [bunch of firebase data],
  currentMonth: number
}
</code>```

Is there a way to run a method for every repetition of the v-for? In my thinking, I could do something like this:

```<code>    computed: {
        eventsByDay () {
          return this.thisMonthsEvents.filter(function (event) {
            return event.date === this.currentMonth + '-' + Somehow get the day from loop + '-2017'
});
        }
      }
</code>```

答:
Use a method instead of a computed property and call the method directly in the v-for loop, passing in the day variable:

```<code>methods: {
  getEventsByDay(day) {
    return this.thisMonthsEvents.filter(function (event) {
      return event.date === this.currentMonth + '-' + day + '-2017'
    });
  }
}
</code>```

```<code><li v-for="day in daysInMonth">
  {{ getEventsByDay(day) }}
</li>
</code>```

Title: Vue - run method for every v-for item

Body:
I loop through days in a calendar via v-for:

Over in Firebase, I have events stored. Each event has a date property:

eVeNtKeY
  date: 12/7/17

Now, each day won't have an event but I need to get an event count for each day. I downloaded all the event for the month via Firebase call and have it saved in the Vue data as an array thisMonthsEvent.

data: {
  thisMonthsEvents: [bunch of firebase data],
  currentMonth: number
}

Is there a way to run a method for every repetition of the v-for? In my thinking, I could do something like this:

    computed: {
        eventsByDay () {
          return this.thisMonthsEvents.filter(function (event) {
            return event.date === this.currentMonth + '-' + Somehow get the day from loop + '-2017'
});
        }
      }

Body:
Use a method instead of a computed property and call the method directly in the v-for loop, passing in the day variable:

methods: {
  getEventsByDay(day) {
    return this.thisMonthsEvents.filter(function (event) {
      return event.date === this.currentMonth + '-' + day + '-2017'
    });
  }
}

<li v-for="day in daysInMonth">
  {{ getEventsByDay(day) }}
</li>


问:
Chromedriver --screenshot not working in headless mode?
I'm using new chrome driver headless mode (Chrome v59, mac os) with webdriver. but unfortunately, screenshot option given in headless mode is not working for me. following code shows the chrome options configured.

```<code>chromeOptions.addArguments("headless");
chromeOptions.addArguments("disable-gpu");
chromeOptions.addArguments("window-size=1980x960");
chromeOptions.addArguments("screenshot");
</code>```

I'm getting unknown chrome error:

```<code>unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 60.05 seconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'ip-192-168-13-242.ec2.internal', ip: '192.168.13.242', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_51'
Driver info: driver.version: ChromeDriver
        at com.axonix.utilities.SeleniumDriverWrapper.setupNewDriverInstance(SeleniumDriverWrapper.java:78)
        at com.axonix.utilities.SeleniumDriverWrapper.<init>(SeleniumDriverWrapper.java:55)
        at com.axonix.utilities.SeleniumInterface.<init>(SeleniumInterface.java:30)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
        at org.picocontainer.injectors.AbstractInjector.newInstance(AbstractInjector.java:145)
        at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:342)
        at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
        at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
        at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
        at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
        at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
        at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
        at org.picocontainer.DefaultPainer.getComponent(DefaultPicoContainer.java:647)
        at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
        at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
        at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
        at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
        at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
        at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
        at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
        at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
        at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
        at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
        at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
        at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
        at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
        at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
        at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
        at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
        at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
        at cucumber.runtime.Runtime.runStep(Runtime.java:300)
        at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
        at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
        at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
        at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
        at cucumber.runtimee.run(Runtime.java:122)
        at cucumber.api.cli.Main.run(Main.java:36)
        at cucumber.api.cli.Main.main(Main.java:18)
</code>```

答:
The window-size argument expects string format 800,600, try this instead:

```<code>chromeOptions.addArguments("window-size=1980,960");
</code>```

Also, you have a typo in your screenshot argument:

```<code>chromeOptions.addArguments("screenshot");
</code>```

Here's a great reference of all available Chromium command line switches:

https://peter.sh/experiments/chromium-command-line-switches/

Body:
I'm using new chrome driver headless mode (Chrome v59, mac os) with webdriver. but unfortunately, screenshot option given in headless mode is not working for me. following code shows the chrome options configured.

chromeOptions.addArguments("headless");
chromeOptions.addArguments("disable-gpu");
chromeOptions.addArguments("window-size=1980x960");
chromeOptions.addArguments("screenshot");

I'm getting unknown chrome error:

unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 60.05 seconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'ip-192-168-13-242.ec2.internal', ip: '192.168.13.242', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_51'
Driver info: driver.version: ChromeDriver
        at com.axonix.utilities.SeleniumDriverWrapper.setupNewDriverInstance(SeleniumDriverWrapper.java:78)
        at com.axonix.utilities.SeleniumDriverWrapper.<init>(SeleniumDriverWrapper.java:55)
        at com.axonix.utilities.SeleniumInterface.<init>(SeleniumInterface.java:30)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
        at org.picocontainer.injectors.AbstractInjector.newInstance(AbstractInjector.java:145)
        at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:342)
        at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
        at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
        at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
        at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
        at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
        at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
        at org.picocontainer.DefaultPainer.getComponent(DefaultPicoContainer.java:647)
        at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
        at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
        at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
        at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
        at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
        at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
        at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
        at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
        at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
        at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
        at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
        at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
        at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
        at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
        at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
        at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
        at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
        at cucumber.runtime.Runtime.runStep(Runtime.java:300)
        at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
        at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
        at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
        at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
        at cucumber.runtimee.run(Runtime.java:122)
        at cucumber.api.cli.Main.run(Main.java:36)
        at cucumber.api.cli.Main.main(Main.java:18)

Body:
The window-size argument expects string format 800,600, try this instead:

chromeOptions.addArguments("window-size=1980,960");

Also, you have a typo in your screenshot argument:

chromeOptions.addArguments("screenshot");

Here's a great reference of all available Chromium command line switches:

https://peter.sh/experiments/chromium-command-line-switches/


问:
ExecuteNonQuery() ERROR -> The conversion of the nvarchar value '3955811801' overflowed an int column.
My code is as shown below :

```<code>using (SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DarmanConnectionString"].ToString()))
{
    using (SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
    {
        _cmd.CommandType = CommandType.StoredProcedure;
        _cmd.Parameters.Add(new SqlParameter("@Co_ID", int.Parse(Session["Co_ID"].ToString())));

        _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.NVarChar));
        _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

        _conn.Open();
        _cmd.ExecuteNonQuery();

        Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value.ToString());
        lblSumTotalPayShow.Text = result.ToString();

            _conn.Close();
        }
    }
</code>```

my SP is like this :

```<code>create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
As
    -----------------
    Declare @Sum nvarchar(50)
    -----------------
BEGIN
    Select @Sum = convert(nvarchar(50), SUM(TotalPay))
    From Noskheh
    Where (Co_ID = @Co_ID)

    Return @Sum
END
</code>```

and the error is in line (_cmd.ExecuteNonQuery();):

Error:

Sys.WebForms.PageRequestManagerServerErrorException: The conversion of
  the nvarchar value '3955811801' overflowed an int column. The
  'sp_Noskheh_SumOfTotalPay' procedure attempted to return a status of
  NULL, which is not allowed. A status of 0 will be returned instead.

Would you please help me to figure out this problem?

答: If the problem is not the @Co_ID as others indicate, then maybe the SUM(TotalPay) might be equal to your 3.9 billion value.  if the TotalPay column is an integer, the SUM is integer before converting to varchar.

Body:
My code is as shown below :

using (SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DarmanConnectionString"].ToString()))
{
    using (SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
    {
        _cmd.CommandType = CommandType.StoredProcedure;
        _cmd.Parameters.Add(new SqlParameter("@Co_ID", int.Parse(Session["Co_ID"].ToString())));

        _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.NVarChar));
        _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

        _conn.Open();
        _cmd.ExecuteNonQuery();

        Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value.ToString());
        lblSumTotalPayShow.Text = result.ToString();

            _conn.Close();
        }
    }

my SP is like this :

create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
As
    -----------------
    Declare @Sum nvarchar(50)
    -----------------
BEGIN
    Select @Sum = convert(nvarchar(50), SUM(TotalPay))
    From Noskheh
    Where (Co_ID = @Co_ID)

    Return @Sum
END

and the error is in line (_cmd.ExecuteNonQuery();):

Error:

Sys.WebForms.PageRequestManagerServerErrorException: The conversion of
  the nvarchar value '3955811801' overflowed an int column. The
  'sp_Noskheh_SumOfTotalPay' procedure attempted to return a status of
  NULL, which is not allowed. A status of 0 will be returned instead.

Would you please help me to figure out this problem?

ContentLicense: CC BY-SA 2.5


问:
Map Filtered JSON Links to Filter JSON Nodes
I have node and link data for a force directed graph. Links may have num of one, two, or three links between them:

```<code>{"nodes": [{"id": "Michael Scott", "type": "boss"}
          ,{"id": "Jim Halpert", "type": "employee"}
          ,{"id": "Pam Beasley", "type": "employee"}
          ,{"id": "Kevin Malone", "type": "employee"}
          ,{"id": "Angela", "type": "employee"}
          ,{"id": "Dwight Schrute", "type": "employee"}]
,"links": [{"source": "Michael Scott", "target": "Jim Halpert", "num": 1}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "num": 2}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "num": 2}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}]
}
</code>```

I have a dropdown which should drive filtering of nodes and links for a d3 force-directed graph, based on num. I have this code so far to filter the JSON node and link data

```<code>var dropdown = d3.select("#selectLinkNumber")
var change = function() {
d3.selectAll("svg > *").remove()
var val = dropdown.node().options[dropdown.node().selectedIndex].value;

d3.json("test.json", function(error, graph) {
    var filteredLinks = graph.links.filter(d => d.num >= val);
    //Needs some way to map unique source and targets to id in nodes
    var filteredNodes = graph.nodes.filter()//Needs some way to fill node filtering with mapping from filteredLinks
      });

    var filteredGraph = {
          nodes: filteredNodes,
          links: filteredLinks
      };
    //do stuff
    })
}
dropdown.on("change", change)
change();
</code>```

How would I finish the JavaScript array manipulation code to filter out links based on num, and also filter out the corresponding nodes?

答:
You can use the node ids as keys to an object to ensure they're only added once, and the nodes array is only filtered once per id. This assumes no node is linked to itself, but that would be an unusual edge case.

```<code>var filteredNodes = Object.values(filteredLinks.reduce(function(t,v){
  if(!t[v.source]){
    t[v.source] = graph.nodes.filter(o => o.id === v.source)[0]
  }
  if(!t[v.target]){
    t[v.target] = graph.nodes.filter(o => o.id === v.target)[0]
  }
  return t;
},{}))
</code>```

Body:
I have node and link data for a force directed graph. Links may have num of one, two, or three links between them:

{"nodes": [{"id": "Michael Scott", "type": "boss"}
          ,{"id": "Jim Halpert", "type": "employee"}
          ,{"id": "Pam Beasley", "type": "employee"}
          ,{"id": "Kevin Malone", "type": "employee"}
          ,{"id": "Angela", "type": "employee"}
          ,{"id": "Dwight Schrute", "type": "employee"}]
,"links": [{"source": "Michael Scott", "target": "Jim Halpert", "num": 1}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "num": 2}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "num": 2}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}]
}

I have a dropdown which should drive filtering of nodes and links for a d3 force-directed graph, based on num. I have this code so far to filter the JSON node and link data

var dropdown = d3.select("#selectLinkNumber")
var change = function() {
d3.selectAll("svg > *").remove()
var val = dropdown.node().options[dropdown.node().selectedIndex].value;

d3.json("test.json", function(error, graph) {
    var filteredLinks = graph.links.filter(d => d.num >= val);
    //Needs some way to map unique source and targets to id in nodes
    var filteredNodes = graph.nodes.filter()//Needs some way to fill node filtering with mapping from filteredLinks
      });

    var filteredGraph = {
          nodes: filteredNodes,
          links: filteredLinks
      };
    //do stuff
    })
}
dropdown.on("change", change)
change();

How would I finish the JavaScript array manipulation code to filter out links based on num, and also filter out the corresponding nodes?

Body:
You can use the node ids as keys to an object to ensure they're only added once, and the nodes array is only filtered once per id. This assumes no node is linked to itself, but that would be an unusual edge case.

var filteredNodes = Object.values(filteredLinks.reduce(function(t,v){
  if(!t[v.source]){
    t[v.source] = graph.nodes.filter(o => o.id === v.source)[0]
  }
  if(!t[v.target]){
    t[v.target] = graph.nodes.filter(o => o.id === v.target)[0]
  }
  return t;
},{}))


问:
Modify groovy.util.slurpersupport.NodeChild in grails
Is it possible to append a node in
groovy.util.slurpersupport.NodeChild in Grails?

AppendNode does not work.

Do I have to use xmlparser or xmlslurper?

Best regards,
Peter

答:
It's definitely possible!  appendNode works but it's not especially obvious at first how to make it work.

In this example, we're storing HTML of a table in an object.  We'll parse that into a Node and NodeChild(ren), then append rows to it.  You could start at the second line of code if you already have your NodeChild, but I wanted to show how I got there in this example.

```<code>def tableContent = new XmlSlurper().parseText(table.htmlContent)

tableContent.tbody.appendNode({
  tr(class: "appended", "data-uuid": UUID.randomUUID().toString()) {
    tableContent.thead.tr.th.each {
      td {}
    }
  }
})
</code>```

Note that you can also use .replaceNode instead of .appendNode, if you want to replace an existing node.  Finally, you can use mkp.yield within this whole block to output raw data.

In the end, we can get our HTML back using

```<code>String tableString = new StreamingMarkupBuilder().bind { mkp.yield tableContent }
</code>```

and then continue to do whatever we need to with it.

Body:
It's definitely possible!  appendNode works but it's not especially obvious at first how to make it work.

In this example, we're storing HTML of a table in an object.  We'll parse that into a Node and NodeChild(ren), then append rows to it.  You could start at the second line of code if you already have your NodeChild, but I wanted to show how I got there in this example.

def tableContent = new XmlSlurper().parseText(table.htmlContent)

tableContent.tbody.appendNode({
  tr(class: "appended", "data-uuid": UUID.randomUUID().toString()) {
    tableContent.thead.tr.th.each {
      td {}
    }
  }
})

Note that you can also use .replaceNode instead of .appendNode, if you want to replace an existing node.  Finally, you can use mkp.yield within this whole block to output raw data.

In the end, we can get our HTML back using

String tableString = new StreamingMarkupBuilder().bind { mkp.yield tableContent }

and then continue to do whatever we need to with it.


问:
Laravel 5 getting ID from URL
I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.

```<code>@foreach ($patients as $patient)
    <tr>
        <td>{{ $patient->pID }}</td>
        <td>{{ $patient->pName }}</td>
        <td>{{ $patient->pAddress }}</td>
        <td>{{ $patient->pBday }}</td>
        <td>{{ $patient->pPhone}}</td>
        <td>{{ $patient->pEcon }}</td>
        <td>{{ $patient->pDreg }}</td>
        <td></td>
        <td>
            <a href="{{ URL::to('visit/'.$patient->pID) }}">
                <img src="../images/viewvisit.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('addeditvisit/'.$patient->pID) }}">
                <img src="../images/visit.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('editpatient/'.$patient->pID) }}">
                <img src="../images/update.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('deletepatient/'.$patient->pID) }}">
                <img src="../images/delete.png" style="width:30px; height:30px;">
            </a>
        </td>
    </tr>
@endforeach
</code>```

what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.

I'm currently stuck with this controller function.

```<code>public function index(Request $request) {

    $doctors = Doctor::where('dStatus', 0)
        ->lists('dName', 'dID');
    $beds = Bed::where('bStatus', 0)
        ->lists('bName', 'bID');
    $patient = Patient::patient();
    // $uri = $request->path('patient');

    return View::make('pages.addeditvisit', [
        'doctors'=>$doctors,
        'beds'=>$beds,
        'patient'=>$patient->pID
    ]);
}
</code>```

答:
This is late. But for the benefit of others like me;

If you do not have to do it in a method like the answers above have shown, As of Laravel 5.0 (Not sure about previous versions), you can do

```<code>$request->route('id');
</code>```

That returns the value of the id parameter on the route.

Title: Laravel 5 getting ID from URL

Body:
I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.

@foreach ($patients as $patient)

        {{ $patient->pID }}
        {{ $patient->pName }}
        {{ $patient->pAddress }}
        {{ $patient->pBday }}
        {{ $patient->pPhone}}
        {{ $patient->pEcon }}
        {{ $patient->pDreg }}

            pID) }}">

            pID) }}">

            pID) }}">

            pID) }}">

@endforeach

what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.

I'm currently stuck with this controller function.

public function index(Request $request) {

    $doctors = Doctor::where('dStatus', 0)
        ->lists('dName', 'dID');
    $beds = Bed::where('bStatus', 0)
        ->lists('bName', 'bID');
    $patient = Patient::patient();
    // $uri = $request->path('patient');

    return View::make('pages.addeditvisit', [
        'doctors'=>$doctors,
        'beds'=>$beds,
        'patient'=>$patient->pID
    ]);
}

Body:
This is late. But for the benefit of others like me;

If you do not have to do it in a method like the answers above have shown, As of Laravel 5.0 (Not sure about previous versions), you can do

$request->route('id');

That returns the value of the id parameter on the route.


问:
Build (make) lib every time, recompile project only if lib is newer
I have the following project structure:

```<code>lib/
    Makefile
    src/...
    inc/...
    build/
        inc/...
        lib/libmylib.a
subproj1/
    src/main.cpp
    Makefile
</code>```

The Makefile in the lib folder is designed to create the file libmylib.a and copy the relevant header files to the build/inc folder.

I want the Makefile in subproj1 to always call make -C ../lib, but only re-compile file if headers have changed, and re-link only if necessary (one object file or libmylib.a is newer).

I have the following (non-defined variables such as CC are defined in another file):

```<code>LIBDIR = ../lib
SRCDIR = src
OBJDIR = obj
SRCS = $(SRCDIR)/main.cpp

MAIN=myexe

OBJS = $(SRCS:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
DEPS = $(OBJS:.o=.d)

all: $(MAIN)

debug: CFLAGS += -g -DDEBUG
debug: LFLAGS += -g
debug: $(MAIN)

$(MAIN): $(OBJS) $(LIBDIR)/build/lib/libmylib.a
    $(CC) $^ -o $@ $(LIBS) $(LFLAGS)

$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(LIBDIR)/build/lib/libmylib.a
    mkdir -p $(OBJDIR)
    $(CC) -c -o $@ $(CFLAGS) $(INCS) -MD -MF $(patsubst %.o, %.d, $@) $<

$(LIBDIR)/build/lib/libmylib.a:
    make -C $(LIBDIR)

-include $(DEPS)

.PHONY: clean $(LIBDIR)/build/lib/libmylib.a

clean:
    $(RM) obj/* $(MAIN)
</code>```

The above will re-compile main.cpp even if nothing has changed in the lib folder. If I remove $(LIBDIR)/build/lib/libmylib.a from the $(OBJDIR)/%.o rule, the .cpp file will not be re-compiled if a header changed (I would need to run make twice).

Is there a way to have the .cpp files in subproj1 being compiled only if the header files in lib have changed (or if the .cpp files themselves have changed), and to get myexe built only if one of the .cpp has been re-compiled (newer .o) or if libmylib.a is newer?

答:
This might be a bit cleaner.

```<code>LIBDIR = ../lib
SRCDIR = src
OBJDIR = obj
SRCS = $(SRCDIR)/main.cpp

MAIN=myexe

OBJS = $(SRCS:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
DEPS = $(OBJS:.o=.d)

all: makelib
    $(MAKE) $(MAIN)

debug: CFLAGS += -g -DDEBUG
debug: LFLAGS += -g
debug: $(MAIN)

$(MAIN): $(OBJS)
    $(CC) $^ -o $@ $(LIBS) $(LFLAGS)

$(OBJDIR)/%.o: $(SRCDIR)/%.cpp
    mkdir -p $(OBJDIR)
    $(CC) -c -o $@ $(CFLAGS) $(INCS) -MD -MF $(patsubst %.o, %.d, $@) $<

makelib:
    make -C $(LIBDIR)

-include $(DEPS)

.PHONY: clean makelib

clean:
    $(RM) obj/* $(MAIN)
</code>```

The main target all requires makelib to be built, and then it recursively calls itself for the target $(MAIN) (so all of $(MAIN)'s dependencies will be recalculated after makelib has finished building).

Body:
I have the following project structure:

lib/
    Makefile
    src/...
    inc/...
    build/
        inc/...
        lib/libmylib.a
subproj1/
    src/main.cpp
    Makefile

The Makefile in the lib folder is designed to create the file libmylib.a and copy the relevant header files to the build/inc folder.

I want the Makefile in subproj1 to always call make -C ../lib, but only re-compile file if headers have changed, and re-link only if necessary (one object file or libmylib.a is newer).

I have the following (non-defined variables such as CC are defined in another file):

LIBDIR = ../lib
SRCDIR = src
OBJDIR = obj
SRCS = $(SRCDIR)/main.cpp

MAIN=myexe

OBJS = $(SRCS:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
DEPS = $(OBJS:.o=.d)

all: $(MAIN)

debug: CFLAGS += -g -DDEBUG
debug: LFLAGS += -g
debug: $(MAIN)

$(MAIN): $(OBJS) $(LIBDIR)/build/lib/libmylib.a
    $(CC) $^ -o $@ $(LIBS) $(LFLAGS)

$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(LIBDIR)/build/lib/libmylib.a
    mkdir -p $(OBJDIR)
    $(CC) -c -o $@ $(CFLAGS) $(INCS) -MD -MF $(patsubst %.o, %.d, $@) $<

$(LIBDIR)/build/lib/libmylib.a:
    make -C $(LIBDIR)

-include $(DEPS)

.PHONY: clean $(LIBDIR)/build/lib/libmylib.a

clean:
    $(RM) obj/* $(MAIN)

The above will re-compile main.cpp even if nothing has changed in the lib folder. If I remove $(LIBDIR)/build/lib/libmylib.a from the $(OBJDIR)/%.o rule, the .cpp file will not be re-compiled if a header changed (I would need to run make twice).

Is there a way to have the .cpp files in subproj1 being compiled only if the header files in lib have changed (or if the .cpp files themselves have changed), and to get myexe built only if one of the .cpp has been re-compiled (newer .o) or if libmylib.a is newer?

Body:
This might be a bit cleaner.

LIBDIR = ../lib
SRCDIR = src
OBJDIR = obj
SRCS = $(SRCDIR)/main.cpp

MAIN=myexe

OBJS = $(SRCS:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
DEPS = $(OBJS:.o=.d)

all: makelib
    $(MAKE) $(MAIN)

debug: CFLAGS += -g -DDEBUG
debug: LFLAGS += -g
debug: $(MAIN)

$(MAIN): $(OBJS)
    $(CC) $^ -o $@ $(LIBS) $(LFLAGS)

$(OBJDIR)/%.o: $(SRCDIR)/%.cpp
    mkdir -p $(OBJDIR)
    $(CC) -c -o $@ $(CFLAGS) $(INCS) -MD -MF $(patsubst %.o, %.d, $@) $<

makelib:
    make -C $(LIBDIR)

-include $(DEPS)

.PHONY: clean makelib

clean:
    $(RM) obj/* $(MAIN)

The main target all requires makelib to be built, and then it recursively calls itself for the target $(MAIN) (so all of $(MAIN)'s dependencies will be recalculated after makelib has finished building).


问:
Pandas time Slices
I am trying to read a csv and then return a dataframe based off a time slice.

```<code>Date    Time    Transaction No.
7/3/2017    15:26:54    2141439
7/3/2017    15:26:44    2142226
7/3/2017    15:25:26    2132076
7/3/2017    15:24:17    2141038
7/3/2017    15:20:55    2140073
7/3/2017    15:16:28    2133436
7/3/2017    15:10:48    2134561
7/3/2017    14:40:26    2125436
7/3/2017    14:35:50    2133569
7/3/2017    14:33:18    2126370
7/3/2017    14:31:42    2132945
</code>```

Above is what my csv looks like I am trying the following:

```<code>df = pd.read_csv('test_file.csv',parse_dates=[['Date', 'Time']])
</code>```

I would want to return only values between 14:30 and 15:00. I tried adding index_col =[0] to the read_csv function but I am getting a little lost of how to return the data I am looking. My initial thought was to make my index be a datetime index and use the between function to get what I desired but I can't seem to make it work.

Title: Pandas time Slices

Body:
I am trying to read a csv and then return a dataframe based off a time slice.

Date    Time    Transaction No.
7/3/2017    15:26:54    2141439
7/3/2017    15:26:44    2142226
7/3/2017    15:25:26    2132076
7/3/2017    15:24:17    2141038
7/3/2017    15:20:55    2140073
7/3/2017    15:16:28    2133436
7/3/2017    15:10:48    2134561
7/3/2017    14:40:26    2125436
7/3/2017    14:35:50    2133569
7/3/2017    14:33:18    2126370
7/3/2017    14:31:42    2132945

Above is what my csv looks like I am trying the following:

df = pd.read_csv('test_file.csv',parse_dates=[['Date', 'Time']])

I would want to return only values between 14:30 and 15:00. I tried adding index_col =[0] to the read_csv function but I am getting a little lost of how to return the data I am looking. My initial thought was to make my index be a datetime index and use the between function to get what I desired but I can't seem to make it work.

Body:
Use parameter index_col for DatetimeIndex and then filter by between_time:

df = pd.read_csv('test_file.csv',index_col=['Date_Time'], parse_dates=[['Date', 'Time']])
print (df)
                     Transaction No.
Date_Time
2017-07-03 15:26:54          2141439
2017-07-03 15:26:44          2142226
2017-07-03 15:25:26          2132076
2017-07-03 15:24:17          2141038
2017-07-03 15:20:55          2140073
2017-07-03 15:16:28          2133436
2017-07-03 15:10:48          2134561
2017-07-03 14:40:26          2125436
2017-07-03 14:35:50          2133569
2017-07-03 14:33:18          2126370
2017-07-03 14:31:42          2132945

df = df.between_time('14:30', '15:00')
print (df)
                     Transaction No.
Date_Time
2017-07-03 14:40:26          2125436
2017-07-03 14:35:50          2133569
2017-07-03 14:33:18          2126370
2017-07-03 14:31:42          2132945


问:
Why does my url spits out the two // at the end?
I am very new to React so bear with me here. I have this button here:

```<code>let showButton
if (schema.type === 'belongs_to') {
  showButton = (
    <Link to={['collections', 'locks', this.props.collectionName]}>
      <button>Visa</button>
    </Link>
  )
}
</code>```

This button will redirect to this URL: http://localhost:3000/#/collections/locks/ and there is nothing wrong with that, but when I'm adding this: this.props.id which is a legit prop, but the url I get is this: http://localhost:3000/#/collections/locks//. Notice the two // at the end.

My Question

Why does my url spits out the two // at the end? Is it because this.props.id is empty? As I said, I am very new to this. Thankful for all the support!

Code:

I just want to say that I'm maintaining this project, so all of the code is not written by me, therefor I might not know every little line.

However.. The this.props.id if from here:

```<code>class DeleteDocument extends Component {
  constructor(props) {
    super(props)
    this.state = { confirmed: false }
  }
  render() {
    return (
      <div className="DeleteDocument">
        <div className="box">
          <div className="title">
            Är du säker på att du vill ta bort dokumentet?
          </div>
          <label>
            <input
              type="checkbox"
              value={this.state.confirmed}
              onChange={e =>
                this.setState({ confirmed: !this.state.confirmed })}
            />
            Ja, jag är säker
          </label>
          <div className="box" />
        </div>
        <div style={{ marginTop: '20px' }}>
          <button
            disabled={!this.state.confirmed}
            onClick={this.props.deleteDocument}
          >
            Ta bort
          </button>
          <div style={{ padding: '15px', borderBottom: '1px solid #ccc' }}>
            <Link to={'/collections/locks/${this.props.id}'}> HERE IT IS
              <button>Avbryt</button>
            </Link>
          </div>
        </div>
      </div>
    )
  }
}
</code>```

So I made a decision to use the same props because it's working here and the naming of it seemed to suit my use for it (don't know if this makes sense).

答: Seems you id - is empty string. So you need to share code where you use this.props.id</p>

Body:
I am very new to React so bear with me here. I have this button here:

let showButton
if (schema.type === 'belongs_to') {
  showButton = (
    <Link to={['collections', 'locks', this.props.collectionName]}>
      <button>Visa</button>
    </Link>
  )
}

This button will redirect to this URL: http://localhost:3000/#/collections/locks/ and there is nothing wrong with that, but when I'm adding this: this.props.id which is a legit prop, but the url I get is this: http://localhost:3000/#/collections/locks//. Notice the two // at the end.

My Question

Why does my url spits out the two // at the end? Is it because this.props.id is empty? As I said, I am very new to this. Thankful for all the support!

Code:

I just want to say that I'm maintaining this project, so all of the code is not written by me, therefor I might not know every little line.

However.. The this.props.id if from here:

class DeleteDocument extends Component {
  constructor(props) {
    super(props)
    this.state = { confirmed: false }
  }
  render() {
    return (

            Är du säker på att du vill ta bort dokumentet?

            <input
              type="checkbox"
              value={this.state.confirmed}
              onChange={e =>
                this.setState({ confirmed: !this.state.confirmed })}
            />
            Ja, jag är säker

          <button
            disabled={!this.state.confirmed}
            onClick={this.props.deleteDocument}
          >
            Ta bort
          </button>

            <Link to={'/collections/locks/${this.props.id}'}> HERE IT IS
              <button>Avbryt</button>
            </Link>

    )
  }
}

So I made a decision to use the same props because it's working here and the naming of it seemed to suit my use for it (don't know if this makes sense).


问:
"functions have a __get__() method so that they can be converted to a method when accessed as attributes."
According to  Python's  Descriptor HowTo Guide

functions have a __get__() method so that they can be converted to a method when accessed as attributes.

does

The non-data descriptor transforms an obj.f(*args) call into f(obj,*args). Calling klass.f(*args) becomes f(*args).

mean that

obj.f(*args) is converted to f(obj,*args), and klass.f(*args) to f(*args)?

obj.f(*args) and klass.f(*args) are function calls, and f(obj,*args) and f(*args) method calls? I feel the opposites are true: obj.f(*args) and klass.f(*args) are method calls, and f(obj,*args) and f(*args)  function calls.

Thanks.

答:
obj.f(*args) is converted to f(obj,*args), and klass.f(*args) to f(*args)?

Yes.  In Python 3, though, klass.f(*args), is not "converted" because unbound methods no longer exists, so klass.f is just plain f.

obj.f(*args) and klass.f(*args) are function calls, and f(obj,*args) and f(*args) method calls?

No.  f is a function.  When that function is accessed as an attribute of an instance, as in obj.f, the result is a method object.  So obj.f(*args) is a call on the method object.  The method object underlyingly converts that into the function call f(obj, *args), as described above.  Also, as described above, klass.f in Python 3 is just a plain function, so both klass.f(*args) and f(*args) are equivalent.

I find it is best not to get too hung up on the distinction between "methods" and "functions" in Python.  In Python, unlike some other languages, you can make many kinds of objects callable (by defining a __call__ method).  Because of this, when you see some_obj(), it doesn't mean some_obj must be either a function or a method --- it could be some other callable object --- and so the difference between those two is not so crucial.  Rather, you just want to think about what callable behavior an object defines.  Ultimately all these calls turn into function calls, and "method" is just a name for one particular kind of common callable object, whose callable behavior is that it inserts the self argument before calling the underlying function, as described above.


问:
Sed inside a while read loop
I have been reading a lot of questions and answers about using sed within a while loop. I think I have the command down correctly, but I seem to get no output once I put all of the pieces together. Can someone tell me what I am missing?

I have an input file with 700 variables, one on each line. I need to use each of these 700 variables within a sed command. I run the following command to verify variables are outputting correctly:

cat Input_File.txt | while read var; do echo $var; done

I then try to add in the sed command as follows:

cat Input_File.txt | while read var; do sed -n "/$var/,+10p" Multi-BLAST_5814.txt >> Multi_BLAST_Subset; done

This command leaves me without an error, but a blinking cursor as if this is an infinite loop. It should use each of the 700 variables, find the corresponding line in Multi_BLAST_5814.txt and output the search variable line and the 10 lines after the search term into a new file, appending each as it goes. I can execute the sed command alone with a manually set single value variable successfully and I can execute the while loop successfully using the input file. Anyone have a thought as to why this is not working?

User, that is exactly what I have done to this point.

I have a large text file (128 MB) with BLAST output. I need to search through this for a subset of results for 769 samples (Out of the 5814 samples that are in the file).

I have created a .txt file with those 769 sample names.

To test grep and sed, I manually assigned a variable with one of the 769 samples names I need to search and can get the results I need as follows:

```<code>$ Otu="S41_Folmer_Otu96;size=12;"
$ grep $Otu -A 10 Multi_BLAST_5814.txt
            OR
</code>```

$ sed -n "/$Otu/,+10p" Multi_BLAST_5814.txt

The OUTPUT is exactly what I want as follows:

```<code>    Query= S41_Folmer_Otu96;size=12;
    Length=101

    Sequences producing significant alignments:       Score(Bits)  E Value

    gi|58397553|gb|AY830431.1|  Scopelocheirus schellenbergi clone...   180    1E-41
    gi|306447543|gb|HQ018876.1|  Liposcelis paeta isolate CZ cytoc...   174    6E-40
    gi|306447533|gb|HQ018871.1|  Liposcelis decolor isolate CQ cyt...   104    9E-19
    gi|1043259532|gb|KX130860.1|  Batocera rufomaculata isolate Br...   99    4E-17
    gi|987210821|gb|KR141076.1|  Psocoptera sp. BOLD:ACO1391 vouch...   81    1E-11
</code>```

To Test to make sure the input file contains the correct variables I run the following:

```<code>$ Cat Input_File.txt
$ while read Otu; do echo $Otu; done <Input_File.txt

    S41_Folmer_Otu96;size=12;
    S78_Folmer_Otu15;size=538;
    S73_Leray_Otu52;size=6;
    S66_Leray_Otu93;size=6;
    S10_Folmer_Otu10;size=1612;
    ... All 769 variables
</code>```

Again, this is exactly what I expect and is correct.

But, When I do either of the following commands, nothing is printed to the screen (if I leave off the write file/append action) or to the file I need to create.

$ cat Input_File.txt | while read Otu; do grep "$Otu" -A 10 Multi_BLAST_5814.txt >> Multi_BLAST_Subset.txt; done

$ cat Input_File.txt | while read Otu; do sed -n "/$Otu/,+10p" Multi_BLAST_5814.txt >> Multi_BLAST_Subset.txt; done

Sed hangs and never closes, leaving me at a blinking cursor. Grep finishes but also gives no output. I am at a loss as to why this is not working. Everything works inidividually, so I may be left with manually searching all 769 samples copy/paste.

答:
If you have access to GNU grep no need for a sed command, grep "$var" -A 10 will do the same thing and won't break if $var contains the delimiter used in your sed command.

From man grep :

```<code>   -A NUM, --after-context=NUM
          Print  NUM  lines  of  trailing  context  after  matching lines.
          Places  a  line  containing  a  group  separator  (--)   between
          contiguous  groups  of  matches.  With the -o or --only-matching
          option, this has no effect and a warning is given.
</code>```

Title: Sed inside a while read loop

Body:
I have been reading a lot of questions and answers about using sed within a while loop. I think I have the command down correctly, but I seem to get no output once I put all of the pieces together. Can someone tell me what I am missing?

I have an input file with 700 variables, one on each line. I need to use each of these 700 variables within a sed command. I run the following command to verify variables are outputting correctly:

cat Input_File.txt | while read var; do echo $var; done

I then try to add in the sed command as follows:

cat Input_File.txt | while read var; do sed -n "/$var/,+10p" Multi-BLAST_5814.txt >> Multi_BLAST_Subset; done

This command leaves me without an error, but a blinking cursor as if this is an infinite loop. It should use each of the 700 variables, find the corresponding line in Multi_BLAST_5814.txt and output the search variable line and the 10 lines after the search term into a new file, appending each as it goes. I can execute the sed command alone with a manually set single value variable successfully and I can execute the while loop successfully using the input file. Anyone have a thought as to why this is not working?

User, that is exactly what I have done to this point.

I have a large text file (128 MB) with BLAST output. I need to search through this for a subset of results for 769 samples (Out of the 5814 samples that are in the file).

I have created a .txt file with those 769 sample names.

To test grep and sed, I manually assigned a variable with one of the 769 samples names I need to search and can get the results I need as follows:

$ Otu="S41_Folmer_Otu96;size=12;"
$ grep $Otu -A 10 Multi_BLAST_5814.txt
            OR

$ sed -n "/$Otu/,+10p" Multi_BLAST_5814.txt

The OUTPUT is exactly what I want as follows:

    Query= S41_Folmer_Otu96;size=12;
    Length=101

    Sequences producing significant alignments:       Score(Bits)  E Value

    gi|58397553|gb|AY830431.1|  Scopelocheirus schellenbergi clone...   180    1E-41
    gi|306447543|gb|HQ018876.1|  Liposcelis paeta isolate CZ cytoc...   174    6E-40
    gi|306447533|gb|HQ018871.1|  Liposcelis decolor isolate CQ cyt...   104    9E-19
    gi|1043259532|gb|KX130860.1|  Batocera rufomaculata isolate Br...   99    4E-17
    gi|987210821|gb|KR141076.1|  Psocoptera sp. BOLD:ACO1391 vouch...   81    1E-11

To Test to make sure the input file contains the correct variables I run the following:

$ Cat Input_File.txt
$ while read Otu; do echo $Otu; done <Input_File.txt

    S41_Folmer_Otu96;size=12;
    S78_Folmer_Otu15;size=538;
    S73_Leray_Otu52;size=6;
    S66_Leray_Otu93;size=6;
    S10_Folmer_Otu10;size=1612;
    ... All 769 variables

Again, this is exactly what I expect and is correct.

But, When I do either of the following commands, nothing is printed to the screen (if I leave off the write file/append action) or to the file I need to create.

$ cat Input_File.txt | while read Otu; do grep "$Otu" -A 10 Multi_BLAST_5814.txt >> Multi_BLAST_Subset.txt; done

$ cat Input_File.txt | while read Otu; do sed -n "/$Otu/,+10p" Multi_BLAST_5814.txt >> Multi_BLAST_Subset.txt; done

Sed hangs and never closes, leaving me at a blinking cursor. Grep finishes but also gives no output. I am at a loss as to why this is not working. Everything works inidividually, so I may be left with manually searching all 769 samples copy/paste.

Body:
If you have access to GNU grep no need for a sed command, grep "$var" -A 10 will do the same thing and won't break if $var contains the delimiter used in your sed command.

From man grep :

   -A NUM, --after-context=NUM
          Print  NUM  lines  of  trailing  context  after  matching lines.
          Places  a  line  containing  a  group  separator  (--)   between
          contiguous  groups  of  matches.  With the -o or --only-matching
          option, this has no effect and a warning is given.


问:
When should this-> be used?
I was wondering if this-> should be used both:

```<code>void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}
</code>```

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks

答:
I tend to follow this simple rule of thumbs:

Attributes: no this, if it's not a parameter of the method, then it's obviously an attribute of the class (and I tend to rely on naming convention anyway to distinguish them)

Methods: this->, to distinguish class methods from free-standing functions

The second also brings consistency, since it might be necessary in templated code (and I wrote a lot of it, especially in my pet projects).

The rationale behind this is simple: write as much as necessary to be explicit (ie make the life of your reader easier), but not a stitch more (this would be clutter), which follows Antoine de Saint-Exupery's:

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

Title: When should this-> be used?

Body:
I was wondering if this-> should be used both:

void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks


问:
Get value of another column in an ant.design Table's column?
In my react and ant.design based app, I've a table with the following columns.

```<code>const tableColumns = [{
      title : 'Lorem',
      dataIndex : 'lorem'
      render: text => <a href='#'> {text + ipsum} </a>
    }, {
      title : 'Ipsum',
      dataIndex : 'ipsum'
    }];
</code>```

I want to use value for ipsum i.e. the second column for each row inside render function of the first column. What's the best recommended way in ant.design to fetch second column's value here?

答:
The second argument to the render function is the current record:

```<code>render: (text, row) => <a> {text + row.ipsum} </a>
</code>```

https://ant.design/components/table/#Column

Body:
In my react and ant.design based app, I've a table with the following columns.

const tableColumns = [{
      title : 'Lorem',
      dataIndex : 'lorem'
      render: text =>  {text + ipsum}
    }, {
      title : 'Ipsum',
      dataIndex : 'ipsum'
    }];

I want to use value for ipsum i.e. the second column for each row inside render function of the first column. What's the best recommended way in ant.design to fetch second column's value here?

Body:
The second argument to the render function is the current record:

render: (text, row) => <a> {text + row.ipsum} </a>

https://ant.design/components/table/#Column


问:
Best practice for maintaining lists of redirect urls with IIS 8?
Some website changes caused redirect lists with 400+ URLs. What is the best way to maintain these? Adding them one by one is not a good option. Adding them to the the web-config causes the file to grow to the point of the system being unable to read it.

Is there a way to maintain a separate file with redirects in IIS 8?

答:
From my experience best way is to use rewrite maps:

Create rewriteMaps.config

```<code><rewriteMaps>
    <rewriteMap name="Redirects">
        <add key="/test.aspx" value="/test2.aspx" />
        <add key="/aboutus.aspx" value="/about" />
    </rewriteMap>
</rewriteMaps>
</code>```

Create rewriteRules.config

```<code><rules>
    <rule name="Rule for Redirects">
        <match url=".*" />
        <conditions>
        <add input="{Redirects:{REQUEST_URI}}" pattern="(.+)" />
        </conditions>
        <action type="Redirect" url="{C:1}" appendQueryString="false" />
    </rule>
</rules>
</code>```

In web.config use configSource attribute

```<code><rewrite>
    <rewriteMaps configSource="rewriteMaps.config" />
    <rules configSource="rewriteRules.config" />
</rewrite>
</code>```

Benefits of this structure

Web.config small and clean

You can put complex redirects/rewrites with conditions in rewriteRules.config

You can put simple redirects (redirect pathA to pathB) directly into rewriteMaps.config as key-value pair

Body:
From my experience best way is to use rewrite maps:

Create rewriteMaps.config

<rewriteMaps>
    <rewriteMap name="Redirects">
        <add key="/test.aspx" value="/test2.aspx" />
        <add key="/aboutus.aspx" value="/about" />
    </rewriteMap>
</rewriteMaps>

Create rewriteRules.config

<rules>
    <rule name="Rule for Redirects">
        <match url=".*" />
        <conditions>
        <add input="{Redirects:{REQUEST_URI}}" pattern="(.+)" />
        </conditions>
        <action type="Redirect" url="{C:1}" appendQueryString="false" />
    </rule>
</rules>

In web.config use configSource attribute

<rewrite>
    <rewriteMaps configSource="rewriteMaps.config" />
    <rules configSource="rewriteRules.config" />
</rewrite>

Benefits of this structure

Web.config small and clean

You can put complex redirects/rewrites with conditions in rewriteRules.config

You can put simple redirects (redirect pathA to pathB) directly into rewriteMaps.config as key-value pair


问:
How to push a new page when clicking ion-item and retrieve data
I am using Ionic 2 and a list of clickable ion-item with details arrow:

```<code><ion-item-group>
    <button ion-item (click)="onWhenItemClick()">
      Quand
      <ion-note item-end>{{ date }}</ion-note>
    </button>
    <button ion-item (click)="onWhereItemClick()">
      Où
      <ion-note item-end>{{ location }}</ion-note>
    </button>
  </ion-item-group>
</code>```

As there is this arrow I would expect (as a user) to see a new page sliding from right to left when clicking on of these items.

For your information, each ion-item should bring me to a page that only displays a list of radio items.

I would like to recreate the same mechanisms as a select or a modal but with a page.

So basically I want to push a new page (easy) and be able to pop/dismiss it and handle this dismissal with as function like onDismiss().

How would you do that?
Pushing the new page is not

答: I suggest you to have a look at this amazing tutorial https://www.joshmorony.com/passing-data-between-pages-in-ionic-2/</p>

Body:
I am using Ionic 2 and a list of clickable ion-item with details arrow:

<ion-item-group>
    <button ion-item (click)="onWhenItemClick()">
      Quand
      <ion-note item-end>{{ date }}</ion-note>
    </button>
    <button ion-item (click)="onWhereItemClick()">
      Où
      <ion-note item-end>{{ location }}</ion-note>
    </button>
  </ion-item-group>

As there is this arrow I would expect (as a user) to see a new page sliding from right to left when clicking on of these items.

For your information, each ion-item should bring me to a page that only displays a list of radio items.

I would like to recreate the same mechanisms as a select or a modal but with a page.

So basically I want to push a new page (easy) and be able to pop/dismiss it and handle this dismissal with as function like onDismiss().

How would you do that?
Pushing the new page is not


问:
Could not find default endpoint element
I've added a proxy to a webservice to a VS2008/.NET 3.5 solution. When constructing the client .NET throws this error:

Could not find default endpoint element that references contract 'IMySOAPWebService' in the ServiceModel client configuration section. This might be because no configuaration file was found for your application or because no endpoint element matching this contract could be found in the client element.

Searching for this error tells me to use the full namespace in the contract. Here's my app.config with full namespace:

```<code><client>
  <endpoint address="http://192.168.100.87:7001/soap/IMySOAPWebService"
            binding="basicHttpBinding" bindingConfiguration="IMySOAPWebServicebinding"
            contract="Fusion.DataExchange.Workflows.IMySOAPWebService" name="IMySOAPWebServicePort" />
</client>
</code>```

I'm running XP local (I mention this because a number of Google hits mention win2k3)
The app.config is copied to app.exe.config, so that is also not the problem.

Any clues?

答:
Several responses here hit upon the correct solution when you're facing the mind-numbingly obscure error of referencing the service from a class file: copy service config info into your app.config web.config of your console or windows app.  None of those answers seem to show you what to copy though.  Let's try and correct that.

Here's what I copied out of my class library's config file, into my console app's config file, in order to get around this crazy error for a service I write called "TranslationServiceOutbound".

You basically want everything inside the system.serviceModel section:

```<code>  <system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_ITranslationServiceOutbound" />
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://MyHostName/TranslationServiceOutbound/TranslationServiceOutbound.svc"
    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITranslationServiceOutbound"
    contract="TranslationService.ITranslationServiceOutbound" name="BasicHttpBinding_ITranslationServiceOutbound" />
</client>
</code>```

OwnerDisplayName: Edoode

Title: Could not find default endpoint element

Body:
I've added a proxy to a webservice to a VS2008/.NET 3.5 solution. When constructing the client .NET throws this error:

Could not find default endpoint element that references contract 'IMySOAPWebService' in the ServiceModel client configuration section. This might be because no configuaration file was found for your application or because no endpoint element matching this contract could be found in the client element.

Searching for this error tells me to use the full namespace in the contract. Here's my app.config with full namespace:

<client>
  <endpoint address="http://192.168.100.87:7001/soap/IMySOAPWebService"
            binding="basicHttpBinding" bindingConfiguration="IMySOAPWebServicebinding"
            contract="Fusion.DataExchange.Workflows.IMySOAPWebService" name="IMySOAPWebServicePort" />
</client>

I'm running XP local (I mention this because a number of Google hits mention win2k3)
The app.config is copied to app.exe.config, so that is also not the problem.

Any clues?

Body:
Several responses here hit upon the correct solution when you're facing the mind-numbingly obscure error of referencing the service from a class file: copy service config info into your app.config web.config of your console or windows app.  None of those answers seem to show you what to copy though.  Let's try and correct that.

Here's what I copied out of my class library's config file, into my console app's config file, in order to get around this crazy error for a service I write called "TranslationServiceOutbound".

You basically want everything inside the system.serviceModel section:

  <system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_ITranslationServiceOutbound" />
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://MyHostName/TranslationServiceOutbound/TranslationServiceOutbound.svc"
    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITranslationServiceOutbound"
    contract="TranslationService.ITranslationServiceOutbound" name="BasicHttpBinding_ITranslationServiceOutbound" />
</client>


问:
Setting element href value jQuery
There are a few posts on this already, and this one which couldn't be more simple to follow. For some reason though I can't get the element to link to the href attribute.

This is the class for the element that needs to be linked: .vc_tta-tab:nth-child(1);

There is an anchor on the page #about;

This is the jQuery I'm using:

```<code><script>
jQuery('.vc_tta-tab:nth-child(1)').prop('href','https://example.com/#about');
</script>
</code>```

The idea is to use the .vc_tta-tab:nth-child(1) element to link to the /#about section on the page.

Please can someone help me correct what I'm doing wrong?

答: VDesign is right about using attr instead of prop. For your URL I think you might need the actual page to use the anchor. Like http://example.com/index.html#about instead of http://example.com/#about.

Title: Setting element href value jQuery

Body:
There are a few posts on this already, and this one which couldn't be more simple to follow. For some reason though I can't get the element to link to the href attribute.

This is the class for the element that needs to be linked: .vc_tta-tab:nth-child(1);

There is an anchor on the page #about;

This is the jQuery I'm using:

The idea is to use the .vc_tta-tab:nth-child(1) element to link to the /#about section on the page.

Please can someone help me correct what I'm doing wrong?


问:
Function that counts how often it call another function
I have a 'twice' function that return 2 of the argument passed into it. I also have another function 'runTwice' that counts the number of times it called the 'twice' function (the idea being that I want the 'twice' function to only run 'twice' no matter how often it is called via the 'runTwice' function). Can you please help?

Functions are given below:

var count = 1;

function twice(num){
  return num*2;
}

function runTwice(func){
  if (count<3){
    count++;
    return func;
  } else {
    return 'Function cannot run!';
  }
}

var myFunc = runTwice(twice)

var output = [];

for (var i = 0; i < 3; i++){
  output.push(myFunc(i));
}

console.log(output);```

I would like the output to be [0, 2, 'Function cannot run!'].

I can make this work if I count the 'twice' function directly but I am looking to understand why this doesn't work as presented above.

答:
The function runTwice should return another function that will decide whether to call the function func (using Function.prototype.apply) or to return a string message instead:

function twice(num){
    return num * 2;
}

function runTwice(func){
    var count = 0;                              // this will be trapped in a closure along with func
    return function() {                         // this is the function that gets called
      count++;                                  // it increments its version of the count variable
      if(count <= 2)                            // if count is less than 2
        return func.apply(this, arguments);     // then it calls the function func with whatever arguments passed into it and return the returned value of that call
      return "Not available anymore!";          // otherwise (count > 2), then it returns a string
    }
}

var myFunc = runTwice(twice);

for (var i = 0; i < 3; i++){
    console.log(myFunc(i));
}```
</div>
</div>
</p>

<p><strong>Even better:</strong></p>

<p>You can pass in the number of times allowed as well:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function double(num) {
    return num * 2;
}

function triple(num) {
    return num * 3;
}

function run(func, times){
    var count = 0;                              // this will be trapped in a closure along with func and times
    return function() {                         // this is the function that gets called
      count++;                                  // it increments its version of the count variable
      if(count <= times)                        // if count is less than times
        return func.apply(this, arguments);     // then it calls the function func with whatever arguments passed into it and return the returned value of that call
      return "Not available anymore!";          // otherwise (count > times), then it returns a string
    }
}

var double2times = run(double, 2);              // double2times can only be called 2 times
var triple5times = run(triple, 5);              // triple5times can only be called 5 times

for (var i = 0; i < 10; i++){
    console.log("Double:", double2times(i));
    console.log("Triple:", triple5times(i));
}</code>```

Body:
I have a 'twice' function that return 2 of the argument passed into it. I also have another function 'runTwice' that counts the number of times it called the 'twice' function (the idea being that I want the 'twice' function to only run 'twice' no matter how often it is called via the 'runTwice' function). Can you please help?

Functions are given below:

var count = 1;

function twice(num){
  return num*2;
}

function runTwice(func){
  if (count<3){
    count++;
    return func;
  } else {
    return 'Function cannot run!';
  }
}

var myFunc = runTwice(twice)

var output = [];

for (var i = 0; i < 3; i++){
  output.push(myFunc(i));
}

console.log(output);

I would like the output to be [0, 2, 'Function cannot run!'].

I can make this work if I count the 'twice' function directly but I am looking to understand why this doesn't work as presented above.

Body:
The function runTwice should return another function that will decide whether to call the function func (using Function.prototype.apply) or to return a string message instead:

function twice(num){
    return num * 2;
}

function runTwice(func){
    var count = 0;                              // this will be trapped in a closure along with func
    return function() {                         // this is the function that gets called
      count++;                                  // it increments its version of the count variable
      if(count <= 2)                            // if count is less than 2
        return func.apply(this, arguments);     // then it calls the function func with whatever arguments passed into it and return the returned value of that call
      return "Not available anymore!";          // otherwise (count > 2), then it returns a string
    }
}

var myFunc = runTwice(twice);

for (var i = 0; i < 3; i++){
    console.log(myFunc(i));
}

Even better:

You can pass in the number of times allowed as well:

function double(num) {
    return num * 2;
}

function triple(num) {
    return num * 3;
}

function run(func, times){
    var count = 0;                              // this will be trapped in a closure along with func and times
    return function() {                         // this is the function that gets called
      count++;                                  // it increments its version of the count variable
      if(count <= times)                        // if count is less than times
        return func.apply(this, arguments);     // then it calls the function func with whatever arguments passed into it and return the returned value of that call
      return "Not available anymore!";          // otherwise (count > times), then it returns a string
    }
}

var double2times = run(double, 2);              // double2times can only be called 2 times
var triple5times = run(triple, 5);              // triple5times can only be called 5 times

for (var i = 0; i < 10; i++){
    console.log("Double:", double2times(i));
    console.log("Triple:", triple5times(i));
}


问:
ASP.NET MVC AJAX POST ValidateAntiForgeryToken
With my code i get a internal Server error:

```<code>@using (Html.BeginForm("", "Manage", FormMethod.Post, new { role = "form"}))
{
    @Html.AntiForgeryToken()
}
<script>
function Like(id) {
    var requestData = {
        profileId: id,
        __RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),
    };

    $.ajax({
        url: '/Manage/Like',
        type: 'POST',
        data: JSON.stringify(requestData),
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        error: function (xhr) { alert('Error: ' + xhr.statusText); },
        success: function (result) {},
        async: true,
        processData: false
    });
}
</script>
</code>```

Controller:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Like(string profileId)
{ ... }
</code>```

If i remove [ValidateAntiForgeryToken] everything works fine, but i lose the sercurity. How can i fix the internal server error?

I see in fiddler SyntaxView 2 requests:
/Manage/Like
{"profileId":13,"__RequestVerificationToken":"jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2"}

/Manage
__RequestVerificationToken=MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2

答:
Taking this from a sim. question here include antiforgerytoken in ajax post ASP.NET MVC</p>

```<code>function Like(id) {
 var form = $('form');
 var token = $('input[name="__RequestVerificationToken"]', form).val();
 $.ajax({
    url: '/Manage/Like',
    type: 'POST',
    data: { __RequestVerificationToken: token, profileID: id },
    error: function (xhr) { alert('Error: ' + xhr.statusText); },
    success: function (result) {},
    async: true,
    processData: false
 });
}
</code>```

Body:
With my code i get a internal Server error:

@using (Html.BeginForm("", "Manage", FormMethod.Post, new { role = "form"}))
{
    @Html.AntiForgeryToken()
}

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Like(string profileId)
{ ... }

If i remove [ValidateAntiForgeryToken] everything works fine, but i lose the sercurity. How can i fix the internal server error?

I see in fiddler SyntaxView 2 requests:
/Manage/Like
{"profileId":13,"__RequestVerificationToken":"jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2"}

/Manage
__RequestVerificationToken=MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2

Body:
Taking this from a sim. question here include antiforgerytoken in ajax post ASP.NET MVC

function Like(id) {
 var form = $('form');
 var token = $('input[name="__RequestVerificationToken"]', form).val();
 $.ajax({
    url: '/Manage/Like',
    type: 'POST',
    data: { __RequestVerificationToken: token, profileID: id },
    error: function (xhr) { alert('Error: ' + xhr.statusText); },
    success: function (result) {},
    async: true,
    processData: false
 });
}


问:
How do I align 3 circular images?
So I have this code:

/*--- Circular images --- */
.img-circular1, .img-circular2, .img-circular3{
 width: 200px;
 height: 200px;
 background-size: cover;
 display: block;
  border-radius: 100px;
 -webkit-border-radius: 100px;
 -moz-border-radius: 100px;
 float: left;
 background: red;
}
.img-circular1{
   background-image: url('/Images/learn.jpg');
}
.img-circular2{
   background-image: url('/Images/watch.jpg');
}
.img-circular3{
   background-image: url('/Images/practice.jpg');
}
#container1
{
top: 100px;
    position: relative;
    margin-left:auto;
    margin-right:auto;
    width:70%;
    background-color: green;
    overflow: auto;
    bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container1" style="padding-bottom: 500px;">
<div class="img-circular1"></div>
<div class="img-circular2"></div>
<div class="img-circular3"></div>
<div class="img-circular1"></div>
</div></code>```

I have no managed to get 2 of them to show in a green box. But the third (which I duplicated before and after the other 2) will not show for some reason?

Also, they are not equidistant apart - how can I get them an equal spacing apart?

Please help

NOTE: Instead of images there are red circles, just for visibility reasons.

答:
I updated your code to use FlexBox. Since you want your circles to be equally spaced across the row, float: left won't help much. I had to add a wrapper div around each circle div so that it could expand to fill the space without distorting the circles.

/*--- Circular images --- */

.img-circular1,
.img-circular2,
.img-circular3 {
  width: 200px;
  height: 200px;
  background-size: cover;
  border-radius: 100px;
  -webkit-border-radius: 100px;
  -moz-border-radius: 100px;
  background: red;
  display: block;
  margin: 0 auto;
}

.img-circular1 {
  background-image: url('/Images/learn.jpg');
}

.img-circular2 {
  background-image: url('/Images/watch.jpg');
}

.img-circular3 {
  background-image: url('/Images/practice.jpg');
}

#container1 {
  top: 100px;
  position: relative;
  margin-left: auto;
  margin-right: auto;
  width: 70%;
  background-color: green;
  overflow: auto;
  bottom: 0;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.wrap {
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container1" style="padding-bottom: 500px;">
  <div class="wrap">
    <div class="img-circular1"></div>
  </div>
  <div class="wrap">
    <div class="img-circular2"></div>
  </div>
  <div class="wrap">
    <div class="img-circular3"></div>
  </div>
  <div class="wrap">
    <div class="img-circular1"></div>
  </div>
</div></code>```

Title: How do I align 3 circular images?

Body:
So I have this code:

/*--- Circular images --- */
.img-circular1, .img-circular2, .img-circular3{
 width: 200px;
 height: 200px;
 background-size: cover;
 display: block;
  border-radius: 100px;
 -webkit-border-radius: 100px;
 -moz-border-radius: 100px;
 float: left;
 background: red;
}
.img-circular1{
   background-image: url('/Images/learn.jpg');
}
.img-circular2{
   background-image: url('/Images/watch.jpg');
}
.img-circular3{
   background-image: url('/Images/practice.jpg');
}
#container1
{
top: 100px;
    position: relative;
    margin-left:auto;
    margin-right:auto;
    width:70%;
    background-color: green;
    overflow: auto;
    bottom: 0;
}

I have no managed to get 2 of them to show in a green box. But the third (which I duplicated before and after the other 2) will not show for some reason?

Also, they are not equidistant apart - how can I get them an equal spacing apart?

Please help

NOTE: Instead of images there are red circles, just for visibility reasons.

Body:
I updated your code to use FlexBox. Since you want your circles to be equally spaced across the row, float: left won't help much. I had to add a wrapper div around each circle div so that it could expand to fill the space without distorting the circles.

/*--- Circular images --- */

.img-circular1,
.img-circular2,
.img-circular3 {
  width: 200px;
  height: 200px;
  background-size: cover;
  border-radius: 100px;
  -webkit-border-radius: 100px;
  -moz-border-radius: 100px;
  background: red;
  display: block;
  margin: 0 auto;
}

.img-circular1 {
  background-image: url('/Images/learn.jpg');
}

.img-circular2 {
  background-image: url('/Images/watch.jpg');
}

.img-circular3 {
  background-image: url('/Images/practice.jpg');
}

#container1 {
  top: 100px;
  position: relative;
  margin-left: auto;
  margin-right: auto;
  width: 70%;
  background-color: green;
  overflow: auto;
  bottom: 0;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.wrap {
  flex-grow: 1;
}

<div id="container1" style="padding-bottom: 500px;">
  <div class="wrap">
    <div class="img-circular1"></div>
  </div>
  <div class="wrap">
    <div class="img-circular2"></div>
  </div>
  <div class="wrap">
    <div class="img-circular3"></div>
  </div>
  <div class="wrap">
    <div class="img-circular1"></div>
  </div>
</div>


问:
Setting up Android Development Environment on Windows 7
I want to start learning Android developement. I have a windows 7 Home Premium Operating System. My problem is I am not able to setup the environment of developing android. Here is what I have done till now.

I have installed Java (both 32 bit and 64 bit versions)

I have installed Android SDK (installer_r08-windows.exe)

I have not yet downloaded any tools or platforms or ADT.

I have downloaded 32 bit eclipse. (eclipse-SDK-3.5.1-win32.zip)

I am stuck at this eclipse setup. A strange thing I observed is that, it does not install. When I click on eclipse.exe, it starts running from there only. I am still not sure if my eclipse installation is proper?

So, I assumed that my eclipse is working fine. Then when I try installing new programs in eclipse, eg google plugin, it gives error.

I want to know, where am I going wrong? What mistakes am I doing?
Can anyone guide me with the complete step by step procedure to setup my android development environment on windows 7?

Thanks in advance.

Jay

答: I found I had to relax Windows 7's security settings quite a lot just until Eclipse was fully set up, and then I was able to restore them back to their normal setting.</p>


问:
Using a handle with nested dragula and slice
I am looking to add the use of a handle to the following nested dragula example but it seems impossible.  Any idea how to modify the script for using handles instead of the whole div being draggable:

```<code>(function() {
  dragula([].slice.apply(document.querySelectorAll('.nested')));
})();
</code>```

The full script is here:
https://codepen.io/trzmaxim/pen/GppXGE

Dragula can be found here:
https://bevacqua.github.io/dragula/

Thanks for your consideration!

答:
i just had a look at the docs and found this:

```<code>(function() {
  dragula([].slice.apply(document.querySelectorAll('.nested')),{
     moves: function (el, container, handle) {
       return handle.classList.contains('handle');
     }
  });
})();
</code>```

you just have to add an element with class handle into each item, i tried out with your codepen and it works!

https://codepen.io/anon/pen/RgBNje

Body:
I am looking to add the use of a handle to the following nested dragula example but it seems impossible.  Any idea how to modify the script for using handles instead of the whole div being draggable:

(function() {
  dragula([].slice.apply(document.querySelectorAll('.nested')));
})();

The full script is here:
https://codepen.io/trzmaxim/pen/GppXGE

Dragula can be found here:
https://bevacqua.github.io/dragula/

Thanks for your consideration!

Body:
i just had a look at the docs and found this:

(function() {
  dragula([].slice.apply(document.querySelectorAll('.nested')),{
     moves: function (el, container, handle) {
       return handle.classList.contains('handle');
     }
  });
})();

you just have to add an element with class handle into each item, i tried out with your codepen and it works!

https://codepen.io/anon/pen/RgBNje


问:
control servo motor speed by raspberry pi
How to make servo motor reach the desired angle slowly using raspberry pi with python ?
I tried this , but it seems not to work in all conditions .

```<code>   p = GPIO.PWM(7,50)
   p.start(7.5)
   def servo(angl) :
       try :
               angle_end = angl
               for i in range (1,100) :
                   angle_step_to_end = (i *angle_end)/100
                   duty_cycle =(((12.5-2.5)/(180-0) * angle_step_to_end)+2.5
                   p.ChangeDutyCycle(duty_cycle)
       except KeyboardInterrupt :
                           p.stop()
                           GPIO.cleanup()
</code>```

Is there something more real ?!

答:
Typical hobby servos are designed to rotate as fast as possible to the commanded position.  To get slow movement, you have to slowly change the commanded position.  Without doing a lot of manual calculations, your code appears to be doing that.

Typical values are 1.5 millisecond pulse every 20 ms (7.5%) or so to "center" the servo in its arc of movement.  To move to the extremes, typical values are 1.0 milliseconds at one extreme to 2.0 at the other.

Seeing as 7.5 is the midpoint, I propose you simply call p.ChangeDutyCycle() with values that (as smoothly as you want) vary between 5.0% and 10.0%.  Remembering of course, that the open-loop control of hobby servos is typically governed by a very cheap potentiometer and that super-precise control is not really attainable.

Body:
How to make servo motor reach the desired angle slowly using raspberry pi with python ?
I tried this , but it seems not to work in all conditions .

   p = GPIO.PWM(7,50)
   p.start(7.5)
   def servo(angl) :
       try :
               angle_end = angl
               for i in range (1,100) :
                   angle_step_to_end = (i *angle_end)/100
                   duty_cycle =(((12.5-2.5)/(180-0) * angle_step_to_end)+2.5
                   p.ChangeDutyCycle(duty_cycle)
       except KeyboardInterrupt :
                           p.stop()
                           GPIO.cleanup()

Is there something more real ?!